codexuse-cli 3.6.5 → 3.7.0

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.
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import { $ as encodeUnknownEffect, $i as isFailure, $n as asSome, $o as BaseProto, $r as scoped, $t as runFold, A as NullOr, Aa as gen$1, An as make$20, Ao as getOrThrow, Ar as log$1, At as Size, B as Union, Bi as close, Bn as parseJson, Bo as map$5, Br as onInterrupt, Bt as fromChannel$1, C as Finite, Ca as fiberInterrupt, Ci as catchDone, Cn as offerAll, Co as sort, Cr as forkIn, Ct as assign, D as NonEmptyArray, Da as forkDetach, Di as TaggedError, Dn as unbounded, Do as makeEquivalence$2, Dr as ignoreCause, Dt as FileDescriptor, E as Literals, Ea as forever$1, Ei as Error$1, En as take, Er as ignore, Et as TypeId$16, F as TaggedErrorClass, Fa as scopeAddFinalizerExit, Fi as succeed$2, Fn as badArgument, Fo as getOrElse, Fr as map$3, Ft as decodeText, G as decodeEffect, Gi as fail$4, Gn as encodeBase64Url, Go as make$25, Gr as provideService, Gt as fromReadableStream, H as Void, Ha as sync$1, Hi as provide$2, Hn as InvalidValue$1, Ho as none$3, Hr as orElseSucceed, Ht as fromIterable$1, I as TemplateLiteral, Ii as sync$2, In as systemError, Io as getOrNull, Ir as mapError, J as decodeUnknownEffect, Ja as CurrentLogSpans, Ji as make$26, Jn as addFinalizer$1, Jo as PipeInspectableProto, Jr as runFork, Jt as merge$1, K as decodeExit, Ka as void_$2, Ki as failCause$1, Kn as acquireRelease, Ko as make$31, Kr as provideServices, Kt as isStream, L as Trim, La as sleep$1, Li as unwrap$1, Ln as nominal, Lo as getOrUndefined, Lr as matchCauseEffect, Lt as empty$4, M as Record, Ma as loggerMake, Mi as mergeAll, Mn as makeUnsafe$1, Mo as succeed$3, Mr as logError$1, Mt as make$21, N as String$1, Ni as provide$1, No as filter$1, Nr as logInfo$1, Nt as callback$1, O as NonEmptyString, Oa as formatLabel, Oi as effect, On as publish, Oo as fail$3, Or as interrupt, Ot as FileSystem, P as Struct, Pa as scope, Pi as provideMerge, Pn as BadArgument, Po as fromNullishOr, Pr as logWarning$1, Pt as concat, Q as encodeEffect, Qa as Service, Qi as hasInterrupts$1, Qn as as, Qo as withFiber, Qt as runCollect, R as Tuple, Ra as structuredMessage, Ri as Scope, Rn as transform$1, Ro as isNone, Rr as matchEffect, Rt as fail$5, S as ErrorClass, Sa as defaultLogger$1, Si as zipWith, Sn as offer$1, So as of, Sr as forkDetach$1, St as withDecodingDefault, T as Literal, Ta as fnUntraced$1, Ti as Class, Tn as shutdown, To as map$7, Tr as gen, Tt as Path$1, U as brand, Ua as tracerLogger$1, Ui as _await, Un as makeFormatterDefault, Uo as some, Ur as promise, Ut as fromPubSub, V as Unknown, Va as suspend$1, Vi as make$27, Vn as stringifyJson, Vo as match, Vr as orDie, Vt as fromEffect, W as declare, Wa as uninterruptibleMask, Wi as doneUnsafe, Wn as make$30, Wo as Number$2, Wr as provide, Wt as fromQueue, X as decodeUnknownSync, Xa as DisablePropagation, Xi as succeed$4, Xn as andThen, Xr as runPromiseWith, Xt as onExit, Y as decodeUnknownExit, Ya as MinimumLogLevel, Yi as makeUnsafe$2, Yn as all, Yo as YieldableProto, Yr as runPromise, Yt as mkString, Z as encode, Za as Reference, Zi as fail, Zn as annotateLogs, Zo as isEffect$1, Zr as runSync, Zt as run$2, _ as url, _a as andThen$1, _i as useSpan, _o as fromIterable$2, _r as fn, _s as constVoid, _t as tag, aa as UnknownError, ai as succeedNone, an as unwrap, ao as fromInputUnsafe, ar as catchFilter, as as symbolRedactable, at as isLessThanOrEqualTo, b as DateValid, ba as causePretty, bi as withParentSpan, bn as failCauseUnsafe, bo as makeEquivalence$1, br as forever, bs as pipe, bt as toType, c as FalseValues, ca as hasInterrupts, ci as tap, cn as drain, cr as catch_, cs as structure, ct as isMinLength, d as boolean$3, da as squash, di as timeoutOrElse, dn as fromTransform, do as toMillis, dr as ensuring, ds as isNotNull, dt as isSchemaError, ea as isSuccess, ei as service, en as runForEach, eo as empty$5, er as asVoid, es as Class$1, et as fromJsonString, f as map$6, fi as tryPromise, fn as mapDone, fo as toSeconds, fr as exit, fs as isNotUndefined, ft as link$1, ga as addFinalizer$2, gi as updateServices, go as flatMapNullishOr, gr as flatMap, gs as constTrue, gt as suspend$2, h as string$3, ha as LogToStderr$1, hi as uninterruptibleMask$1, ho as filter, hr as filterOrFail, hs as constFalse, ht as optional$2, ia as NoSuchElementError, ii as succeed, in as transduce, io as merge$2, ir as catchDefect, is as redact$1, it as isGreaterThanOrEqualTo, j as Number$1, ja as ignore$1, ji as empty$6, jn as set$2, jo as isFailure$1, jr as logDebug, jt as WatchBackend, k as Null, ka as formatLogSpan, ki as effectDiscard, kn as unbounded$1, kr as isEffect, kt as FileTypeId, l as TrueValues, la as hasInterruptsOnly, li as tapCause, ln as fromChannel, lo as minutes, lr as die, ls as symbol$1, lt as isNonEmpty, m as port, ma as CurrentLoggers$1, mi as uninterruptible, mo as ensure, mr as failCause, ms as isUndefined, mt as mutable, n as SqlClient, na as void_$3, ni as services, nn as suspend$3, nr as callback, ns as format$1, nt as isBetween, oa as done, oi as suspend, on as get$1, or as catchTag, os as symbol, ot as isMaxLength, p as option, pa as ConsoleRef, pi as try_, pn as make$28, po as zero, pr as fail$1, ps as isNullish, pt as makeFilter, q as decodeTo, qa as CurrentLogAnnotations, qi as isDone, qn as acquireUseRelease, qo as strictEqual, qr as result, qt as make$29, ra as Done, ri as servicesWith, rn as toReadableStreamEffect, ro as make$24, rr as catchCause, rs as formatJson$1, rt as isGreaterThan, s as Boolean$1, sa as fail$2, si as sync, sn as make$22, so as isFinite$1, sr as catchTags, ss as array, st as isMaxProperties, ta as succeed$1, ti as serviceOption, tn as splitLines, to as get$2, tr as cached, ts as NodeInspectSymbol, tt as is, u as all$1, ua as pretty, ui as timeoutOption, un as isSink, uo as seconds, ur as effectify, us as hasProperty, ut as isPattern, v as Array$1, va as as$1, vi as void_$1, vo as isArray, vr as fnUntraced, vs as dual, vt as toCodecStringTree, w as Int, wa as flatMap$1, wi as clamp, wn as offerUnsafe, wo as makeEquivalence, wr as forkScoped, wt as omit, x as Defect, xa as consolePretty$1, xi as withSpan, xn as make$23, xo as map$4, xr as forkChild, xs as pipeArguments, xt as withConstructorDefault, y as Boolean$2, yi as withFiber$1, yn as endUnsafe, yo as isReadonlyArrayNonEmpty, yr as forEach, ys as identity, yt as toJsonSchemaDocument, z as URLFromString, zi as addFinalizer, zn as transformOrFail, zo as isSome, zr as never, zt as flatMap$2 } from "./SqlClient-DSf3-WP1.mjs";
4
- import { a as make$32, i as keys, n as getOption, o as makeWith$1, r as invalidate, s as set$3, t as get$3 } from "./Cache-Ctxz7HFI.mjs";
3
+ import { $ as is, $a as fromInputUnsafe, $i as succeed$1, $n as cached, $o as structure, $r as serviceOption, $t as splitLines, A as Record, Aa as scope, Ai as mergeAll, An as makeUnsafe$1, Ao as isNone, Ar as logError$1, At as make$21, B as Void, Ba as void_$2, Bi as provide$2, Bn as InvalidValue$1, Bo as PipeInspectableProto, Br as orElseSucceed, Bt as fromIterable$1, C as Literal, Ca as forkDetach, Ci as Class, Cn as shutdown, Co as isFailure$1, Cr as gen, Ct as Path$1, D as Null, Da as ignore$1, Di as effectDiscard, Dn as unbounded$1, Do as getOrElse, Dr as isEffect, Dt as FileTypeId, E as NonEmptyString, Ea as gen$1, Ei as effect, En as publish, Eo as fromNullishOr, Er as interrupt, Et as FileSystem, F as Trim, Fa as succeedNone, Fi as unwrap$1, Fn as nominal, Fo as some, Fr as matchCauseEffect, Ft as empty$4, G as decodeTo, Ga as Reference, Gi as isDone, Gn as acquireUseRelease, Go as BaseProto, Gr as result, Gt as make$30, H as declare, Ha as CurrentLogSpans, Hi as doneUnsafe, Hn as make$31, Ho as exitSucceed, Hr as provide, Ht as fromQueue, I as Tuple, Ia as suspend$1, Ii as Scope, In as transform$1, Io as Number$2, Ir as matchEffect, It as fail$5, J as decodeUnknownSync, Ja as empty$5, Ji as succeed$5, Jn as andThen, Jo as format$1, Jr as runPromiseWith, Jt as onExit$1, K as decodeUnknownEffect, Ka as Service, Ki as make$27, Kn as addFinalizer$1, Ko as Class$1, Kr as runFork, Kt as merge$1, L as URLFromString, La as sync$1, Li as addFinalizer, Ln as transformOrFail, Lo as make$26, Lr as never, Lt as flatMap$2, M as Struct, Ma as servicesWith, Mi as provideMerge, Mn as BadArgument, Mo as map$4, Mr as logWarning$1, Mt as concat, N as TaggedErrorClass, Na as sleep$1, Ni as succeed$2, Nn as badArgument, No as match, Nr as map$2, Nt as decodeText, O as NullOr, Oa as loggerMake, On as make$20, Oo as getOrNull, Or as log$1, Ot as Size, P as TemplateLiteral, Pa as succeed$3, Pi as sync$2, Pn as systemError, Po as none, Pr as mapError, Q as fromJsonString, Qa as merge$2, Qi as isSuccess, Qn as asVoid, Qo as array, Qr as service, Qt as runForEach, R as Union, Ra as uninterruptibleMask, Ri as close, Rn as parseJson, Ro as make$32, Rr as onInterrupt, Rt as fromChannel$1, S as Int, Sa as forever$1, Si as clamp, Sn as offerUnsafe, So as failVoid, Sr as forkScoped, St as omit, T as NonEmptyArray, Ta as formatLogSpan, Ti as TaggedError, Tn as unbounded, To as filter$1, Tr as ignoreCause, Tt as FileDescriptor, U as decodeEffect, Ua as MinimumLogLevel, Ui as fail$4, Un as encodeBase64Url, Uo as isEffect$1, Ur as provideService, Ut as fromReadableStream, V as brand, Va as CurrentLogAnnotations, Vi as _await, Vn as makeFormatterDefault, Vo as YieldableProto, Vr as promise, Vt as fromPubSub, W as decodeExit, Wa as DisablePropagation, Wi as failCause$1, Wn as acquireRelease, Wo as withFiber, Wr as provideServices, Wt as isStream, X as encodeEffect, Xi as hasInterrupts$1, Xn as as, Xo as symbolRedactable, Xt as runCollect, Y as encode, Ya as get$4, Yi as fail, Yn as annotateLogs, Yo as redact$1, Yr as runSync, Yt as run$2, Z as encodeUnknownEffect, Za as make$25, Zi as isFailure, Zn as asSome$1, Zo as symbol, Zr as scoped, Zt as runFold, _ as url, _a as causePretty, _i as withFiber$1, _n as endUnsafe, _o as makeEquivalence, _r as forEach, _t as toJsonSchemaDocument, aa as fail$2, ai as sync, an as make$22, ao as toMillis, ar as catchTags, as as isUndefined, at as isMaxProperties, b as Defect, ba as flatMap$1, bi as zipWith, bn as offer$1, bo as makeEquivalence$2, br as forkDetach$1, bt as withDecodingDefault, c as FalseValues, ca as pretty, ci as timeoutOption, cn as isSink, co as filter, cr as effectify, cs as constVoid, ct as isPattern, d as boolean$3, da as ConsoleRef, di as try_, dn as make$29, do as isArray, dr as fail$1, ds as pipe, dt as makeFilter, ea as void_$3, ei as services, en as suspend$3, eo as infinity, er as callback, es as symbol$1, et as isBetween, f as map$5, fa as CurrentLoggers$1, fi as uninterruptible, fn as get$3, fo as isReadonlyArrayNonEmpty, fr as failCause, fs as pipeArguments, ft as mutable, ga as asSome, gi as void_$1, gn as size, go as sort, gr as fnUntraced, gt as toCodecStringTree, h as string$3, ha as as$1, hi as useSpan, hn as set$3, ho as of, hr as fn, ht as tag, ia as done, ii as suspend, in as get$2, io as seconds, ir as catchTag, is as isNullish, it as isMaxLength, j as String$1, ja as scopeAddFinalizerExit, ji as provide$1, jo as isSome, jr as logInfo$1, jt as callback$1, k as Number$1, ka as onExit, ki as empty$6, kn as set$4, ko as getOrUndefined, kr as logDebug, kt as WatchBackend, l as TrueValues, la as squash, li as timeoutOrElse, ln as fromTransform, lo as flatMapNullishOr, lr as ensuring, ls as dual, lt as isSchemaError, m as port, ma as andThen$1, mi as updateServices$1, mn as remove$2, mo as map$3, mr as flatMap, mt as suspend$2, n as SqlClient, na as NoSuchElementError, ni as succeed, nn as transduce, no as isZero, nr as catchDefect, ns as isNotNull, nt as isGreaterThanOrEqualTo, oa as hasInterrupts, oi as tap, on as drain, oo as zero, or as catch_, os as constFalse, ot as isMinLength, p as option, pa as addFinalizer$2, pi as uninterruptibleMask$1, pn as make$24, po as makeEquivalence$1, pr as filterOrFail, pt as optional$2, q as decodeUnknownExit, qi as makeUnsafe$2, qn as all, qo as NodeInspectSymbol, qr as runPromise, qt as mkString, ra as UnknownError, ri as succeedNone$1, rn as unwrap, ro as minutes, rr as catchFilter, rs as isNotUndefined, rt as isLessThanOrEqualTo, s as Boolean$1, sa as hasInterruptsOnly, si as tapCause, sn as fromChannel, so as ensure, sr as die, ss as constTrue, st as isNonEmpty, ta as Done, ti as servicesWith$1, tn as toReadableStreamEffect, to as isFinite$1, tr as catchCause, ts as hasProperty, tt as isGreaterThan, u as all$1, ua as ClockRef, ui as tryPromise, un as mapDone, uo as fromIterable$2, ur as exit, us as identity, ut as link$1, v as Array$1, va as defaultLogger$1, vi as withParentSpan, vn as failCauseUnsafe, vo as map$6, vr as forever, vt as toType, w as Literals, wa as formatLabel, wi as Error$1, wn as take, wo as succeed$4, wr as ignore, wt as TypeId$17, x as ErrorClass, xa as fnUntraced$1, xi as catchDone, xn as offerAll, xo as fail$3, xr as forkIn, xt as assign, y as Boolean$2, ya as fiberInterrupt, yi as withSpan, yn as make$23, yo as filterMap, yr as forkChild, yt as withConstructorDefault, z as Unknown, za as updateServices, zi as make$28, zn as stringifyJson, zo as strictEqual, zr as orDie, zt as fromEffect } from "./SqlClient-B-Bb00hw.mjs";
5
4
  import { createRequire } from "node:module";
6
5
  import * as NodeChildProcess from "node:child_process";
7
6
  import { execFileSync, spawn, spawnSync } from "node:child_process";
@@ -34,7 +33,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
34
33
  var __getOwnPropNames = Object.getOwnPropertyNames;
35
34
  var __getProtoOf = Object.getPrototypeOf;
36
35
  var __hasOwnProp = Object.prototype.hasOwnProperty;
37
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
36
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
38
37
  var __copyProps = (to, from, except, desc) => {
39
38
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
40
39
  key = keys[i];
@@ -296,7 +295,7 @@ const makeHandle = (params) => Object.assign(Object.create(HandleProto), params)
296
295
  * @category Models
297
296
  */
298
297
  const make$19 = (spawn) => {
299
- const streamString = (command, options) => spawn(command).pipe(map$3((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap);
298
+ const streamString = (command, options) => spawn(command).pipe(map$2((handle) => decodeText(options?.includeStderr === true ? handle.all : handle.stdout)), unwrap);
300
299
  const streamLines = (command, options) => splitLines(streamString(command, options));
301
300
  return ChildProcessSpawner.of({
302
301
  spawn,
@@ -316,16 +315,16 @@ const make$19 = (spawn) => {
316
315
  var ChildProcessSpawner = class extends Service()("effect/process/ChildProcessSpawner") {};
317
316
  //#endregion
318
317
  //#region ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/unstable/process/ChildProcess.js
319
- const TypeId$15 = "~effect/unstable/process/ChildProcess";
320
- const Proto$9 = {
318
+ const TypeId$16 = "~effect/unstable/process/ChildProcess";
319
+ const Proto$10 = {
321
320
  ...PipeInspectableProto,
322
321
  ...YieldableProto,
323
- [TypeId$15]: TypeId$15,
322
+ [TypeId$16]: TypeId$16,
324
323
  asEffect() {
325
324
  return ChildProcessSpawner.use((_) => _.spawn(this));
326
325
  }
327
326
  };
328
- const makeStandardCommand = (command, args, options) => Object.assign(Object.create(Proto$9), {
327
+ const makeStandardCommand = (command, args, options) => Object.assign(Object.create(Proto$10), {
329
328
  _tag: "StandardCommand",
330
329
  command,
331
330
  args,
@@ -874,7 +873,7 @@ const make$17 = /* @__PURE__ */ gen(function* () {
874
873
  const stdin = yield* setupChildStdin(cmd, childProcess, stdinConfig);
875
874
  const { all, stderr, stdout } = setupChildOutputStreams(cmd, childProcess, stdoutConfig, stderrConfig);
876
875
  const { getInputFd, getOutputFd } = yield* setupAdditionalFds(cmd, childProcess, resolvedAdditionalFds);
877
- const isRunning = map$3(isDone(exitSignal), (done) => !done);
876
+ const isRunning = map$2(isDone(exitSignal), (done) => !done);
878
877
  const exitCode = flatMap(_await(exitSignal), ([code, signal]) => {
879
878
  if (isNotNull(code)) return succeed(ExitCode(code));
880
879
  return fail$1(toPlatformError("exitCode", new globalThis.Error(`Process interrupted due to receipt of signal: '${signal}'`), cmd));
@@ -903,7 +902,7 @@ const make$17 = /* @__PURE__ */ gen(function* () {
903
902
  const command = pipeline[i];
904
903
  const options = pipeOptions[i] ?? {};
905
904
  const stdinConfig = resolveStdinOption(command.options);
906
- const sourceStream = unwrap(map$3(handle, (h) => getSourceStream(h, options.from)));
905
+ const sourceStream = unwrap(map$2(handle, (h) => getSourceStream(h, options.from)));
907
906
  const toOption = options.to ?? "stdin";
908
907
  if (toOption === "stdin") handle = spawnCommand(make$18(command.command, command.args, {
909
908
  ...command.options,
@@ -1054,7 +1053,7 @@ const makeTempDirectoryScoped = /* @__PURE__ */ (() => {
1054
1053
  const openFactory = (method) => {
1055
1054
  const nodeOpen = effectify(NFS.open, handleErrnoException("FileSystem", method), handleBadArgument(method));
1056
1055
  const nodeClose = effectify(NFS.close, handleErrnoException("FileSystem", method), handleBadArgument(method));
1057
- return (path, options) => pipe(acquireRelease(nodeOpen(path, options?.flag ?? "r", options?.mode), (fd) => orDie(nodeClose(fd))), map$3((fd) => makeFile(FileDescriptor(fd), options?.flag?.startsWith("a") ?? false)));
1056
+ return (path, options) => pipe(acquireRelease(nodeOpen(path, options?.flag ?? "r", options?.mode), (fd) => orDie(nodeClose(fd))), map$2((fd) => makeFile(FileDescriptor(fd), options?.flag?.startsWith("a") ?? false)));
1058
1057
  };
1059
1058
  const open = /* @__PURE__ */ openFactory("open");
1060
1059
  const makeFile = /* @__PURE__ */ (() => {
@@ -1078,7 +1077,7 @@ const makeFile = /* @__PURE__ */ (() => {
1078
1077
  this.append = append;
1079
1078
  }
1080
1079
  get stat() {
1081
- return map$3(nodeStat(this.fd), makeFileInfo);
1080
+ return map$2(nodeStat(this.fd), makeFileInfo);
1082
1081
  }
1083
1082
  get sync() {
1084
1083
  return nodeSync(this.fd);
@@ -1094,7 +1093,7 @@ const makeFile = /* @__PURE__ */ (() => {
1094
1093
  read(buffer) {
1095
1094
  return suspend(() => {
1096
1095
  const position = this.position;
1097
- return map$3(nodeRead(this.fd, {
1096
+ return map$2(nodeRead(this.fd, {
1098
1097
  buffer,
1099
1098
  position
1100
1099
  }), (bytesRead) => {
@@ -1109,7 +1108,7 @@ const makeFile = /* @__PURE__ */ (() => {
1109
1108
  return suspend(() => {
1110
1109
  const buffer = Buffer.allocUnsafeSlow(sizeNumber);
1111
1110
  const position = this.position;
1112
- return map$3(nodeReadAlloc(this.fd, {
1111
+ return map$2(nodeReadAlloc(this.fd, {
1113
1112
  buffer,
1114
1113
  position
1115
1114
  }), (bytesRead) => {
@@ -1123,7 +1122,7 @@ const makeFile = /* @__PURE__ */ (() => {
1123
1122
  });
1124
1123
  }
1125
1124
  truncate(length) {
1126
- return map$3(nodeTruncate(this.fd, length ? Number(length) : void 0), () => {
1125
+ return map$2(nodeTruncate(this.fd, length ? Number(length) : void 0), () => {
1127
1126
  if (!this.append) {
1128
1127
  const len = BigInt(length ?? 0);
1129
1128
  if (this.position > len) this.position = len;
@@ -1133,7 +1132,7 @@ const makeFile = /* @__PURE__ */ (() => {
1133
1132
  write(buffer) {
1134
1133
  return suspend(() => {
1135
1134
  const position = this.position;
1136
- return map$3(nodeWrite(this.fd, buffer, void 0, void 0, this.append ? void 0 : Number(position)), (bytesWritten) => {
1135
+ return map$2(nodeWrite(this.fd, buffer, void 0, void 0, this.append ? void 0 : Number(position)), (bytesWritten) => {
1137
1136
  const sizeWritten = Size(bytesWritten);
1138
1137
  if (!this.append) this.position = position + sizeWritten;
1139
1138
  return sizeWritten;
@@ -1222,7 +1221,7 @@ const makeFileInfo = (stat) => ({
1222
1221
  });
1223
1222
  const stat$1 = /* @__PURE__ */ (() => {
1224
1223
  const nodeStat = /* @__PURE__ */ effectify(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat"));
1225
- return (path) => map$3(nodeStat(path), makeFileInfo);
1224
+ return (path) => map$2(nodeStat(path), makeFileInfo);
1226
1225
  })();
1227
1226
  const symlink = /* @__PURE__ */ (() => {
1228
1227
  const nodeSymlink = /* @__PURE__ */ effectify(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink"));
@@ -1274,7 +1273,7 @@ const watchNode = (path) => callback$1((queue) => acquireRelease(sync(() => {
1274
1273
  });
1275
1274
  return watcher;
1276
1275
  }), (watcher) => sync(() => watcher.close())));
1277
- const watch = (backend, path) => stat$1(path).pipe(map$3((stat) => {
1276
+ const watch = (backend, path) => stat$1(path).pipe(map$2((stat) => {
1278
1277
  if (backend) {
1279
1278
  const stream = backend.register(path, stat);
1280
1279
  if (stream) return stream;
@@ -1295,7 +1294,7 @@ const writeFile$1 = (path, data, options) => callback((resume, signal) => {
1295
1294
  resume(fail$1(handleBadArgument("writeFile")(err)));
1296
1295
  }
1297
1296
  });
1298
- const makeFileSystem = /* @__PURE__ */ map$3(/* @__PURE__ */ serviceOption(WatchBackend), (backend) => make$21({
1297
+ const makeFileSystem = /* @__PURE__ */ map$2(/* @__PURE__ */ serviceOption(WatchBackend), (backend) => make$21({
1299
1298
  access,
1300
1299
  chmod,
1301
1300
  chown,
@@ -1363,8 +1362,8 @@ const toFileUrl = (path) => try_({
1363
1362
  * @since 1.0.0
1364
1363
  * @category Layers
1365
1364
  */
1366
- const layerPosix$1 = /* @__PURE__ */ succeed$2(Path$1)({
1367
- [TypeId$16]: TypeId$16,
1365
+ const layerPosix = /* @__PURE__ */ succeed$2(Path$1)({
1366
+ [TypeId$17]: TypeId$17,
1368
1367
  ...Path.posix,
1369
1368
  fromFileUrl,
1370
1369
  toFileUrl
@@ -1373,8 +1372,8 @@ const layerPosix$1 = /* @__PURE__ */ succeed$2(Path$1)({
1373
1372
  * @since 1.0.0
1374
1373
  * @category Layers
1375
1374
  */
1376
- const layerWin32$1 = /* @__PURE__ */ succeed$2(Path$1)({
1377
- [TypeId$16]: TypeId$16,
1375
+ const layerWin32 = /* @__PURE__ */ succeed$2(Path$1)({
1376
+ [TypeId$17]: TypeId$17,
1378
1377
  ...Path.win32,
1379
1378
  fromFileUrl,
1380
1379
  toFileUrl
@@ -1384,7 +1383,7 @@ const layerWin32$1 = /* @__PURE__ */ succeed$2(Path$1)({
1384
1383
  * @category Layers
1385
1384
  */
1386
1385
  const layer$8 = /* @__PURE__ */ succeed$2(Path$1)({
1387
- [TypeId$16]: TypeId$16,
1386
+ [TypeId$17]: TypeId$17,
1388
1387
  ...Path,
1389
1388
  fromFileUrl,
1390
1389
  toFileUrl
@@ -1399,34 +1398,24 @@ const layer$8 = /* @__PURE__ */ succeed$2(Path$1)({
1399
1398
  * @category layer
1400
1399
  */
1401
1400
  const layer$7 = layer$8;
1402
- /**
1403
- * @since 1.0.0
1404
- * @category layer
1405
- */
1406
- const layerPosix = layerPosix$1;
1407
- /**
1408
- * @since 1.0.0
1409
- * @category layer
1410
- */
1411
- const layerWin32 = layerWin32$1;
1412
1401
  //#endregion
1413
1402
  //#region ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/Stdio.js
1414
1403
  /**
1415
1404
  * @since 4.0.0
1416
1405
  * @category Type IDs
1417
1406
  */
1418
- const TypeId$14 = "~effect/Stdio";
1407
+ const TypeId$15 = "~effect/Stdio";
1419
1408
  /**
1420
1409
  * @since 4.0.0
1421
1410
  * @category Services
1422
1411
  */
1423
- const Stdio = /* @__PURE__ */ Service(TypeId$14);
1412
+ const Stdio = /* @__PURE__ */ Service(TypeId$15);
1424
1413
  /**
1425
1414
  * @since 4.0.0
1426
1415
  * @category Constructors
1427
1416
  */
1428
1417
  const make$16 = (options) => ({
1429
- [TypeId$14]: TypeId$14,
1418
+ [TypeId$15]: TypeId$15,
1430
1419
  ...options
1431
1420
  });
1432
1421
  //#endregion
@@ -1480,7 +1469,7 @@ const layer$6 = /* @__PURE__ */ succeed$2(Stdio, /* @__PURE__ */ make$16({
1480
1469
  const layer$5 = layer$6;
1481
1470
  //#endregion
1482
1471
  //#region ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/Terminal.js
1483
- const TypeId$13 = "~effect/platform/Terminal";
1472
+ const TypeId$14 = "~effect/platform/Terminal";
1484
1473
  const QuitErrorTypeId = "effect/platform/Terminal/QuitError";
1485
1474
  /**
1486
1475
  * A `QuitError` represents an error that occurs when a user attempts to
@@ -1513,7 +1502,7 @@ const Terminal = /* @__PURE__ */ Service("effect/platform/Terminal");
1513
1502
  */
1514
1503
  const make$15 = (impl) => Terminal.of({
1515
1504
  ...impl,
1516
- [TypeId$13]: TypeId$13
1505
+ [TypeId$14]: TypeId$14
1517
1506
  });
1518
1507
  //#endregion
1519
1508
  //#region ../../node_modules/.bun/@effect+platform-node-shared@https+++pkg.pr.new+Effect-TS+effect-smol+@effect+platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368+eecd35a1726d7096/node_modules/@effect/platform-node-shared/dist/NodeTerminal.js
@@ -1538,7 +1527,7 @@ const make$14 = /* @__PURE__ */ fnUntraced(function* (shouldQuit = defaultShould
1538
1527
  })) });
1539
1528
  const columns = sync(() => stdout.columns ?? 0);
1540
1529
  const readInput = gen(function* () {
1541
- yield* get$1(rlRef);
1530
+ yield* get$2(rlRef);
1542
1531
  const queue = yield* make$23();
1543
1532
  const handleKeypress = (s, k) => {
1544
1533
  const userInput = {
@@ -1557,7 +1546,7 @@ const make$14 = /* @__PURE__ */ fnUntraced(function* (shouldQuit = defaultShould
1557
1546
  stdin.on("keypress", handleKeypress);
1558
1547
  return queue;
1559
1548
  });
1560
- const readLine = scoped(flatMap(get$1(rlRef), (readlineInterface) => callback((resume) => {
1549
+ const readLine = scoped(flatMap(get$2(rlRef), (readlineInterface) => callback((resume) => {
1561
1550
  const onLine = (line) => resume(succeed(line));
1562
1551
  readlineInterface.once("line", onLine);
1563
1552
  return sync(() => readlineInterface.off("line", onLine));
@@ -1592,11 +1581,6 @@ function defaultShouldQuit(input) {
1592
1581
  */
1593
1582
  /**
1594
1583
  * @since 1.0.0
1595
- * @category constructors
1596
- */
1597
- const make$13 = make$14;
1598
- /**
1599
- * @since 1.0.0
1600
1584
  * @category layers
1601
1585
  */
1602
1586
  const layer$3 = layer$4;
@@ -1608,6 +1592,567 @@ const layer$3 = layer$4;
1608
1592
  */
1609
1593
  const layer$2 = /* @__PURE__ */ provideMerge(layer$11, /* @__PURE__ */ mergeAll(layer$9, layer$7, layer$5, layer$3));
1610
1594
  //#endregion
1595
+ //#region ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/Cache.js
1596
+ /**
1597
+ * @since 4.0.0
1598
+ */
1599
+ const TypeId$13 = "~effect/Cache";
1600
+ /**
1601
+ * Creates a cache with dynamic time-to-live based on the result and key.
1602
+ *
1603
+ * The timeToLive function receives both the exit result and the key, allowing
1604
+ * for flexible TTL policies based on success/failure state and key characteristics.
1605
+ *
1606
+ * @example
1607
+ * ```ts
1608
+ * import { Cache, Effect, Exit } from "effect"
1609
+ *
1610
+ * // Cache with different TTL for success vs failure
1611
+ * const program = Effect.gen(function*() {
1612
+ * const cache = yield* Cache.makeWith<string, number, string>({
1613
+ * capacity: 100,
1614
+ * lookup: (key) =>
1615
+ * key === "fail"
1616
+ * ? Effect.fail("error")
1617
+ * : Effect.succeed(key.length),
1618
+ * timeToLive: (exit, key) => {
1619
+ * if (Exit.isFailure(exit)) return "1 minute" // Short TTL for errors
1620
+ * return key.startsWith("temp") ? "5 minutes" : "1 hour"
1621
+ * }
1622
+ * })
1623
+ *
1624
+ * // Get values with different TTL policies
1625
+ * const result1 = yield* Cache.get(cache, "hello")
1626
+ * const result2 = yield* Cache.get(cache, "temp_data")
1627
+ * console.log({ result1, result2 }) // { result1: 5, result2: 9 }
1628
+ * })
1629
+ * ```
1630
+ *
1631
+ * @example
1632
+ * ```ts
1633
+ * import { Cache, Effect, Exit } from "effect"
1634
+ *
1635
+ * // Cache with TTL based on computed value
1636
+ * const userCache = Effect.gen(function*() {
1637
+ * const cache = yield* Cache.makeWith<
1638
+ * number,
1639
+ * { id: number; active: boolean },
1640
+ * never
1641
+ * >({
1642
+ * capacity: 1000,
1643
+ * lookup: (id) => Effect.succeed({ id, active: id % 2 === 0 }),
1644
+ * timeToLive: (exit) => {
1645
+ * if (Exit.isSuccess(exit)) {
1646
+ * const user = exit.value
1647
+ * return user.active ? "1 hour" : "5 minutes"
1648
+ * }
1649
+ * return "30 seconds"
1650
+ * }
1651
+ * })
1652
+ *
1653
+ * return cache
1654
+ * })
1655
+ * ```
1656
+ *
1657
+ * @since 4.0.0
1658
+ * @category Constructors
1659
+ */
1660
+ const makeWith$1 = (options) => servicesWith((services) => {
1661
+ const self = Object.create(Proto$9);
1662
+ self.lookup = (key) => updateServices(options.lookup(key), (input) => merge$2(services, input));
1663
+ self.map = make$24();
1664
+ self.capacity = options.capacity;
1665
+ self.timeToLive = options.timeToLive ? (exit, key) => fromInputUnsafe(options.timeToLive(exit, key)) : defaultTimeToLive;
1666
+ return succeed$3(self);
1667
+ });
1668
+ /**
1669
+ * Creates a cache with a fixed time-to-live for all entries.
1670
+ *
1671
+ * This is the basic cache constructor where all entries share the same TTL.
1672
+ * The lookup function will be called when a key is not found or has expired.
1673
+ *
1674
+ * @example
1675
+ * ```ts
1676
+ * import { Cache, Effect } from "effect"
1677
+ *
1678
+ * // Basic cache with string keys
1679
+ * const program = Effect.gen(function*() {
1680
+ * const cache = yield* Cache.make<string, number>({
1681
+ * capacity: 100,
1682
+ * lookup: (key) => Effect.succeed(key.length)
1683
+ * })
1684
+ *
1685
+ * const result1 = yield* Cache.get(cache, "hello")
1686
+ * const result2 = yield* Cache.get(cache, "world")
1687
+ * console.log({ result1, result2 }) // { result1: 5, result2: 5 }
1688
+ * })
1689
+ * ```
1690
+ *
1691
+ * @example
1692
+ * ```ts
1693
+ * import { Cache, Effect } from "effect"
1694
+ *
1695
+ * // Cache with TTL and async lookup
1696
+ * const fetchUserCache = Effect.gen(function*() {
1697
+ * const cache = yield* Cache.make<
1698
+ * number,
1699
+ * { name: string; email: string },
1700
+ * string
1701
+ * >({
1702
+ * capacity: 500,
1703
+ * lookup: (userId) =>
1704
+ * Effect.tryPromise({
1705
+ * try: () => fetch(`/api/users/${userId}`).then((r) => r.json()),
1706
+ * catch: () => "Failed to fetch user"
1707
+ * }),
1708
+ * timeToLive: "15 minutes"
1709
+ * })
1710
+ *
1711
+ * // First call fetches from API, second call returns cached result
1712
+ * const user1 = yield* Cache.get(cache, 123)
1713
+ * const user2 = yield* Cache.get(cache, 123) // From cache
1714
+ * return { user1, user2 }
1715
+ * })
1716
+ * ```
1717
+ *
1718
+ * @since 4.0.0
1719
+ * @category Constructors
1720
+ */
1721
+ const make$13 = (options) => makeWith$1({
1722
+ ...options,
1723
+ timeToLive: options.timeToLive ? () => options.timeToLive : defaultTimeToLive
1724
+ });
1725
+ const Proto$9 = {
1726
+ ...PipeInspectableProto,
1727
+ [TypeId$13]: TypeId$13,
1728
+ toJSON() {
1729
+ return {
1730
+ _id: "Cache",
1731
+ capacity: this.capacity,
1732
+ map: this.map
1733
+ };
1734
+ }
1735
+ };
1736
+ const defaultTimeToLive = (_, _key) => infinity;
1737
+ /**
1738
+ * Retrieves the value associated with the specified key from the cache.
1739
+ *
1740
+ * If the key is not present or has expired, it will invoke the lookup function
1741
+ * to construct the value, store it in the cache, and return it.
1742
+ *
1743
+ * @example
1744
+ * ```ts
1745
+ * import { Cache, Effect } from "effect"
1746
+ *
1747
+ * const program = Effect.gen(function*() {
1748
+ * const cache = yield* Cache.make({
1749
+ * capacity: 10,
1750
+ * lookup: (key: string) => Effect.succeed(key.length)
1751
+ * })
1752
+ *
1753
+ * // Cache miss - triggers lookup function
1754
+ * const result1 = yield* Cache.get(cache, "hello")
1755
+ * console.log(result1) // 5
1756
+ *
1757
+ * // Cache hit - returns cached value without lookup
1758
+ * const result2 = yield* Cache.get(cache, "hello")
1759
+ * console.log(result2) // 5 (from cache)
1760
+ *
1761
+ * return { result1, result2 }
1762
+ * })
1763
+ * ```
1764
+ *
1765
+ * @example
1766
+ * ```ts
1767
+ * import { Cache, Effect } from "effect"
1768
+ *
1769
+ * // Error handling when lookup fails
1770
+ * const program = Effect.gen(function*() {
1771
+ * const cache = yield* Cache.make<string, number, string>({
1772
+ * capacity: 10,
1773
+ * lookup: (key: string) =>
1774
+ * key === "error"
1775
+ * ? Effect.fail("Lookup failed")
1776
+ * : Effect.succeed(key.length)
1777
+ * })
1778
+ *
1779
+ * // Successful lookup
1780
+ * const success = yield* Cache.get(cache, "hello")
1781
+ * console.log(success) // 5
1782
+ *
1783
+ * // Failed lookup - returns error
1784
+ * const failure = yield* Effect.exit(Cache.get(cache, "error"))
1785
+ * console.log(failure) // Exit.fail("Lookup failed")
1786
+ * })
1787
+ * ```
1788
+ *
1789
+ * @example
1790
+ * ```ts
1791
+ * import { Cache, Effect } from "effect"
1792
+ *
1793
+ * // Concurrent access - multiple gets of same key only invoke lookup once
1794
+ * const program = Effect.gen(function*() {
1795
+ * let lookupCount = 0
1796
+ * const cache = yield* Cache.make({
1797
+ * capacity: 10,
1798
+ * lookup: (key: string) =>
1799
+ * Effect.sync(() => {
1800
+ * lookupCount++
1801
+ * return key.length
1802
+ * })
1803
+ * })
1804
+ *
1805
+ * // Multiple concurrent gets
1806
+ * const results = yield* Effect.all([
1807
+ * Cache.get(cache, "hello"),
1808
+ * Cache.get(cache, "hello"),
1809
+ * Cache.get(cache, "hello")
1810
+ * ], { concurrency: "unbounded" })
1811
+ *
1812
+ * console.log(results) // [5, 5, 5]
1813
+ * console.log(lookupCount) // 1 (lookup called only once)
1814
+ * })
1815
+ * ```
1816
+ *
1817
+ * @since 4.0.0
1818
+ * @category Combinators
1819
+ */
1820
+ const get$1 = /* @__PURE__ */ dual(2, (self, key) => withFiber((fiber) => {
1821
+ const oentry = get$3(self.map, key);
1822
+ if (isSome(oentry) && !hasExpired(oentry.value, fiber)) {
1823
+ remove$2(self.map, key);
1824
+ set$3(self.map, key, oentry.value);
1825
+ return _await(oentry.value.deferred);
1826
+ }
1827
+ const deferred = makeUnsafe$2();
1828
+ const entry = {
1829
+ expiresAt: void 0,
1830
+ deferred
1831
+ };
1832
+ set$3(self.map, key, entry);
1833
+ if (Number.isFinite(self.capacity)) checkCapacity(self);
1834
+ return onExit(self.lookup(key), (exit) => {
1835
+ doneUnsafe(deferred, exit);
1836
+ const ttl = self.timeToLive(exit, key);
1837
+ if (isFinite$1(ttl)) entry.expiresAt = fiber.getRef(ClockRef).currentTimeMillisUnsafe() + toMillis(ttl);
1838
+ else if (isZero(ttl)) remove$2(self.map, key);
1839
+ return void_$2;
1840
+ });
1841
+ }));
1842
+ const hasExpired = (entry, fiber) => {
1843
+ if (entry.expiresAt === void 0) return false;
1844
+ return fiber.getRef(ClockRef).currentTimeMillisUnsafe() >= entry.expiresAt;
1845
+ };
1846
+ const checkCapacity = (self) => {
1847
+ let diff = size(self.map) - self.capacity;
1848
+ if (diff <= 0) return;
1849
+ for (const [key] of self.map) {
1850
+ remove$2(self.map, key);
1851
+ diff--;
1852
+ if (diff === 0) return;
1853
+ }
1854
+ };
1855
+ /**
1856
+ * Retrieves the value associated with the specified key from the cache,
1857
+ * returning an `Option` that is `Some` if the key exists and has not expired,
1858
+ * or `None` if the key does not exist or has expired.
1859
+ *
1860
+ * Unlike `get`, this function will not invoke the lookup function if the key
1861
+ * is missing or expired.
1862
+ *
1863
+ * @example
1864
+ * ```ts
1865
+ * import { Cache, Effect } from "effect"
1866
+ *
1867
+ * const program = Effect.gen(function*() {
1868
+ * const cache = yield* Cache.make({
1869
+ * capacity: 10,
1870
+ * lookup: (key: string) => Effect.succeed(key.length)
1871
+ * })
1872
+ *
1873
+ * // No value in cache yet - returns None without lookup
1874
+ * const empty = yield* Cache.getOption(cache, "hello")
1875
+ * console.log(empty) // Option.none()
1876
+ *
1877
+ * // Populate cache using get
1878
+ * yield* Cache.get(cache, "hello")
1879
+ *
1880
+ * // Now getOption returns the cached value
1881
+ * const cached = yield* Cache.getOption(cache, "hello")
1882
+ * console.log(cached) // Option.some(5)
1883
+ *
1884
+ * return { empty, cached }
1885
+ * })
1886
+ * ```
1887
+ *
1888
+ * @example
1889
+ * ```ts
1890
+ * import { Cache, Effect } from "effect"
1891
+ * import { TestClock } from "effect/testing"
1892
+ *
1893
+ * // Expired entries return None
1894
+ * const program = Effect.gen(function*() {
1895
+ * const cache = yield* Cache.make({
1896
+ * capacity: 10,
1897
+ * lookup: (key: string) => Effect.succeed(key.length),
1898
+ * timeToLive: "1 hour"
1899
+ * })
1900
+ *
1901
+ * // Add value to cache
1902
+ * yield* Cache.get(cache, "hello")
1903
+ *
1904
+ * // Value exists before expiration
1905
+ * const beforeExpiry = yield* Cache.getOption(cache, "hello")
1906
+ * console.log(beforeExpiry) // Option.some(5)
1907
+ *
1908
+ * // Simulate time passing
1909
+ * yield* TestClock.adjust("2 hours")
1910
+ *
1911
+ * // Value expired - returns None
1912
+ * const afterExpiry = yield* Cache.getOption(cache, "hello")
1913
+ * console.log(afterExpiry) // Option.none()
1914
+ * })
1915
+ * ```
1916
+ *
1917
+ * @example
1918
+ * ```ts
1919
+ * import { Cache, Deferred, Effect, Fiber } from "effect"
1920
+ *
1921
+ * // Waits for ongoing computation to complete
1922
+ * const program = Effect.gen(function*() {
1923
+ * const deferred = yield* Deferred.make<void>()
1924
+ * const cache = yield* Cache.make({
1925
+ * capacity: 10,
1926
+ * lookup: (_key: string) => Deferred.await(deferred).pipe(Effect.as(42))
1927
+ * })
1928
+ *
1929
+ * // Start lookup in background
1930
+ * const getFiber = yield* Effect.forkChild(Cache.get(cache, "key"))
1931
+ *
1932
+ * // getOption waits for ongoing computation
1933
+ * const optionFiber = yield* Effect.forkChild(Cache.getOption(cache, "key"))
1934
+ *
1935
+ * // Complete the computation
1936
+ * yield* Deferred.succeed(deferred, void 0)
1937
+ *
1938
+ * const result = yield* Fiber.join(optionFiber)
1939
+ * console.log(result) // Option.some(42)
1940
+ * })
1941
+ * ```
1942
+ *
1943
+ * @since 4.0.0
1944
+ * @category Combinators
1945
+ */
1946
+ const getOption = /* @__PURE__ */ dual(2, (self, key) => withFiber((fiber) => {
1947
+ const entry = getImpl(self, key, fiber);
1948
+ return entry ? asSome(_await(entry.deferred)) : succeedNone;
1949
+ }));
1950
+ const getImpl = (self, key, fiber, isRead = true) => {
1951
+ const oentry = get$3(self.map, key);
1952
+ if (isNone(oentry)) return;
1953
+ else if (hasExpired(oentry.value, fiber)) {
1954
+ remove$2(self.map, key);
1955
+ return;
1956
+ } else if (isRead) {
1957
+ remove$2(self.map, key);
1958
+ set$3(self.map, key, oentry.value);
1959
+ }
1960
+ return oentry.value;
1961
+ };
1962
+ /**
1963
+ * Sets the value associated with the specified key in the cache. This will
1964
+ * overwrite any existing value for that key, skipping the lookup function.
1965
+ *
1966
+ * @example
1967
+ * ```ts
1968
+ * import { Cache, Effect } from "effect"
1969
+ *
1970
+ * const program = Effect.gen(function*() {
1971
+ * const cache = yield* Cache.make({
1972
+ * capacity: 100,
1973
+ * lookup: (key: string) => Effect.succeed(key.length)
1974
+ * })
1975
+ *
1976
+ * // Set a value directly without invoking lookup
1977
+ * yield* Cache.set(cache, "hello", 42)
1978
+ * const result = yield* Cache.get(cache, "hello")
1979
+ * console.log(result) // 42 (not 5 from lookup)
1980
+ * })
1981
+ * ```
1982
+ *
1983
+ * @example
1984
+ * ```ts
1985
+ * import { Cache, Effect } from "effect"
1986
+ *
1987
+ * // Overwriting existing cached values
1988
+ * const program = Effect.gen(function*() {
1989
+ * const cache = yield* Cache.make({
1990
+ * capacity: 100,
1991
+ * lookup: (key: string) => Effect.succeed(key.length)
1992
+ * })
1993
+ *
1994
+ * // First get populates via lookup
1995
+ * const original = yield* Cache.get(cache, "test") // 4
1996
+ *
1997
+ * // Set overwrites the cached value
1998
+ * yield* Cache.set(cache, "test", 999)
1999
+ * const updated = yield* Cache.get(cache, "test") // 999
2000
+ *
2001
+ * console.log({ original, updated })
2002
+ * })
2003
+ * ```
2004
+ *
2005
+ * @example
2006
+ * ```ts
2007
+ * import { Cache, Effect } from "effect"
2008
+ * import { TestClock } from "effect/testing"
2009
+ *
2010
+ * // TTL behavior with set operations
2011
+ * const program = Effect.gen(function*() {
2012
+ * const cache = yield* Cache.make({
2013
+ * capacity: 100,
2014
+ * lookup: (key: string) => Effect.succeed(key.length),
2015
+ * timeToLive: "1 hour"
2016
+ * })
2017
+ *
2018
+ * // Set value with TTL applied
2019
+ * yield* Cache.set(cache, "temporary", 123)
2020
+ * console.log(yield* Cache.has(cache, "temporary")) // true
2021
+ *
2022
+ * // Advance time past TTL
2023
+ * yield* TestClock.adjust("2 hours")
2024
+ * console.log(yield* Cache.has(cache, "temporary")) // false
2025
+ * })
2026
+ * ```
2027
+ *
2028
+ * @example
2029
+ * ```ts
2030
+ * import { Cache, Effect } from "effect"
2031
+ *
2032
+ * // Capacity enforcement with set operations
2033
+ * const program = Effect.gen(function*() {
2034
+ * const cache = yield* Cache.make({
2035
+ * capacity: 2,
2036
+ * lookup: (key: string) => Effect.succeed(key.length)
2037
+ * })
2038
+ *
2039
+ * // Fill cache to capacity
2040
+ * yield* Cache.set(cache, "a", 1)
2041
+ * yield* Cache.set(cache, "b", 2)
2042
+ * console.log(yield* Cache.size(cache)) // 2
2043
+ *
2044
+ * // Adding another entry evicts oldest
2045
+ * yield* Cache.set(cache, "c", 3)
2046
+ * console.log(yield* Cache.size(cache)) // 2
2047
+ * console.log(yield* Cache.has(cache, "a")) // false (evicted)
2048
+ * console.log(yield* Cache.has(cache, "c")) // true
2049
+ * })
2050
+ * ```
2051
+ *
2052
+ * @since 4.0.0
2053
+ * @category Combinators
2054
+ */
2055
+ const set$2 = /* @__PURE__ */ dual(3, (self, key, value) => withFiber((fiber) => {
2056
+ const exit = exitSucceed(value);
2057
+ const deferred = makeUnsafe$2();
2058
+ doneUnsafe(deferred, exit);
2059
+ const ttl = self.timeToLive(exit, key);
2060
+ if (isZero(ttl)) {
2061
+ remove$2(self.map, key);
2062
+ return void_$2;
2063
+ }
2064
+ set$3(self.map, key, {
2065
+ deferred,
2066
+ expiresAt: isFinite$1(ttl) ? fiber.getRef(ClockRef).currentTimeMillisUnsafe() + toMillis(ttl) : void 0
2067
+ });
2068
+ checkCapacity(self);
2069
+ return void_$2;
2070
+ }));
2071
+ /**
2072
+ * Invalidates the entry associated with the specified key in the cache.
2073
+ *
2074
+ * @example
2075
+ * ```ts
2076
+ * import { Cache, Effect } from "effect"
2077
+ *
2078
+ * const program = Effect.gen(function*() {
2079
+ * const cache = yield* Cache.make({
2080
+ * capacity: 10,
2081
+ * lookup: (key: string) => Effect.succeed(key.length)
2082
+ * })
2083
+ *
2084
+ * // Add a value to the cache
2085
+ * yield* Cache.get(cache, "hello")
2086
+ * console.log(yield* Cache.has(cache, "hello")) // true
2087
+ *
2088
+ * // Invalidate the entry
2089
+ * yield* Cache.invalidate(cache, "hello")
2090
+ * console.log(yield* Cache.has(cache, "hello")) // false
2091
+ *
2092
+ * // Invalidating non-existent keys doesn't error
2093
+ * yield* Cache.invalidate(cache, "nonexistent")
2094
+ *
2095
+ * // Get after invalidation will invoke lookup again
2096
+ * let lookupCount = 0
2097
+ * const cache2 = yield* Cache.make({
2098
+ * capacity: 10,
2099
+ * lookup: (key: string) =>
2100
+ * Effect.sync(() => {
2101
+ * lookupCount++
2102
+ * return key.length
2103
+ * })
2104
+ * })
2105
+ *
2106
+ * yield* Cache.get(cache2, "test") // lookupCount = 1
2107
+ * yield* Cache.invalidate(cache2, "test")
2108
+ * yield* Cache.get(cache2, "test") // lookupCount = 2 (lookup called again)
2109
+ * })
2110
+ * ```
2111
+ *
2112
+ * @since 4.0.0
2113
+ * @category Combinators
2114
+ */
2115
+ const invalidate = /* @__PURE__ */ dual(2, (self, key) => sync$1(() => {
2116
+ remove$2(self.map, key);
2117
+ }));
2118
+ /**
2119
+ * Retrieves all active keys from the cache, automatically filtering out expired entries.
2120
+ *
2121
+ * @example
2122
+ * ```ts
2123
+ * import { Cache, Effect } from "effect"
2124
+ *
2125
+ * // Basic key enumeration
2126
+ * const program = Effect.gen(function*() {
2127
+ * const cache = yield* Cache.make({
2128
+ * capacity: 10,
2129
+ * lookup: (key: string) => Effect.succeed(key.length)
2130
+ * })
2131
+ *
2132
+ * // Add some entries to the cache
2133
+ * yield* Cache.get(cache, "hello")
2134
+ * yield* Cache.get(cache, "world")
2135
+ * yield* Cache.get(cache, "cache")
2136
+ *
2137
+ * // Retrieve all active keys
2138
+ * const keys = yield* Cache.keys(cache)
2139
+ *
2140
+ * console.log(Array.from(keys)) // ["hello", "world", "cache"]
2141
+ * })
2142
+ * ```
2143
+ *
2144
+ * @since 4.0.0
2145
+ * @category Combinators
2146
+ */
2147
+ const keys = (self) => withFiber((fiber) => {
2148
+ const now = fiber.getRef(ClockRef).currentTimeMillisUnsafe();
2149
+ return succeed$3(filterMap(self.map, ([key, entry]) => {
2150
+ if (entry.expiresAt === void 0 || entry.expiresAt > now) return succeed$4(key);
2151
+ remove$2(self.map, key);
2152
+ return failVoid;
2153
+ }));
2154
+ });
2155
+ //#endregion
1611
2156
  //#region ../../node_modules/.bun/effect@https+++pkg.pr.new+Effect-TS+effect-smol+effect@8881a9b/node_modules/effect/dist/Console.js
1612
2157
  /**
1613
2158
  * A reference to the current console service in the Effect system.
@@ -1848,45 +2393,6 @@ const isLogger = (u) => hasProperty(u, TypeId$12);
1848
2393
  */
1849
2394
  const CurrentLoggers = CurrentLoggers$1;
1850
2395
  /**
1851
- * @since 4.0.0
1852
- * @category references
1853
- */
1854
- const LogToStderr = LogToStderr$1;
1855
- /**
1856
- * Transforms the output of a `Logger` using the provided function.
1857
- *
1858
- * This allows you to modify, enhance, or completely change the output format
1859
- * of an existing logger without recreating the entire logging logic.
1860
- *
1861
- * @example
1862
- * ```ts
1863
- * import { Logger } from "effect"
1864
- *
1865
- * // Create a logger that outputs objects
1866
- * const structuredLogger = Logger.make((options) => ({
1867
- * level: options.logLevel,
1868
- * message: options.message,
1869
- * timestamp: options.date.toISOString()
1870
- * }))
1871
- *
1872
- * // Transform the output to JSON strings
1873
- * const jsonStringLogger = Logger.map(
1874
- * structuredLogger,
1875
- * (output) => JSON.stringify(output)
1876
- * )
1877
- *
1878
- * // Transform to uppercase messages
1879
- * const uppercaseLogger = Logger.map(
1880
- * structuredLogger,
1881
- * (output) => ({ ...output, message: String(output.message).toUpperCase() })
1882
- * )
1883
- * ```
1884
- *
1885
- * @since 2.0.0
1886
- * @category utils
1887
- */
1888
- const map$2 = /* @__PURE__ */ dual(2, (self, f) => loggerMake((options) => f(self.log(options))));
1889
- /**
1890
2396
  * Match strings that do not contain any whitespace characters, double quotes,
1891
2397
  * or equal signs.
1892
2398
  */
@@ -2027,114 +2533,6 @@ const defaultLogger = defaultLogger$1;
2027
2533
  */
2028
2534
  const formatSimple = /* @__PURE__ */ loggerMake(/* @__PURE__ */ format(escapeDoubleQuotes));
2029
2535
  /**
2030
- * A `Logger` which outputs logs using a structured format.
2031
- *
2032
- * For example:
2033
- * ```
2034
- * {
2035
- * message: [ 'hello' ],
2036
- * level: 'INFO',
2037
- * timestamp: '2025-01-03T14:25:39.666Z',
2038
- * annotations: { key: 'value' },
2039
- * spans: { label: 0 },
2040
- * fiberId: '#1'
2041
- * }
2042
- * ```
2043
- *
2044
- * @example
2045
- * ```ts
2046
- * import { Effect, Logger } from "effect"
2047
- *
2048
- * // Use the structured format logger
2049
- * const structuredLoggerProgram = Effect.log("Hello Structured Format").pipe(
2050
- * Effect.provide(Logger.layer([Logger.formatStructured]))
2051
- * )
2052
- *
2053
- * // Perfect for JSON processing and analytics
2054
- * const analyticsProgram = Effect.gen(function*() {
2055
- * yield* Effect.log("User action", { action: "click", element: "button" })
2056
- * yield* Effect.logInfo("API call", { endpoint: "/users", duration: 150 })
2057
- * }).pipe(
2058
- * Effect.annotateLogs("sessionId", "abc123"),
2059
- * Effect.withLogSpan("request"),
2060
- * Effect.provide(Logger.layer([Logger.formatStructured]))
2061
- * )
2062
- *
2063
- * // Process structured output
2064
- * const processingLogger = Logger.map(Logger.formatStructured, (output) => {
2065
- * // Process the structured object
2066
- * const enhanced = { ...output, processed: true }
2067
- * return enhanced
2068
- * })
2069
- * ```
2070
- *
2071
- * @since 4.0.0
2072
- * @category constructors
2073
- */
2074
- const formatStructured = /* @__PURE__ */ loggerMake(({ cause, date, fiber, logLevel, message }) => {
2075
- const annotationsObj = {};
2076
- const spansObj = {};
2077
- const annotations = fiber.getRef(CurrentLogAnnotations);
2078
- for (const [key, value] of Object.entries(annotations)) annotationsObj[key] = structuredMessage(value);
2079
- const now = date.getTime();
2080
- const spans = fiber.getRef(CurrentLogSpans);
2081
- for (const [label, timestamp] of spans) spansObj[label] = now - timestamp;
2082
- const messageArr = ensure(message);
2083
- return {
2084
- message: messageArr.length === 1 ? structuredMessage(messageArr[0]) : messageArr.map(structuredMessage),
2085
- level: logLevel.toUpperCase(),
2086
- timestamp: date.toISOString(),
2087
- cause: cause.reasons.length > 0 ? causePretty(cause) : void 0,
2088
- annotations: annotationsObj,
2089
- spans: spansObj,
2090
- fiberId: formatFiberId(fiber.id)
2091
- };
2092
- });
2093
- /**
2094
- * A `Logger` which outputs logs using a structured format serialized as JSON
2095
- * on a single line.
2096
- *
2097
- * For example:
2098
- * ```
2099
- * {"message":["hello"],"level":"INFO","timestamp":"2025-01-03T14:28:57.508Z","annotations":{"key":"value"},"spans":{"label":0},"fiberId":"#1"}
2100
- * ```
2101
- *
2102
- * @example
2103
- * ```ts
2104
- * import { Effect, Logger } from "effect"
2105
- *
2106
- * // Use the JSON format logger
2107
- * const jsonLoggerProgram = Effect.log("Hello JSON Format").pipe(
2108
- * Effect.provide(Logger.layer([Logger.formatJson]))
2109
- * )
2110
- *
2111
- * // Perfect for log aggregation and processing systems
2112
- * const productionProgram = Effect.gen(function*() {
2113
- * yield* Effect.log("Server started", { port: 3000, env: "production" })
2114
- * yield* Effect.logInfo("Request received", {
2115
- * method: "GET",
2116
- * path: "/api/users"
2117
- * })
2118
- * yield* Effect.logError("Database error", { error: "Connection timeout" })
2119
- * }).pipe(
2120
- * Effect.annotateLogs("service", "api-server"),
2121
- * Effect.withLogSpan("request-processing"),
2122
- * Effect.provide(Logger.layer([Logger.formatJson]))
2123
- * )
2124
- *
2125
- * // Send to external logging service
2126
- * const externalLogger = Logger.map(Logger.formatJson, (jsonString) => {
2127
- * // Send to Elasticsearch, CloudWatch, etc.
2128
- * console.log("Sending to external service:", jsonString)
2129
- * return jsonString
2130
- * })
2131
- * ```
2132
- *
2133
- * @since 4.0.0
2134
- * @category constructors
2135
- */
2136
- const formatJson = /* @__PURE__ */ map$2(formatStructured, formatJson$1);
2137
- /**
2138
2536
  * Returns a new `Logger` which will aggregate logs output by the specified
2139
2537
  * `Logger` over the provided `window`. After the `window` has elapsed, the
2140
2538
  * provided `flush` function will be called with the logs aggregated during
@@ -2199,104 +2597,6 @@ const batched = /* @__PURE__ */ dual(2, (self, options) => flatMap$1(scope, (sco
2199
2597
  }))));
2200
2598
  }));
2201
2599
  /**
2202
- * A `Logger` which outputs logs in a "pretty" format and writes them to the
2203
- * console.
2204
- *
2205
- * For example:
2206
- * ```
2207
- * [09:37:17.579] INFO (#1) label=0ms: hello
2208
- * key: value
2209
- * ```
2210
- *
2211
- * @example
2212
- * ```ts
2213
- * import { Effect, Logger } from "effect"
2214
- *
2215
- * // Use the pretty console logger with default settings
2216
- * const basicPretty = Effect.log("Hello Pretty Format").pipe(
2217
- * Effect.provide(Logger.layer([Logger.consolePretty()]))
2218
- * )
2219
- *
2220
- * // Configure pretty logger options
2221
- * const customPretty = Logger.consolePretty({
2222
- * colors: true,
2223
- * stderr: false,
2224
- * mode: "tty",
2225
- * formatDate: (date) => date.toLocaleTimeString()
2226
- * })
2227
- *
2228
- * // Perfect for development environment
2229
- * const developmentProgram = Effect.gen(function*() {
2230
- * yield* Effect.log("Application starting")
2231
- * yield* Effect.logInfo("Database connected")
2232
- * yield* Effect.logWarning("High memory usage detected")
2233
- * }).pipe(
2234
- * Effect.annotateLogs("environment", "development"),
2235
- * Effect.withLogSpan("startup"),
2236
- * Effect.provide(Logger.layer([customPretty]))
2237
- * )
2238
- *
2239
- * // Disable colors for CI/CD environments
2240
- * const ciLogger = Logger.consolePretty({ colors: false })
2241
- * ```
2242
- *
2243
- * @since 4.0.0
2244
- * @category constructors
2245
- */
2246
- const consolePretty = consolePretty$1;
2247
- /**
2248
- * A `Logger` which includes log messages as tracer span events.
2249
- *
2250
- * This logger integrates logging with distributed tracing by recording
2251
- * all log messages as events on the current trace span, making them visible
2252
- * in tracing tools like OpenTelemetry, Jaeger, or Zipkin.
2253
- *
2254
- * **Note**: This logger is included in the default set of loggers for all
2255
- * Effect programs, so log messages automatically appear as span events unless
2256
- * you override the default loggers.
2257
- *
2258
- * @example
2259
- * ```ts
2260
- * import { Effect, Logger } from "effect"
2261
- *
2262
- * // Tracer logger is included by default - logs automatically become span events
2263
- * const defaultProgram = Effect.gen(function*() {
2264
- * yield* Effect.log("This automatically becomes a span event")
2265
- * yield* Effect.logInfo("Processing data")
2266
- * })
2267
- *
2268
- * // Explicitly combine tracer logger with other loggers
2269
- * const observabilityProgram = Effect.gen(function*() {
2270
- * yield* Effect.log("Operation started")
2271
- * yield* Effect.logInfo("Processing data")
2272
- * yield* Effect.logError("Error occurred")
2273
- * }).pipe(
2274
- * Effect.withLogSpan("data-processing"),
2275
- * Effect.provide(Logger.layer([
2276
- * Logger.tracerLogger,
2277
- * Logger.consoleJson
2278
- * ]))
2279
- * )
2280
- *
2281
- * // Perfect for correlating logs with traces in distributed systems
2282
- * const distributedProgram = Effect.gen(function*() {
2283
- * yield* Effect.log("Step 1: Fetching user data")
2284
- * yield* Effect.sleep("100 millis")
2285
- * yield* Effect.log("Step 2: Processing payment")
2286
- * yield* Effect.sleep("200 millis")
2287
- * yield* Effect.log("Step 3: Sending confirmation")
2288
- * }).pipe(
2289
- * Effect.withLogSpan("payment-workflow"),
2290
- * Effect.annotateLogs("userId", "user-123"),
2291
- * Effect.provide(Logger.layer([Logger.tracerLogger]))
2292
- * )
2293
- * ```
2294
- *
2295
- * @since 4.0.0
2296
- * @category constructors
2297
- */
2298
- const tracerLogger = tracerLogger$1;
2299
- /**
2300
2600
  * Creates a `Layer` which will overwrite the current set of loggers with the
2301
2601
  * specified array of `loggers`.
2302
2602
  *
@@ -2573,7 +2873,7 @@ const get = (self) => sync(() => self.ref.current);
2573
2873
  * @since 2.0.0
2574
2874
  * @category setters
2575
2875
  */
2576
- const set$1 = /* @__PURE__ */ dual(2, (self, value) => sync(() => set$2(self.ref, value)));
2876
+ const set$1 = /* @__PURE__ */ dual(2, (self, value) => sync(() => set$4(self.ref, value)));
2577
2877
  /**
2578
2878
  * Atomically modifies the value of the Ref using the given function.
2579
2879
  *
@@ -13651,30 +13951,6 @@ const makeSchemaPrimitive = (tag, schema) => {
13651
13951
  */
13652
13952
  const boolean$2 = /* @__PURE__ */ makeSchemaPrimitive("Boolean", Boolean$1);
13653
13953
  /**
13654
- * Creates a primitive that parses floating-point numbers from string input.
13655
- *
13656
- * @example
13657
- * ```ts
13658
- * import { Effect } from "effect"
13659
- * import { Primitive } from "effect/unstable/cli"
13660
- *
13661
- * const parseFloat = Effect.gen(function*() {
13662
- * const result1 = yield* Primitive.float.parse("3.14")
13663
- * console.log(result1) // 3.14
13664
- *
13665
- * const result2 = yield* Primitive.float.parse("-42.5")
13666
- * console.log(result2) // -42.5
13667
- *
13668
- * const result3 = yield* Primitive.float.parse("0")
13669
- * console.log(result3) // 0
13670
- * })
13671
- * ```
13672
- *
13673
- * @since 4.0.0
13674
- * @category constructors
13675
- */
13676
- const float = /* @__PURE__ */ makeSchemaPrimitive("Float", Finite);
13677
- /**
13678
13954
  * Creates a primitive that parses integer numbers from string input.
13679
13955
  *
13680
13956
  * @example
@@ -13699,30 +13975,6 @@ const float = /* @__PURE__ */ makeSchemaPrimitive("Float", Finite);
13699
13975
  */
13700
13976
  const integer$2 = /* @__PURE__ */ makeSchemaPrimitive("Integer", Int);
13701
13977
  /**
13702
- * Creates a primitive that parses Date objects from string input.
13703
- *
13704
- * @example
13705
- * ```ts
13706
- * import { Effect } from "effect"
13707
- * import { Primitive } from "effect/unstable/cli"
13708
- *
13709
- * const parseDate = Effect.gen(function*() {
13710
- * const result1 = yield* Primitive.date.parse("2023-12-25")
13711
- * console.log(result1) // Date object for December 25, 2023
13712
- *
13713
- * const result2 = yield* Primitive.date.parse("2023-12-25T10:30:00Z")
13714
- * console.log(result2) // Date object with time
13715
- *
13716
- * const result3 = yield* Primitive.date.parse("Dec 25, 2023")
13717
- * console.log(result3) // Date object parsed from natural format
13718
- * })
13719
- * ```
13720
- *
13721
- * @since 4.0.0
13722
- * @category constructors
13723
- */
13724
- const date = /* @__PURE__ */ makeSchemaPrimitive("Date", DateValid);
13725
- /**
13726
13978
  * Creates a primitive that accepts any string value without validation.
13727
13979
  *
13728
13980
  * @example
@@ -13785,28 +14037,6 @@ const choice$2 = (choices) => {
13785
14037
  return Object.assign(primitive, { choiceKeys: choices.map(([key]) => key) });
13786
14038
  };
13787
14039
  /**
13788
- * A sentinel primitive that always fails to parse a value.
13789
- *
13790
- * Used for flags that don't accept values.
13791
- *
13792
- * @example
13793
- * ```ts
13794
- * import { Effect } from "effect"
13795
- * import { Primitive } from "effect/unstable/cli"
13796
- *
13797
- * const program = Effect.gen(function*() {
13798
- * // This will always fail - useful for boolean flags
13799
- * const result = yield* Primitive.none.parse("any-value")
13800
- * })
13801
- *
13802
- * // The above effect will fail with "This option does not accept values"
13803
- * ```
13804
- *
13805
- * @since 4.0.0
13806
- * @category constructors
13807
- */
13808
- const none$2 = /* @__PURE__ */ makePrimitive("None", () => fail$1("This option does not accept values"));
13809
- /**
13810
14040
  * Gets a human-readable type name for a primitive.
13811
14041
  *
13812
14042
  * Used for generating help documentation.
@@ -14051,34 +14281,6 @@ const choiceWithValue$1 = (kind, name, choices) => makeSingle({
14051
14281
  const choice$1 = (kind, name, choices) => {
14052
14282
  return choiceWithValue$1(kind, name, choices.map((value) => [value, value]));
14053
14283
  };
14054
- /**
14055
- * Creates an empty sentinel parameter that always fails to parse.
14056
- *
14057
- * This is useful for creating placeholder parameters or for combinators.
14058
- *
14059
- * @example
14060
- * ```ts
14061
- * import * as Param from "effect/unstable/cli/Param"
14062
- *
14063
- * // @internal - this module is not exported publicly
14064
- *
14065
- * // Create a none parameter for composition
14066
- * const noneParam = Param.none(Param.flagKind)
14067
- *
14068
- * // Often used in conditional parameter creation
14069
- * const conditionalParam = process.env.NODE_ENV === "production"
14070
- * ? Param.string(Param.flagKind, "my-dev-flag")
14071
- * : Param.none(Param.flagKind)
14072
- * ```
14073
- *
14074
- * @since 4.0.0
14075
- * @category constructors
14076
- */
14077
- const none$1 = (kind) => makeSingle({
14078
- name: "__none__",
14079
- primitiveType: none$2,
14080
- kind
14081
- });
14082
14284
  const FLAG_DASH_REGEXP = /^-+/;
14083
14285
  /**
14084
14286
  * Adds an alias to an option.
@@ -14161,7 +14363,7 @@ const withDescription$2 = /* @__PURE__ */ dual(2, (self, description) => {
14161
14363
  * @category combinators
14162
14364
  */
14163
14365
  const map$1 = /* @__PURE__ */ dual(2, (self, f) => {
14164
- const parse = (args) => map$3(self.parse(args), ([operands, value]) => [operands, f(value)]);
14366
+ const parse = (args) => map$2(self.parse(args), ([operands, value]) => [operands, f(value)]);
14165
14367
  return Object.assign(Object.create(Proto$7), {
14166
14368
  _tag: "Map",
14167
14369
  kind: self.kind,
@@ -14207,7 +14409,7 @@ const transform = (self, f) => Object.assign(Object.create(Proto$7), {
14207
14409
  * @since 4.0.0
14208
14410
  * @category combinators
14209
14411
  */
14210
- const mapEffect = /* @__PURE__ */ dual(2, (self, f) => transform(self, (parse) => (args) => flatMap(parse(args), ([leftover, a]) => f(a).pipe(map$3((b) => [leftover, b])))));
14412
+ const mapEffect = /* @__PURE__ */ dual(2, (self, f) => transform(self, (parse) => (args) => flatMap(parse(args), ([leftover, a]) => f(a).pipe(map$2((b) => [leftover, b])))));
14211
14413
  /**
14212
14414
  * Creates an optional option that returns None when not provided.
14213
14415
  *
@@ -14230,7 +14432,7 @@ const mapEffect = /* @__PURE__ */ dual(2, (self, f) => transform(self, (parse) =
14230
14432
  * @category combinators
14231
14433
  */
14232
14434
  const optional$1 = (param) => {
14233
- const parse = (args) => param.parse(args).pipe(map$3(([leftover, value]) => [leftover, some(value)]), catchTag("MissingOption", () => succeed([args.arguments, none$3()])), catchTag("MissingArgument", () => succeed([args.arguments, none$3()])));
14435
+ const parse = (args) => param.parse(args).pipe(map$2(([leftover, value]) => [leftover, some(value)]), catchTag("MissingOption", () => succeed([args.arguments, none()])), catchTag("MissingArgument", () => succeed([args.arguments, none()])));
14234
14436
  return Object.assign(Object.create(Proto$7), {
14235
14437
  _tag: "Optional",
14236
14438
  kind: param.kind,
@@ -14239,42 +14441,6 @@ const optional$1 = (param) => {
14239
14441
  });
14240
14442
  };
14241
14443
  /**
14242
- * Makes an option optional by providing a default value.
14243
- *
14244
- * This combinator is useful when you want to make an existing option optional
14245
- * by providing a fallback value that will be used when the option is not
14246
- * provided on the command line.
14247
- *
14248
- * @example
14249
- * ```ts
14250
- * import * as Param from "effect/unstable/cli/Param"
14251
- *
14252
- * // @internal - this module is not exported publicly
14253
- *
14254
- * // Using the pipe operator to make an option optional
14255
- * const port = Param.integer(Param.flagKind, "port").pipe(
14256
- * Param.withDefault(8080)
14257
- * )
14258
- *
14259
- * // Can also be used with other combinators
14260
- * const verbose = Param.boolean(Param.flagKind, "verbose").pipe(
14261
- * Param.withAlias("-v"),
14262
- * Param.withDescription("Enable verbose output"),
14263
- * Param.withDefault(false)
14264
- * )
14265
- * ```
14266
- *
14267
- * @since 4.0.0
14268
- * @category combinators
14269
- */
14270
- const withDefault$1 = /* @__PURE__ */ dual(2, (self, defaultValue) => {
14271
- if (!isEffect(defaultValue)) return map$1(optional$1(self), getOrElse(() => defaultValue));
14272
- return mapEffect(optional$1(self), match({
14273
- onNone: () => defaultValue,
14274
- onSome: succeed
14275
- }));
14276
- });
14277
- /**
14278
14444
  * Creates a variadic parameter that can be specified multiple times.
14279
14445
  *
14280
14446
  * This is the base combinator for creating parameters that accept multiple values.
@@ -14829,22 +14995,6 @@ const choiceWithValue = (name, choices) => choiceWithValue$1(flagKind, name, cho
14829
14995
  */
14830
14996
  const choice = (name, choices) => choice$1(flagKind, name, choices);
14831
14997
  /**
14832
- * Creates an empty sentinel flag that always fails to parse.
14833
- * This is useful for creating placeholder flags or for combinators.
14834
- *
14835
- * @example
14836
- * ```ts
14837
- * import { Flag } from "effect/unstable/cli"
14838
- *
14839
- * // Used as a placeholder in flag combinators
14840
- * const conditionalFlag = true ? Flag.string("value") : Flag.none
14841
- * ```
14842
- *
14843
- * @since 4.0.0
14844
- * @category constructors
14845
- */
14846
- const none = /* @__PURE__ */ none$1(flagKind);
14847
- /**
14848
14998
  * Adds an alias to a flag, allowing it to be referenced by multiple names.
14849
14999
  *
14850
15000
  * @example
@@ -14915,28 +15065,6 @@ const withDescription$1 = /* @__PURE__ */ dual(2, (self, description) => withDes
14915
15065
  */
14916
15066
  const optional = (param) => optional$1(param);
14917
15067
  /**
14918
- * Provides a default value for a flag when it's not specified.
14919
- *
14920
- * @example
14921
- * ```ts
14922
- * import { Flag } from "effect/unstable/cli"
14923
- *
14924
- * const portFlag = Flag.integer("port").pipe(
14925
- * Flag.withDefault(8080)
14926
- * )
14927
- * // If --port is not provided, defaults to 8080
14928
- *
14929
- * const hostFlag = Flag.string("host").pipe(
14930
- * Flag.withDefault("localhost")
14931
- * )
14932
- * // If --host is not provided, defaults to "localhost"
14933
- * ```
14934
- *
14935
- * @since 4.0.0
14936
- * @category optionality
14937
- */
14938
- const withDefault = withDefault$1;
14939
- /**
14940
15068
  * Transforms the parsed value of a flag using a mapping function.
14941
15069
  *
14942
15070
  * @example
@@ -15142,7 +15270,7 @@ const makeCommand = (options) => {
15142
15270
  const subcommandDocs = [];
15143
15271
  for (const group of subcommands) subcommandDocs.push({
15144
15272
  group: group.group,
15145
- commands: map$4(group.commands, (subcommand) => ({
15273
+ commands: map$3(group.commands, (subcommand) => ({
15146
15274
  name: subcommand.name,
15147
15275
  alias: subcommand.alias,
15148
15276
  shortDescription: subcommand.shortDescription,
@@ -15883,7 +16011,7 @@ const Completions = /* @__PURE__ */ action({
15883
16011
  "zsh",
15884
16012
  "fish",
15885
16013
  "sh"
15886
- ]).pipe(optional, /* @__PURE__ */ map((v) => map$5(v, (s) => s === "sh" ? "bash" : s)), /* @__PURE__ */ withDescription$1("Print shell completion script")),
16014
+ ]).pipe(optional, /* @__PURE__ */ map((v) => map$4(v, (s) => s === "sh" ? "bash" : s)), /* @__PURE__ */ withDescription$1("Print shell completion script")),
15887
16015
  run: (shell, { command }) => gen(function* () {
15888
16016
  if (isNone(shell)) return;
15889
16017
  const descriptor = fromCommand(command);
@@ -16561,10 +16689,10 @@ const runWith = (command, config) => {
16561
16689
  program = provideService(program, LogLevel, logLevel);
16562
16690
  const services = match(logLevel, {
16563
16691
  onNone: () => empty$5(),
16564
- onSome: (level) => make$24(MinimumLogLevel, level)
16692
+ onSome: (level) => make$25(MinimumLogLevel, level)
16565
16693
  });
16566
16694
  yield* provideServices(program, services);
16567
- }, catchFilter((error) => isCliError(error) && error._tag === "ShowHelp" ? succeed$3(error) : fail$3(error), (error) => showHelp(command, error.commandPath)), catchFilter((e) => isQuitError(e) ? succeed$3(e) : fail$3(e), (_) => interrupt));
16695
+ }, catchFilter((error) => isCliError(error) && error._tag === "ShowHelp" ? succeed$4(error) : fail$3(error), (error) => showHelp(command, error.commandPath)), catchFilter((e) => isQuitError(e) ? succeed$4(e) : fail$3(e), (_) => interrupt));
16568
16696
  };
16569
16697
  //#endregion
16570
16698
  //#region ../../packages/t3-shared/src/Net.ts
@@ -16788,7 +16916,7 @@ function fixPath() {
16788
16916
  if (result) process.env.PATH = result;
16789
16917
  } catch {}
16790
16918
  }
16791
- const expandHomePath = fn(function* (input) {
16919
+ const expandHomePath$1 = fn(function* (input) {
16792
16920
  const { join } = yield* Path$1;
16793
16921
  if (input === "~") return OS.homedir();
16794
16922
  if (input.startsWith("~/") || input.startsWith("~\\")) return join(OS.homedir(), input.slice(2));
@@ -16797,7 +16925,7 @@ const expandHomePath = fn(function* (input) {
16797
16925
  const resolveStateDir = fn(function* (raw) {
16798
16926
  const { join, resolve } = yield* Path$1;
16799
16927
  if (!raw || raw.trim().length === 0) return join(OS.homedir(), ".t3", "userdata");
16800
- return resolve(yield* expandHomePath(raw.trim()));
16928
+ return resolve(yield* expandHomePath$1(raw.trim()));
16801
16929
  });
16802
16930
  //#endregion
16803
16931
  //#region ../../packages/t3-contracts/src/baseSchemas.ts
@@ -16987,6 +17115,8 @@ const MODEL_SLUG_ALIASES_BY_PROVIDER = { codex: {
16987
17115
  const ORCHESTRATION_WS_METHODS = {
16988
17116
  getSnapshot: "orchestration.getSnapshot",
16989
17117
  getThreadSnapshot: "orchestration.getThreadSnapshot",
17118
+ subscribeShell: "orchestration.subscribeShell",
17119
+ subscribeThread: "orchestration.subscribeThread",
16990
17120
  syncExternalThreads: "orchestration.syncExternalThreads",
16991
17121
  dispatchCommand: "orchestration.dispatchCommand",
16992
17122
  getTurnDiff: "orchestration.getTurnDiff",
@@ -17233,7 +17363,8 @@ const ProjectMetaUpdateCommand = Struct({
17233
17363
  const ProjectDeleteCommand = Struct({
17234
17364
  type: Literal("project.delete"),
17235
17365
  commandId: CommandId,
17236
- projectId: ProjectId
17366
+ projectId: ProjectId,
17367
+ force: optional$2(Literal(true))
17237
17368
  });
17238
17369
  const ThreadCreateCommand = Struct({
17239
17370
  type: Literal("thread.create"),
@@ -18900,6 +19031,7 @@ const STATIC_KEYBINDING_COMMANDS = [
18900
19031
  "terminal.new",
18901
19032
  "terminal.close",
18902
19033
  "diff.toggle",
19034
+ "commandPalette.toggle",
18903
19035
  "chat.new",
18904
19036
  "chat.newLocal",
18905
19037
  "editor.openFavorite",
@@ -18989,6 +19121,21 @@ const ProjectWriteFileInput = Struct({
18989
19121
  });
18990
19122
  const ProjectWriteFileResult = Struct({ relativePath: TrimmedNonEmptyString });
18991
19123
  //#endregion
19124
+ //#region ../../packages/t3-contracts/src/filesystem.ts
19125
+ const FILESYSTEM_PATH_MAX_LENGTH = 512;
19126
+ const FilesystemBrowseInput = Struct({
19127
+ partialPath: TrimmedNonEmptyString.check(isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)),
19128
+ cwd: optional$2(TrimmedNonEmptyString.check(isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)))
19129
+ });
19130
+ const FilesystemBrowseEntry = Struct({
19131
+ name: TrimmedNonEmptyString,
19132
+ fullPath: TrimmedNonEmptyString
19133
+ });
19134
+ const FilesystemBrowseResult = Struct({
19135
+ parentPath: TrimmedNonEmptyString,
19136
+ entries: Array$1(FilesystemBrowseEntry)
19137
+ });
19138
+ //#endregion
18992
19139
  //#region ../../packages/t3-contracts/src/editor.ts
18993
19140
  const EDITORS = [
18994
19141
  {
@@ -19040,6 +19187,14 @@ const OpenInEditorInput = Struct({
19040
19187
  editor: EditorId
19041
19188
  });
19042
19189
  //#endregion
19190
+ //#region ../../packages/t3-contracts/src/generalChat.ts
19191
+ const GeneralChatConfig = Struct({ workspaceRoot: TrimmedNonEmptyString });
19192
+ const GeneralChatEnsureResult = Struct({
19193
+ projectId: ProjectId,
19194
+ workspaceRoot: TrimmedNonEmptyString,
19195
+ created: Boolean$2
19196
+ });
19197
+ //#endregion
19043
19198
  //#region ../../packages/t3-contracts/src/server.ts
19044
19199
  const KeybindingsMalformedConfigIssue = Struct({
19045
19200
  kind: Literal("keybindings.malformed-config"),
@@ -19083,7 +19238,8 @@ const ServerConfig = Struct({
19083
19238
  issues: ServerConfigIssues,
19084
19239
  providers: ServerProviderStatuses,
19085
19240
  availableEditors: Array$1(EditorId),
19086
- projectPolicy: ServerProjectPolicy
19241
+ projectPolicy: ServerProjectPolicy,
19242
+ generalChat: GeneralChatConfig
19087
19243
  });
19088
19244
  const ServerUpsertKeybindingResult = Struct({
19089
19245
  keybindings: ResolvedKeybindingsConfig,
@@ -19093,7 +19249,8 @@ const ServerConfigUpdatedPayload = Struct({
19093
19249
  reason: Literals(["keybindings", "projectPolicy"]),
19094
19250
  issues: ServerConfigIssues,
19095
19251
  providers: ServerProviderStatuses,
19096
- projectPolicy: ServerProjectPolicy
19252
+ projectPolicy: ServerProjectPolicy,
19253
+ generalChat: GeneralChatConfig
19097
19254
  });
19098
19255
  const ServerProviderUpdatedPayload = Struct({ providers: ServerProviderStatuses });
19099
19256
  //#endregion
@@ -19105,6 +19262,8 @@ const WS_METHODS = {
19105
19262
  projectsEnsure: "projects.ensure",
19106
19263
  projectsSearchEntries: "projects.searchEntries",
19107
19264
  projectsWriteFile: "projects.writeFile",
19265
+ generalChatEnsure: "generalChat.ensure",
19266
+ filesystemBrowse: "filesystem.browse",
19108
19267
  shellOpenInEditor: "shell.openInEditor",
19109
19268
  gitPull: "git.pull",
19110
19269
  gitStatus: "git.status",
@@ -19204,6 +19363,8 @@ const WebSocketRequestBody = Union([
19204
19363
  tagRequestBody(WS_METHODS.projectsEnsure, ProjectEnsureInput),
19205
19364
  tagRequestBody(WS_METHODS.projectsSearchEntries, ProjectSearchEntriesInput),
19206
19365
  tagRequestBody(WS_METHODS.projectsWriteFile, ProjectWriteFileInput),
19366
+ tagRequestBody(WS_METHODS.generalChatEnsure, Struct({})),
19367
+ tagRequestBody(WS_METHODS.filesystemBrowse, FilesystemBrowseInput),
19207
19368
  tagRequestBody(WS_METHODS.shellOpenInEditor, OpenInEditorInput),
19208
19369
  tagRequestBody(WS_METHODS.gitPull, GitPullInput),
19209
19370
  tagRequestBody(WS_METHODS.gitStatus, GitStatusInput),
@@ -19541,7 +19702,7 @@ const launchDetached = (launch) => gen(function* () {
19541
19702
  });
19542
19703
  const make$9 = gen(function* () {
19543
19704
  const open = yield* tryPromise({
19544
- try: () => import("./open-Cm7F9p66.mjs"),
19705
+ try: () => import("./open-BM96ykXl.mjs"),
19545
19706
  catch: (cause) => new OpenError({
19546
19707
  message: "failed to load browser opener",
19547
19708
  cause
@@ -19609,7 +19770,7 @@ const make$8 = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, t
19609
19770
  migration_id,
19610
19771
  name
19611
19772
  })))}`.withoutTransform;
19612
- const latestMigration = map$3(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$5(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
19773
+ const latestMigration = map$2(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, (_) => map$4(fromNullishOr(_[0]), ({ created_at, migration_id, name }) => ({
19613
19774
  id: migration_id,
19614
19775
  name,
19615
19776
  createdAt: created_at
@@ -19634,7 +19795,7 @@ const make$8 = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, t
19634
19795
  pg: () => sql`LOCK TABLE ${sql(table)} IN ACCESS EXCLUSIVE MODE`,
19635
19796
  orElse: () => void_$1
19636
19797
  });
19637
- const [latestMigrationId, current] = yield* all([map$3(latestMigration, match({
19798
+ const [latestMigrationId, current] = yield* all([map$2(latestMigration, match({
19638
19799
  onNone: () => 0,
19639
19800
  onSome: (_) => _.id
19640
19801
  })), loader]);
@@ -19668,12 +19829,12 @@ const make$8 = ({ dumpSchema = () => void_$1 }) => ({ loader, schemaDirectory, t
19668
19829
  if (schemaDirectory && completed.length > 0) yield* dumpSchema(`${schemaDirectory}/_schema.sql`, table).pipe(catchCause((cause) => logInfo$1("Could not dump schema", cause)));
19669
19830
  return completed;
19670
19831
  });
19671
- const migrationOrder = /* @__PURE__ */ make$25(([a], [b]) => Number$2(a, b));
19832
+ const migrationOrder = /* @__PURE__ */ make$26(([a], [b]) => Number$2(a, b));
19672
19833
  /**
19673
19834
  * @since 4.0.0
19674
19835
  * @category loaders
19675
19836
  */
19676
- const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$4(([key, id, name]) => [
19837
+ const fromRecord = (migrations) => pipe(Object.keys(migrations), flatMapNullishOr((_) => _.match(/^(\d+)_(.+)$/)), map$3(([key, id, name]) => [
19677
19838
  Number(id),
19678
19839
  name,
19679
19840
  succeed(migrations[key])
@@ -20305,6 +20466,20 @@ const normalizePersistedJsonColumns = gen(function* () {
20305
20466
  //#region src/persistence/Migrations/020_NormalizePersistedJsonColumns.ts
20306
20467
  var _020_NormalizePersistedJsonColumns_default = normalizePersistedJsonColumns;
20307
20468
  //#endregion
20469
+ //#region src/persistence/Migrations/021_CleanupInvalidProjectionPendingApprovals.ts
20470
+ var _021_CleanupInvalidProjectionPendingApprovals_default = gen(function* () {
20471
+ yield* (yield* SqlClient)`
20472
+ DELETE FROM projection_pending_approvals
20473
+ WHERE request_id NOT IN (
20474
+ SELECT DISTINCT json_extract(payload_json, '$.requestId')
20475
+ FROM projection_thread_activities
20476
+ WHERE kind = 'approval.requested'
20477
+ AND json_valid(payload_json) = 1
20478
+ AND json_extract(payload_json, '$.requestId') IS NOT NULL
20479
+ )
20480
+ `;
20481
+ });
20482
+ //#endregion
20308
20483
  //#region src/persistence/Migrations.ts
20309
20484
  /**
20310
20485
  * Migrations - Migration runner with inline loader
@@ -20345,7 +20520,8 @@ const loader = fromRecord({
20345
20520
  "17_ProjectionThreadsArchivedAt": _017_ProjectionThreadsArchivedAt_default,
20346
20521
  "18_CanonicalizeModelSelections": _018_CanonicalizeModelSelections_default,
20347
20522
  "19_NormalizeProjectionModelSelectionJson": _019_NormalizeProjectionModelSelectionJson_default,
20348
- "20_NormalizePersistedJsonColumns": _020_NormalizePersistedJsonColumns_default
20523
+ "20_NormalizePersistedJsonColumns": _020_NormalizePersistedJsonColumns_default,
20524
+ "21_CleanupInvalidProjectionPendingApprovals": _021_CleanupInvalidProjectionPendingApprovals_default
20349
20525
  });
20350
20526
  /**
20351
20527
  * Migrator run function - no schema dumping needed
@@ -20370,8 +20546,8 @@ const runMigrations = gen(function* () {
20370
20546
  //#endregion
20371
20547
  //#region src/persistence/Layers/Sqlite.ts
20372
20548
  const defaultSqliteClientLoaders = {
20373
- bun: () => import("./SqliteClient-BBxZHTRF.mjs"),
20374
- node: () => import("./NodeSqliteClient-BPzkJKIG.mjs")
20549
+ bun: () => import("./SqliteClient-9lnXlJby.mjs"),
20550
+ node: () => import("./NodeSqliteClient-BPNNnMBz.mjs")
20375
20551
  };
20376
20552
  const makeRuntimeSqliteLayer = (config) => gen(function* () {
20377
20553
  const loader = defaultSqliteClientLoaders[process.versions.bun !== void 0 ? "bun" : "node"];
@@ -20576,7 +20752,7 @@ const make$7 = gen(function* () {
20576
20752
  threadId: input.threadId,
20577
20753
  fromTurnCount: 0,
20578
20754
  toTurnCount: input.toTurnCount
20579
- }).pipe(map$3((result) => result));
20755
+ }).pipe(map$2((result) => result));
20580
20756
  return {
20581
20757
  getTurnDiff,
20582
20758
  getFullThreadDiff
@@ -20707,7 +20883,7 @@ const makeGitService = gen(function* () {
20707
20883
  const [stdout, stderr, exitCode] = yield* all([
20708
20884
  collectOutput(commandInput, child.stdout, maxOutputBytes),
20709
20885
  collectOutput(commandInput, child.stderr, maxOutputBytes),
20710
- child.exitCode.pipe(map$3((value) => Number(value)), mapError(toGitCommandError(commandInput, "failed to report exit code.")))
20886
+ child.exitCode.pipe(map$2((value) => Number(value)), mapError(toGitCommandError(commandInput, "failed to report exit code.")))
20711
20887
  ], { concurrency: "unbounded" });
20712
20888
  if (!input.allowNonZeroExit && exitCode !== 0) {
20713
20889
  const trimmedStderr = stderr.trim();
@@ -20779,7 +20955,7 @@ const makeCheckpointStore = gen(function* () {
20779
20955
  "HEAD^{commit}"
20780
20956
  ],
20781
20957
  allowNonZeroExit: true
20782
- }).pipe(map$3((result) => {
20958
+ }).pipe(map$2((result) => {
20783
20959
  if (result.code !== 0) return null;
20784
20960
  const commit = result.stdout.trim();
20785
20961
  return commit.length > 0 ? commit : null;
@@ -20793,7 +20969,7 @@ const makeCheckpointStore = gen(function* () {
20793
20969
  "HEAD"
20794
20970
  ],
20795
20971
  allowNonZeroExit: true
20796
- }).pipe(map$3((result) => result.code === 0));
20972
+ }).pipe(map$2((result) => result.code === 0));
20797
20973
  const resolveCheckpointCommit = (cwd, checkpointRef) => git.execute({
20798
20974
  operation: "CheckpointStore.resolveCheckpointCommit",
20799
20975
  cwd,
@@ -20804,7 +20980,7 @@ const makeCheckpointStore = gen(function* () {
20804
20980
  `${checkpointRef}^{commit}`
20805
20981
  ],
20806
20982
  allowNonZeroExit: true
20807
- }).pipe(map$3((result) => {
20983
+ }).pipe(map$2((result) => {
20808
20984
  if (result.code !== 0) return null;
20809
20985
  const commit = result.stdout.trim();
20810
20986
  return commit.length > 0 ? commit : null;
@@ -20832,7 +21008,7 @@ const makeCheckpointStore = gen(function* () {
20832
21008
  cwd,
20833
21009
  args: ["rev-parse", "--is-inside-work-tree"],
20834
21010
  allowNonZeroExit: true
20835
- }).pipe(map$3((result) => result.code === 0 && result.stdout.trim() === "true"), catch_(() => succeed(false)));
21011
+ }).pipe(map$2((result) => result.code === 0 && result.stdout.trim() === "true"), catch_(() => succeed(false)));
20836
21012
  const captureCheckpoint = (input) => gen(function* () {
20837
21013
  const operation = "CheckpointStore.captureCheckpoint";
20838
21014
  yield* acquireUseRelease(fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }), (tempDir) => gen(function* () {
@@ -20907,7 +21083,7 @@ const makeCheckpointStore = gen(function* () {
20907
21083
  cause: error
20908
21084
  })) }));
20909
21085
  });
20910
- const hasCheckpointRef = (input) => resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(map$3((commit) => commit !== null));
21086
+ const hasCheckpointRef = (input) => resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(map$2((commit) => commit !== null));
20911
21087
  const restoreCheckpoint = (input) => gen(function* () {
20912
21088
  const operation = "CheckpointStore.restoreCheckpoint";
20913
21089
  let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
@@ -21050,7 +21226,7 @@ const findOne = (options) => {
21050
21226
  const findOneOption = (options) => {
21051
21227
  const encodeRequest = encodeEffect(options.Request);
21052
21228
  const decode = decodeUnknownEffect(options.Result);
21053
- return (request) => flatMap(flatMap(encodeRequest(request), options.execute), (arr) => isReadonlyArrayNonEmpty(arr) ? asSome(decode(arr[0])) : succeedNone);
21229
+ return (request) => flatMap(flatMap(encodeRequest(request), options.execute), (arr) => isReadonlyArrayNonEmpty(arr) ? asSome$1(decode(arr[0])) : succeedNone$1);
21054
21230
  };
21055
21231
  //#endregion
21056
21232
  //#region src/persistence/Errors.ts
@@ -21234,9 +21410,9 @@ const makeProjectionCheckpointRepository = gen(function* () {
21234
21410
  checkpointTurnCount: row.checkpointTurnCount
21235
21411
  }).pipe(flatMap(() => upsertProjectionCheckpointRow(row))));
21236
21412
  const upsert = (row) => upsertCheckpointRow(row).pipe(mapError(toPersistenceSqlOrDecodeError$6("ProjectionCheckpointRepository.upsert:query", "ProjectionCheckpointRepository.upsert:encodeRequest")));
21237
- const listByThreadId = (input) => listProjectionCheckpointRows(input).pipe(mapError(toPersistenceSqlOrDecodeError$6("ProjectionCheckpointRepository.listByThreadId:query", "ProjectionCheckpointRepository.listByThreadId:decodeRows")), map$3((rows) => rows));
21413
+ const listByThreadId = (input) => listProjectionCheckpointRows(input).pipe(mapError(toPersistenceSqlOrDecodeError$6("ProjectionCheckpointRepository.listByThreadId:query", "ProjectionCheckpointRepository.listByThreadId:decodeRows")), map$2((rows) => rows));
21238
21414
  const getByThreadAndTurnCount = (input) => getProjectionCheckpointRow(input).pipe(mapError(toPersistenceSqlOrDecodeError$6("ProjectionCheckpointRepository.getByThreadAndTurnCount:query", "ProjectionCheckpointRepository.getByThreadAndTurnCount:decodeRow")), flatMap((rowOption) => match(rowOption, {
21239
- onNone: () => succeed(none$3()),
21415
+ onNone: () => succeed(none()),
21240
21416
  onSome: (row) => succeed(some(row))
21241
21417
  })));
21242
21418
  const deleteByThreadId = (input) => deleteProjectionCheckpointRows(input).pipe(mapError(toPersistenceSqlError("ProjectionCheckpointRepository.deleteByThreadId:query")));
@@ -21621,10 +21797,10 @@ const makeProjectionProjectRepository = gen(function* () {
21621
21797
  });
21622
21798
  const upsert = (row) => upsertProjectionProjectRow(row).pipe(mapError(toPersistenceSqlOrDecodeError$4("ProjectionProjectRepository.upsert:query", "ProjectionProjectRepository.upsert:encodeRequest")));
21623
21799
  const getById = (input) => getProjectionProjectRow(input).pipe(mapError(toPersistenceSqlOrDecodeError$4("ProjectionProjectRepository.getById:query", "ProjectionProjectRepository.getById:decodeRow")), flatMap((rowOption) => match(rowOption, {
21624
- onNone: () => succeed(none$3()),
21800
+ onNone: () => succeed(none()),
21625
21801
  onSome: (row) => succeed(some(row))
21626
21802
  })));
21627
- const listAll = () => listProjectionProjectRows().pipe(mapError(toPersistenceSqlOrDecodeError$4("ProjectionProjectRepository.listAll:query", "ProjectionProjectRepository.listAll:decodeRows")), map$3((rows) => rows));
21803
+ const listAll = () => listProjectionProjectRows().pipe(mapError(toPersistenceSqlOrDecodeError$4("ProjectionProjectRepository.listAll:query", "ProjectionProjectRepository.listAll:decodeRows")), map$2((rows) => rows));
21628
21804
  const deleteById = (input) => deleteProjectionProjectRow(input).pipe(mapError(toPersistenceSqlError("ProjectionProjectRepository.deleteById:query")));
21629
21805
  return {
21630
21806
  upsert,
@@ -21714,7 +21890,7 @@ const makeProjectionStateRepository = gen(function* () {
21714
21890
  const upsert = (row) => upsertProjectionStateRow(row).pipe(mapError(toPersistenceSqlError("ProjectionStateRepository.upsert:query")));
21715
21891
  const getByProjector = (input) => getProjectionStateRow(input).pipe(mapError(toPersistenceSqlError("ProjectionStateRepository.getByProjector:query")));
21716
21892
  const listAll = () => listProjectionStateRows(void 0).pipe(mapError(toPersistenceSqlError("ProjectionStateRepository.listAll:query")));
21717
- const minLastAppliedSequence = () => readMinLastAppliedSequence(void 0).pipe(mapError(toPersistenceSqlError("ProjectionStateRepository.minLastAppliedSequence:query")), map$3((row) => row.minLastAppliedSequence));
21893
+ const minLastAppliedSequence = () => readMinLastAppliedSequence(void 0).pipe(mapError(toPersistenceSqlError("ProjectionStateRepository.minLastAppliedSequence:query")), map$2((row) => row.minLastAppliedSequence));
21718
21894
  return {
21719
21895
  upsert,
21720
21896
  getByProjector,
@@ -21829,7 +22005,7 @@ const makeProjectionThreadActivityRepository = gen(function* () {
21829
22005
  `
21830
22006
  });
21831
22007
  const upsert = (row) => upsertProjectionThreadActivityRow(row).pipe(mapError(toPersistenceSqlOrDecodeError$3("ProjectionThreadActivityRepository.upsert:query", "ProjectionThreadActivityRepository.upsert:encodeRequest")));
21832
- const listByThreadId = (input) => listProjectionThreadActivityRows(input).pipe(mapError(toPersistenceSqlOrDecodeError$3("ProjectionThreadActivityRepository.listByThreadId:query", "ProjectionThreadActivityRepository.listByThreadId:decodeRows")), map$3((rows) => rows.map((row) => ({
22008
+ const listByThreadId = (input) => listProjectionThreadActivityRows(input).pipe(mapError(toPersistenceSqlOrDecodeError$3("ProjectionThreadActivityRepository.listByThreadId:query", "ProjectionThreadActivityRepository.listByThreadId:decodeRows")), map$2((rows) => rows.map((row) => ({
21833
22009
  activityId: row.activityId,
21834
22010
  threadId: row.threadId,
21835
22011
  turnId: row.turnId,
@@ -21960,7 +22136,7 @@ const makeProjectionThreadMessageRepository = gen(function* () {
21960
22136
  `
21961
22137
  });
21962
22138
  const upsert = (row) => upsertProjectionThreadMessageRow(row).pipe(mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")));
21963
- const listByThreadId = (input) => listProjectionThreadMessageRows(input).pipe(mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query")), map$3((rows) => rows.map((row) => ({
22139
+ const listByThreadId = (input) => listProjectionThreadMessageRows(input).pipe(mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query")), map$2((rows) => rows.map((row) => ({
21964
22140
  messageId: row.messageId,
21965
22141
  threadId: row.threadId,
21966
22142
  turnId: row.turnId,
@@ -22646,10 +22822,10 @@ const makeProjectionTurnRepository = gen(function* () {
22646
22822
  const replacePendingTurnStart = (row) => sql.withTransaction(clearPendingProjectionTurnsByThread({ threadId: row.threadId }).pipe(flatMap(() => insertPendingProjectionTurn(row)))).pipe(mapError(toPersistenceSqlOrDecodeError$1("ProjectionTurnRepository.replacePendingTurnStart:query", "ProjectionTurnRepository.replacePendingTurnStart:encodeRequest")));
22647
22823
  const getPendingTurnStartByThreadId = (input) => getPendingProjectionTurn(input).pipe(mapError(toPersistenceSqlError("ProjectionTurnRepository.getPendingTurnStartByThreadId:query")));
22648
22824
  const deletePendingTurnStartByThreadId = (input) => clearPendingProjectionTurnsByThread(input).pipe(mapError(toPersistenceSqlError("ProjectionTurnRepository.deletePendingTurnStartByThreadId:query")));
22649
- const listByThreadId = (input) => listProjectionTurnsByThread(input).pipe(mapError(toPersistenceSqlOrDecodeError$1("ProjectionTurnRepository.listByThreadId:query", "ProjectionTurnRepository.listByThreadId:decodeRows")), map$3((rows) => rows));
22650
- const listAll = () => listAllProjectionTurns(void 0).pipe(mapError(toPersistenceSqlOrDecodeError$1("ProjectionTurnRepository.listAll:query", "ProjectionTurnRepository.listAll:decodeRows")), map$3((rows) => rows));
22825
+ const listByThreadId = (input) => listProjectionTurnsByThread(input).pipe(mapError(toPersistenceSqlOrDecodeError$1("ProjectionTurnRepository.listByThreadId:query", "ProjectionTurnRepository.listByThreadId:decodeRows")), map$2((rows) => rows));
22826
+ const listAll = () => listAllProjectionTurns(void 0).pipe(mapError(toPersistenceSqlOrDecodeError$1("ProjectionTurnRepository.listAll:query", "ProjectionTurnRepository.listAll:decodeRows")), map$2((rows) => rows));
22651
22827
  const getByTurnId = (input) => getProjectionTurnByTurnId(input).pipe(mapError(toPersistenceSqlOrDecodeError$1("ProjectionTurnRepository.getByTurnId:query", "ProjectionTurnRepository.getByTurnId:decodeRow")), flatMap((rowOption) => match(rowOption, {
22652
- onNone: () => succeed(none$3()),
22828
+ onNone: () => succeed(none()),
22653
22829
  onSome: (row) => succeed(some(row))
22654
22830
  })));
22655
22831
  const clearCheckpointTurnConflict = (input) => clearCheckpointTurnConflictRow(input).pipe(mapError(toPersistenceSqlError("ProjectionTurnRepository.clearCheckpointTurnConflict:query")));
@@ -22783,8 +22959,8 @@ const makeProviderSessionRuntimeRepository = gen(function* () {
22783
22959
  });
22784
22960
  const upsert = (runtime) => upsertRuntimeRow(runtime).pipe(mapError(toPersistenceSqlOrDecodeError("ProviderSessionRuntimeRepository.upsert:query", "ProviderSessionRuntimeRepository.upsert:encodeRequest")));
22785
22961
  const getByThreadId = (input) => getRuntimeRowByThreadId(input).pipe(mapError(toPersistenceSqlOrDecodeError("ProviderSessionRuntimeRepository.getByThreadId:query", "ProviderSessionRuntimeRepository.getByThreadId:decodeRow")), flatMap((runtimeRowOption) => match(runtimeRowOption, {
22786
- onNone: () => succeed(none$3()),
22787
- onSome: (row) => decodeRuntime(row).pipe(mapError(toPersistenceDecodeError("ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime")), map$3((runtime) => some(runtime)))
22962
+ onNone: () => succeed(none()),
22963
+ onSome: (row) => decodeRuntime(row).pipe(mapError(toPersistenceDecodeError("ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime")), map$2((runtime) => some(runtime)))
22788
22964
  })));
22789
22965
  const list = () => listRuntimeRows(void 0).pipe(mapError(toPersistenceSqlOrDecodeError("ProviderSessionRuntimeRepository.list:query", "ProviderSessionRuntimeRepository.list:decodeRows")), flatMap((rows) => forEach(rows, (row) => decodeRuntime(row).pipe(mapError(toPersistenceDecodeError("ProviderSessionRuntimeRepository.list:rowToRuntime"))), { concurrency: "unbounded" })));
22790
22966
  const deleteByThreadId = (input) => deleteRuntimeByThreadId(input).pipe(mapError(toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query")));
@@ -22996,7 +23172,25 @@ const decideOrchestrationCommand = fn("decideOrchestrationCommand")(function* ({
22996
23172
  projectId: command.projectId
22997
23173
  });
22998
23174
  const occurredAt = nowIso$2();
22999
- return {
23175
+ const activeProjectThreads = readModel.threads.filter((thread) => thread.projectId === command.projectId && thread.deletedAt === null);
23176
+ if (activeProjectThreads.length > 0 && command.force !== true) return yield* fail$1(new OrchestrationCommandInvariantError({
23177
+ commandType: command.type,
23178
+ detail: `Project '${command.projectId}' has ${activeProjectThreads.length} thread(s).`
23179
+ }));
23180
+ const threadDeletedEvents = activeProjectThreads.map((thread) => ({
23181
+ ...withEventBase({
23182
+ aggregateKind: "thread",
23183
+ aggregateId: thread.id,
23184
+ occurredAt,
23185
+ commandId: command.commandId
23186
+ }),
23187
+ type: "thread.deleted",
23188
+ payload: {
23189
+ threadId: thread.id,
23190
+ deletedAt: occurredAt
23191
+ }
23192
+ }));
23193
+ const projectDeletedEvent = {
23000
23194
  ...withEventBase({
23001
23195
  aggregateKind: "project",
23002
23196
  aggregateId: command.projectId,
@@ -23009,6 +23203,7 @@ const decideOrchestrationCommand = fn("decideOrchestrationCommand")(function* ({
23009
23203
  deletedAt: occurredAt
23010
23204
  }
23011
23205
  };
23206
+ return [...threadDeletedEvents, projectDeletedEvent];
23012
23207
  }
23013
23208
  case "thread.create":
23014
23209
  yield* requireProject({
@@ -23643,7 +23838,7 @@ function projectEvent(model, event) {
23643
23838
  updatedAt: event.occurredAt
23644
23839
  };
23645
23840
  switch (event.type) {
23646
- case "project.created": return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => {
23841
+ case "project.created": return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => {
23647
23842
  const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);
23648
23843
  const nextProject = {
23649
23844
  id: payload.projectId,
@@ -23660,7 +23855,7 @@ function projectEvent(model, event) {
23660
23855
  projects: existing ? nextBase.projects.map((entry) => entry.id === payload.projectId ? nextProject : entry) : [...nextBase.projects, nextProject]
23661
23856
  };
23662
23857
  }));
23663
- case "project.meta-updated": return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23858
+ case "project.meta-updated": return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23664
23859
  ...nextBase,
23665
23860
  projects: nextBase.projects.map((project) => project.id === payload.projectId ? {
23666
23861
  ...project,
@@ -23671,7 +23866,7 @@ function projectEvent(model, event) {
23671
23866
  updatedAt: payload.updatedAt
23672
23867
  } : project)
23673
23868
  })));
23674
- case "project.deleted": return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23869
+ case "project.deleted": return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23675
23870
  ...nextBase,
23676
23871
  projects: nextBase.projects.map((project) => project.id === payload.projectId ? {
23677
23872
  ...project,
@@ -23708,28 +23903,28 @@ function projectEvent(model, event) {
23708
23903
  threads: existing ? nextBase.threads.map((entry) => entry.id === thread.id ? thread : entry) : [...nextBase.threads, thread]
23709
23904
  };
23710
23905
  });
23711
- case "thread.archived": return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23906
+ case "thread.archived": return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23712
23907
  ...nextBase,
23713
23908
  threads: updateThread(nextBase.threads, payload.threadId, {
23714
23909
  archivedAt: payload.archivedAt,
23715
23910
  updatedAt: payload.updatedAt
23716
23911
  })
23717
23912
  })));
23718
- case "thread.unarchived": return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23913
+ case "thread.unarchived": return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23719
23914
  ...nextBase,
23720
23915
  threads: updateThread(nextBase.threads, payload.threadId, {
23721
23916
  archivedAt: null,
23722
23917
  updatedAt: payload.updatedAt
23723
23918
  })
23724
23919
  })));
23725
- case "thread.deleted": return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23920
+ case "thread.deleted": return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23726
23921
  ...nextBase,
23727
23922
  threads: updateThread(nextBase.threads, payload.threadId, {
23728
23923
  deletedAt: payload.deletedAt,
23729
23924
  updatedAt: payload.deletedAt
23730
23925
  })
23731
23926
  })));
23732
- case "thread.meta-updated": return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23927
+ case "thread.meta-updated": return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23733
23928
  ...nextBase,
23734
23929
  threads: updateThread(nextBase.threads, payload.threadId, {
23735
23930
  ...payload.projectId !== void 0 ? { projectId: payload.projectId } : {},
@@ -23744,14 +23939,14 @@ function projectEvent(model, event) {
23744
23939
  updatedAt: payload.updatedAt
23745
23940
  })
23746
23941
  })));
23747
- case "thread.runtime-mode-set": return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23942
+ case "thread.runtime-mode-set": return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23748
23943
  ...nextBase,
23749
23944
  threads: updateThread(nextBase.threads, payload.threadId, {
23750
23945
  runtimeMode: payload.runtimeMode,
23751
23946
  updatedAt: payload.updatedAt
23752
23947
  })
23753
23948
  })));
23754
- case "thread.interaction-mode-set": return decodeForEvent(ThreadInteractionModeSetPayload, event.payload, event.type, "payload").pipe(map$3((payload) => ({
23949
+ case "thread.interaction-mode-set": return decodeForEvent(ThreadInteractionModeSetPayload, event.payload, event.type, "payload").pipe(map$2((payload) => ({
23755
23950
  ...nextBase,
23756
23951
  threads: updateThread(nextBase.threads, payload.threadId, {
23757
23952
  interactionMode: payload.interactionMode,
@@ -23856,7 +24051,7 @@ function projectEvent(model, event) {
23856
24051
  })
23857
24052
  };
23858
24053
  });
23859
- case "thread.reverted": return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => {
24054
+ case "thread.reverted": return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => {
23860
24055
  const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
23861
24056
  if (!thread) return nextBase;
23862
24057
  const checkpoints = thread.checkpoints.filter((entry) => entry.checkpointTurnCount <= payload.turnCount).toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount).slice(-MAX_THREAD_CHECKPOINTS);
@@ -23885,7 +24080,7 @@ function projectEvent(model, event) {
23885
24080
  })
23886
24081
  };
23887
24082
  }));
23888
- case "thread.activity-appended": return decodeForEvent(ThreadActivityAppendedPayload, event.payload, event.type, "payload").pipe(map$3((payload) => {
24083
+ case "thread.activity-appended": return decodeForEvent(ThreadActivityAppendedPayload, event.payload, event.type, "payload").pipe(map$2((payload) => {
23889
24084
  const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
23890
24085
  if (!thread) return nextBase;
23891
24086
  const activities = [...thread.activities.filter((entry) => entry.id !== payload.activity.id), payload.activity].toSorted(compareThreadActivities).slice(-500);
@@ -24212,7 +24407,7 @@ const makeOrchestrationEngine = gen(function* () {
24212
24407
  const processEnvelope = (envelope) => {
24213
24408
  const dispatchStartSequence = readModel.snapshotSequence;
24214
24409
  const reconcileReadModelAfterDispatchFailure = gen(function* () {
24215
- const persistedEvents = yield* runCollect(eventStore.readFromSequence(dispatchStartSequence)).pipe(map$3((chunk) => Array.from(chunk)));
24410
+ const persistedEvents = yield* runCollect(eventStore.readFromSequence(dispatchStartSequence)).pipe(map$2((chunk) => Array.from(chunk)));
24216
24411
  if (persistedEvents.length === 0) return;
24217
24412
  let nextReadModel = readModel;
24218
24413
  for (const persistedEvent of persistedEvents) nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
@@ -24223,7 +24418,7 @@ const makeOrchestrationEngine = gen(function* () {
24223
24418
  const existingReceipt = yield* commandReceiptRepository.getByCommandId({ commandId: envelope.command.commandId });
24224
24419
  if (isSome(existingReceipt)) {
24225
24420
  if (existingReceipt.value.status === "accepted") {
24226
- yield* succeed$4(envelope.result, { sequence: existingReceipt.value.resultSequence });
24421
+ yield* succeed$5(envelope.result, { sequence: existingReceipt.value.resultSequence });
24227
24422
  return;
24228
24423
  }
24229
24424
  yield* fail$4(envelope.result, new OrchestrationCommandPreviouslyRejectedError({
@@ -24268,7 +24463,7 @@ const makeOrchestrationEngine = gen(function* () {
24268
24463
  })).pipe(catchTag("SqlError", (sqlError) => fail$1(toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError))));
24269
24464
  readModel = committedCommand.nextReadModel;
24270
24465
  for (const event of committedCommand.committedEvents) yield* publish(eventPubSub, event);
24271
- yield* succeed$4(envelope.result, { sequence: committedCommand.lastSequence });
24466
+ yield* succeed$5(envelope.result, { sequence: committedCommand.lastSequence });
24272
24467
  }).pipe(catch_((error) => gen(function* () {
24273
24468
  yield* reconcileReadModelAfterDispatchFailure.pipe(catch_(() => logWarning$1("failed to reconcile orchestration read model after dispatch failure").pipe(annotateLogs({
24274
24469
  commandId: envelope.command.commandId,
@@ -24313,7 +24508,7 @@ const makeOrchestrationEngine = gen(function* () {
24313
24508
  const getReadModel = () => sync(() => readModel);
24314
24509
  const readEvents = (fromSequenceExclusive) => eventStore.readFromSequence(fromSequenceExclusive);
24315
24510
  const dispatch = (command) => gen(function* () {
24316
- const result = yield* make$26();
24511
+ const result = yield* make$27();
24317
24512
  yield* offer$1(commandQueue, {
24318
24513
  command,
24319
24514
  result
@@ -24353,8 +24548,8 @@ const OrchestrationEngineLive = effect(OrchestrationEngineService, makeOrchestra
24353
24548
  */
24354
24549
  const makeDrainableWorker = (process) => gen(function* () {
24355
24550
  const queue = yield* unbounded();
24356
- const initialIdle = yield* make$26();
24357
- yield* succeed$4(initialIdle, void 0).pipe(orDie);
24551
+ const initialIdle = yield* make$27();
24552
+ yield* succeed$5(initialIdle, void 0).pipe(orDie);
24358
24553
  const state = yield* make$11({
24359
24554
  outstanding: 0,
24360
24555
  idle: initialIdle
@@ -24366,10 +24561,10 @@ const makeDrainableWorker = (process) => gen(function* () {
24366
24561
  outstanding: remaining,
24367
24562
  idle: current.idle
24368
24563
  }];
24369
- }).pipe(flatMap((idle) => idle === null ? void_$1 : succeed$4(idle, void 0).pipe(orDie)));
24564
+ }).pipe(flatMap((idle) => idle === null ? void_$1 : succeed$5(idle, void 0).pipe(orDie)));
24370
24565
  yield* forkScoped(forever(take(queue).pipe(flatMap((item) => process(item).pipe(ensuring(finishOne))))));
24371
24566
  const enqueue = (item) => gen(function* () {
24372
- const nextIdle = yield* make$26();
24567
+ const nextIdle = yield* make$27();
24373
24568
  yield* update(state, (current) => current.outstanding === 0 ? {
24374
24569
  outstanding: 1,
24375
24570
  idle: nextIdle
@@ -24583,6 +24778,20 @@ const IGNORED_DIRECTORY_NAMES = new Set([
24583
24778
  "out",
24584
24779
  ".cache"
24585
24780
  ]);
24781
+ function expandHomePath(input) {
24782
+ if (input === "~") return os.homedir();
24783
+ if (input.startsWith("~/") || input.startsWith("~\\")) return path.join(os.homedir(), input.slice(2));
24784
+ return input;
24785
+ }
24786
+ function isWindowsAbsolutePath(input) {
24787
+ return /^[a-zA-Z]:[\\/]/.test(input) || /^\\\\[^\\]+\\[^\\]+/.test(input);
24788
+ }
24789
+ function resolveBrowseTarget(input) {
24790
+ if (process.platform !== "win32" && isWindowsAbsolutePath(input.partialPath)) throw new Error("Windows-style paths are only supported on Windows.");
24791
+ const expanded = expandHomePath(input.partialPath);
24792
+ if (path.isAbsolute(expanded) || input.partialPath.startsWith("~")) return path.resolve(expanded);
24793
+ return input.cwd ? path.resolve(expandHomePath(input.cwd), expanded) : path.resolve(expanded);
24794
+ }
24586
24795
  const workspaceIndexCache = /* @__PURE__ */ new Map();
24587
24796
  const inFlightWorkspaceIndexBuilds = /* @__PURE__ */ new Map();
24588
24797
  function toPosixPath(input) {
@@ -24901,6 +25110,22 @@ async function searchWorkspaceEntries(input) {
24901
25110
  truncated: index.truncated || matchedEntryCount > limit
24902
25111
  };
24903
25112
  }
25113
+ async function browseFilesystemEntries(input) {
25114
+ const resolvedInputPath = resolveBrowseTarget(input);
25115
+ const endsWithSeparator = /[\\/]$/.test(input.partialPath) || input.partialPath === "~";
25116
+ const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
25117
+ const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
25118
+ const dirents = await fs$1.readdir(parentPath, { withFileTypes: true });
25119
+ const showHidden = endsWithSeparator || prefix.startsWith(".");
25120
+ const lowerPrefix = prefix.toLowerCase();
25121
+ return {
25122
+ parentPath,
25123
+ entries: dirents.filter((dirent) => dirent.isDirectory() && dirent.name.toLowerCase().startsWith(lowerPrefix) && (showHidden || !dirent.name.startsWith("."))).map((dirent) => ({
25124
+ name: dirent.name,
25125
+ fullPath: path.join(parentPath, dirent.name)
25126
+ })).sort((left, right) => left.name.localeCompare(right.name))
25127
+ };
25128
+ }
24904
25129
  //#endregion
24905
25130
  //#region src/provider/Services/ProviderService.ts
24906
25131
  /**
@@ -25021,7 +25246,7 @@ const make$6 = gen(function* () {
25021
25246
  const thread = (yield* orchestrationEngine.getReadModel()).threads.find((entry) => entry.id === threadId);
25022
25247
  const sessions = yield* providerService.listSessions();
25023
25248
  const findSessionWithCwd = (session) => {
25024
- if (!session?.cwd) return none$3();
25249
+ if (!session?.cwd) return none();
25025
25250
  return some({
25026
25251
  threadId: session.threadId,
25027
25252
  cwd: session.cwd
@@ -25031,7 +25256,7 @@ const make$6 = gen(function* () {
25031
25256
  const fromProjected = findSessionWithCwd(sessions.find((session) => session.threadId === thread.id));
25032
25257
  if (isSome(fromProjected)) return fromProjected;
25033
25258
  }
25034
- return none$3();
25259
+ return none();
25035
25260
  });
25036
25261
  const isGitWorkspace = (cwd) => isGitRepository(cwd);
25037
25262
  const resolveCheckpointCwd = fnUntraced(function* (input) {
@@ -25073,7 +25298,7 @@ const make$6 = gen(function* () {
25073
25298
  fromCheckpointRef,
25074
25299
  toCheckpointRef: targetCheckpointRef,
25075
25300
  fallbackFromToHead: false
25076
- }).pipe(map$3((summary) => summary.map((file) => ({
25301
+ }).pipe(map$2((summary) => summary.map((file) => ({
25077
25302
  path: file.path,
25078
25303
  kind: "modified",
25079
25304
  additions: file.additions,
@@ -25458,15 +25683,49 @@ var ProviderCommandReactor = class extends Service()("t3/orchestration/Services/
25458
25683
  */
25459
25684
  var ProviderRuntimeIngestionService = class extends Service()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {};
25460
25685
  //#endregion
25686
+ //#region src/terminal/Services/Manager.ts
25687
+ var TerminalError = class extends TaggedErrorClass()("TerminalError", {
25688
+ message: String$1,
25689
+ cause: optional$2(Defect)
25690
+ }) {};
25691
+ /**
25692
+ * TerminalManager - Service tag for terminal session orchestration.
25693
+ */
25694
+ var TerminalManager = class extends Service()("t3/terminal/Services/Manager/TerminalManager") {};
25695
+ //#endregion
25461
25696
  //#region src/orchestration/Layers/OrchestrationReactor.ts
25462
25697
  const makeOrchestrationReactor = gen(function* () {
25698
+ const orchestrationEngine = yield* OrchestrationEngineService;
25463
25699
  const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
25464
25700
  const providerCommandReactor = yield* ProviderCommandReactor;
25465
25701
  const checkpointReactor = yield* CheckpointReactor;
25702
+ const providerService = yield* ProviderService;
25703
+ const terminalManager = yield* TerminalManager;
25704
+ const startThreadDeletionCleanup = forkScoped(runForEach(orchestrationEngine.streamDomainEvents, (event) => {
25705
+ if (event.type !== "thread.deleted") return void_$1;
25706
+ const threadId = event.payload.threadId;
25707
+ return all([providerService.stopSession({ threadId }).pipe(catchCause((cause) => {
25708
+ if (hasInterruptsOnly(cause)) return failCause(cause);
25709
+ return logWarning$1("failed to stop provider session for deleted thread", {
25710
+ threadId,
25711
+ cause: pretty(cause)
25712
+ });
25713
+ })), terminalManager.close({
25714
+ threadId,
25715
+ deleteHistory: true
25716
+ }).pipe(catchCause((cause) => {
25717
+ if (hasInterruptsOnly(cause)) return failCause(cause);
25718
+ return logWarning$1("failed to close terminals for deleted thread", {
25719
+ threadId,
25720
+ cause: pretty(cause)
25721
+ });
25722
+ }))], { concurrency: "unbounded" }).pipe(asVoid);
25723
+ })).pipe(asVoid);
25466
25724
  return { start: gen(function* () {
25467
25725
  yield* providerRuntimeIngestion.start;
25468
25726
  yield* providerCommandReactor.start;
25469
25727
  yield* checkpointReactor.start;
25728
+ yield* startThreadDeletionCleanup;
25470
25729
  }) };
25471
25730
  });
25472
25731
  const OrchestrationReactorLive = effect(OrchestrationReactor, makeOrchestrationReactor);
@@ -25669,12 +25928,12 @@ const make$5 = gen(function* () {
25669
25928
  const providerService = yield* ProviderService;
25670
25929
  const git = yield* GitCore;
25671
25930
  const textGeneration = yield* TextGeneration;
25672
- const handledTurnStartKeys = yield* make$32({
25931
+ const handledTurnStartKeys = yield* make$13({
25673
25932
  capacity: HANDLED_TURN_START_KEY_MAX,
25674
25933
  timeToLive: HANDLED_TURN_START_KEY_TTL,
25675
25934
  lookup: () => succeed(true)
25676
25935
  });
25677
- const hasHandledTurnStartRecently = (key) => getOption(handledTurnStartKeys, key).pipe(flatMap((cached) => set$3(handledTurnStartKeys, key, true).pipe(as(isSome(cached)))));
25936
+ const hasHandledTurnStartRecently = (key) => getOption(handledTurnStartKeys, key).pipe(flatMap((cached) => set$2(handledTurnStartKeys, key, true).pipe(as(isSome(cached)))));
25678
25937
  const threadProviderOptions = /* @__PURE__ */ new Map();
25679
25938
  const threadModelSelections = /* @__PURE__ */ new Map();
25680
25939
  const appendProviderFailureActivity = (input) => orchestrationEngine.dispatch({
@@ -25725,7 +25984,7 @@ const make$5 = gen(function* () {
25725
25984
  projects: readModel.projects
25726
25985
  });
25727
25986
  const importedThreadResumeCursor = thread.origin === "external-import" && hasImportedThreadLineage(thread) && preferredProvider === "codex" ? { threadId } : void 0;
25728
- const resolveActiveSession = (threadId) => providerService.listSessions().pipe(map$3((sessions) => sessions.find((session) => session.threadId === threadId)));
25987
+ const resolveActiveSession = (threadId) => providerService.listSessions().pipe(map$2((sessions) => sessions.find((session) => session.threadId === threadId)));
25729
25988
  const startProviderSession = (input) => providerService.startSession(threadId, {
25730
25989
  threadId,
25731
25990
  ...preferredProvider ? { provider: preferredProvider } : {},
@@ -25750,11 +26009,11 @@ const make$5 = gen(function* () {
25750
26009
  },
25751
26010
  createdAt
25752
26011
  });
25753
- const existingSessionThreadId = thread.session && thread.session.status !== "stopped" ? thread.id : null;
26012
+ const activeSession = yield* resolveActiveSession(threadId);
26013
+ const existingSessionThreadId = thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
25754
26014
  if (existingSessionThreadId) {
25755
26015
  const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
25756
26016
  const providerChanged = requestedModelSelection !== void 0 && requestedModelSelection.provider !== currentProvider;
25757
- const activeSession = yield* resolveActiveSession(existingSessionThreadId);
25758
26017
  const sessionModelSwitch = currentProvider === void 0 ? "in-session" : (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
25759
26018
  const modelChanged = requestedModelSelection !== void 0 && requestedModelSelection.model !== activeSession?.model;
25760
26019
  const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
@@ -25801,7 +26060,7 @@ const make$5 = gen(function* () {
25801
26060
  });
25802
26061
  const normalizedInput = toNonEmptyProviderInput(input.messageText);
25803
26062
  const normalizedAttachments = input.attachments ?? [];
25804
- const activeSession = yield* providerService.listSessions().pipe(map$3((sessions) => sessions.find((session) => session.threadId === input.threadId)));
26063
+ const activeSession = yield* providerService.listSessions().pipe(map$2((sessions) => sessions.find((session) => session.threadId === input.threadId)));
25805
26064
  const sessionModelSwitch = activeSession === void 0 ? "in-session" : (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
25806
26065
  const requestedModelSelection = input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
25807
26066
  const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model !== void 0 ? {
@@ -28301,6 +28560,7 @@ const makeOrchestrationProjectionPipeline = gen(function* () {
28301
28560
  return;
28302
28561
  }
28303
28562
  if (isSome(existingRow) && existingRow.value.status === "resolved") return;
28563
+ if (event.payload.activity.kind !== "approval.requested") return;
28304
28564
  yield* projectionPendingApprovalRepository.upsert({
28305
28565
  requestId,
28306
28566
  threadId: event.payload.threadId,
@@ -28392,43 +28652,6 @@ const makeOrchestrationProjectionPipeline = gen(function* () {
28392
28652
  });
28393
28653
  const OrchestrationProjectionPipelineLive = effect(OrchestrationProjectionPipeline, makeOrchestrationProjectionPipeline).pipe(provideMerge(layer$2), provideMerge(ProjectionProjectRepositoryLive), provideMerge(ProjectionThreadRepositoryLive), provideMerge(ProjectionThreadMessageRepositoryLive), provideMerge(ProjectionThreadProposedPlanRepositoryLive), provideMerge(ProjectionThreadActivityRepositoryLive), provideMerge(ProjectionThreadSessionRepositoryLive), provideMerge(ProjectionTurnRepositoryLive), provideMerge(ProjectionCheckpointRepositoryLive), provideMerge(ProjectionPendingApprovalRepositoryLive), provideMerge(ProjectionStateRepositoryLive));
28394
28654
  //#endregion
28395
- //#region ../../packages/contracts/src/settings/auto-roll.ts
28396
- const DEFAULT_AUTO_ROLL_ENABLED = false;
28397
- const DEFAULT_AUTO_ROLL_WARNING_THRESHOLD = 85;
28398
- const DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD = 95;
28399
- const AUTO_ROLL_WARNING_MIN = 50;
28400
- const AUTO_ROLL_WARNING_MAX = 99;
28401
- const AUTO_ROLL_SWITCH_MAX = 100;
28402
- function clampNumber(value, min, max) {
28403
- return Math.min(max, Math.max(min, value));
28404
- }
28405
- function resolveFiniteNumber(value, fallback) {
28406
- return Number.isFinite(value) ? value : fallback;
28407
- }
28408
- function sanitizeAutoRollWarningThreshold(value) {
28409
- return clampNumber(resolveFiniteNumber(value, 85), 50, AUTO_ROLL_WARNING_MAX);
28410
- }
28411
- function sanitizeAutoRollSwitchThreshold(value, warningThreshold) {
28412
- const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);
28413
- return clampNumber(resolveFiniteNumber(value, 95), sanitizedWarning + 1, AUTO_ROLL_SWITCH_MAX);
28414
- }
28415
- function sanitizeAutoRollThresholds(warningThreshold, switchThreshold) {
28416
- const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);
28417
- return {
28418
- warningThreshold: sanitizedWarning,
28419
- switchThreshold: sanitizeAutoRollSwitchThreshold(switchThreshold, sanitizedWarning)
28420
- };
28421
- }
28422
- function normalizeAutoRollSettings(raw) {
28423
- const enabled = typeof raw?.enabled === "boolean" ? raw.enabled : false;
28424
- const { warningThreshold: normalizedWarning, switchThreshold: normalizedSwitch } = sanitizeAutoRollThresholds(resolveFiniteNumber(typeof raw?.warningThreshold === "number" ? raw.warningThreshold : NaN, 85), resolveFiniteNumber(typeof raw?.switchThreshold === "number" ? raw.switchThreshold : NaN, 95));
28425
- return {
28426
- enabled,
28427
- warningThreshold: normalizedWarning,
28428
- switchThreshold: normalizedSwitch
28429
- };
28430
- }
28431
- //#endregion
28432
28655
  //#region ../../packages/contracts/src/settings/chat-scrollback.ts
28433
28656
  const CHAT_SCROLLBACK_DEFAULT = 200;
28434
28657
  const CHAT_SCROLLBACK_MIN = 50;
@@ -28992,6 +29215,81 @@ async function patchAppState(patch) {
28992
29215
  });
28993
29216
  }
28994
29217
  //#endregion
29218
+ //#region ../../packages/runtime-app-state/src/app/generalChatWorkspace.ts
29219
+ const GENERAL_CHAT_WORKSPACE_DIRNAME = "general-chat-workspace";
29220
+ const GENERAL_CHAT_PROJECT_TITLE = "General Chat";
29221
+ const GENERAL_CHAT_ANALYTICS_BUCKET = "General Chat";
29222
+ const GENERAL_CHAT_AGENTS_FILENAME = "AGENTS.md";
29223
+ const IS_CASE_INSENSITIVE_PLATFORM$1 = process.platform === "darwin" || process.platform === "win32";
29224
+ function stripTrailingSeparators$1(input) {
29225
+ const trimmed = input.trim();
29226
+ if (trimmed.length === 0) return trimmed;
29227
+ const root = path.parse(trimmed).root;
29228
+ let next = trimmed;
29229
+ while (next.length > root.length && /[\\/]+$/.test(next)) next = next.slice(0, -1);
29230
+ return next;
29231
+ }
29232
+ function canonicalizeWorkspaceRoot(input) {
29233
+ const resolved = path.resolve(input.trim());
29234
+ return stripTrailingSeparators$1((() => {
29235
+ try {
29236
+ return realpathSync.native(resolved);
29237
+ } catch {
29238
+ return resolved;
29239
+ }
29240
+ })());
29241
+ }
29242
+ function workspaceRootKey(input) {
29243
+ const canonical = canonicalizeWorkspaceRoot(input).replaceAll("\\", "/");
29244
+ return IS_CASE_INSENSITIVE_PLATFORM$1 ? canonical.toLowerCase() : canonical;
29245
+ }
29246
+ function resolveGeneralChatWorkspaceRoot() {
29247
+ return canonicalizeWorkspaceRoot(path.join(getUserDataDir(), GENERAL_CHAT_WORKSPACE_DIRNAME));
29248
+ }
29249
+ function resolveGeneralChatAgentsPath() {
29250
+ return path.join(resolveGeneralChatWorkspaceRoot(), GENERAL_CHAT_AGENTS_FILENAME);
29251
+ }
29252
+ function isGeneralChatWorkspaceRoot(workspaceRoot) {
29253
+ return workspaceRootKey(workspaceRoot) === workspaceRootKey(resolveGeneralChatWorkspaceRoot());
29254
+ }
29255
+ //#endregion
29256
+ //#region ../../packages/contracts/src/settings/auto-roll.ts
29257
+ const DEFAULT_AUTO_ROLL_ENABLED = false;
29258
+ const DEFAULT_AUTO_ROLL_WARNING_THRESHOLD = 85;
29259
+ const DEFAULT_AUTO_ROLL_SWITCH_THRESHOLD = 95;
29260
+ const AUTO_ROLL_WARNING_MIN = 50;
29261
+ const AUTO_ROLL_WARNING_MAX = 99;
29262
+ const AUTO_ROLL_SWITCH_MAX = 100;
29263
+ function clampNumber(value, min, max) {
29264
+ return Math.min(max, Math.max(min, value));
29265
+ }
29266
+ function resolveFiniteNumber(value, fallback) {
29267
+ return Number.isFinite(value) ? value : fallback;
29268
+ }
29269
+ function sanitizeAutoRollWarningThreshold(value) {
29270
+ return clampNumber(resolveFiniteNumber(value, 85), 50, AUTO_ROLL_WARNING_MAX);
29271
+ }
29272
+ function sanitizeAutoRollSwitchThreshold(value, warningThreshold) {
29273
+ const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);
29274
+ return clampNumber(resolveFiniteNumber(value, 95), sanitizedWarning + 1, AUTO_ROLL_SWITCH_MAX);
29275
+ }
29276
+ function sanitizeAutoRollThresholds(warningThreshold, switchThreshold) {
29277
+ const sanitizedWarning = sanitizeAutoRollWarningThreshold(warningThreshold);
29278
+ return {
29279
+ warningThreshold: sanitizedWarning,
29280
+ switchThreshold: sanitizeAutoRollSwitchThreshold(switchThreshold, sanitizedWarning)
29281
+ };
29282
+ }
29283
+ function normalizeAutoRollSettings(raw) {
29284
+ const enabled = typeof raw?.enabled === "boolean" ? raw.enabled : false;
29285
+ const { warningThreshold: normalizedWarning, switchThreshold: normalizedSwitch } = sanitizeAutoRollThresholds(resolveFiniteNumber(typeof raw?.warningThreshold === "number" ? raw.warningThreshold : NaN, 85), resolveFiniteNumber(typeof raw?.switchThreshold === "number" ? raw.switchThreshold : NaN, 95));
29286
+ return {
29287
+ enabled,
29288
+ warningThreshold: normalizedWarning,
29289
+ switchThreshold: normalizedSwitch
29290
+ };
29291
+ }
29292
+ //#endregion
28995
29293
  //#region ../../packages/runtime-codex/src/codex/settings.ts
28996
29294
  function asString$7(value) {
28997
29295
  if (typeof value !== "string") return null;
@@ -29526,7 +29824,7 @@ function findActiveProjectByCanonicalRoot(projects, workspaceRoot) {
29526
29824
  function countActiveUniqueProjects(projects) {
29527
29825
  const seen = /* @__PURE__ */ new Set();
29528
29826
  for (const project of projects) {
29529
- if (project.deletedAt !== null) continue;
29827
+ if (project.deletedAt !== null || isGeneralChatWorkspaceRoot(project.workspaceRoot)) continue;
29530
29828
  seen.add(projectRootKey(project.workspaceRoot));
29531
29829
  }
29532
29830
  return seen.size;
@@ -29663,6 +29961,24 @@ const ENV_HINTS = [
29663
29961
  "CODEX_PATH"
29664
29962
  ];
29665
29963
  let cachedStatus = null;
29964
+ function getPathHintEntries() {
29965
+ const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "";
29966
+ const homeEntries = homeDir ? [
29967
+ path.join(homeDir, ".local", "bin"),
29968
+ path.join(homeDir, ".fnm", "aliases", "default", "bin"),
29969
+ path.join(homeDir, ".fnm", "current", "bin"),
29970
+ path.join(homeDir, ".volta", "bin"),
29971
+ path.join(homeDir, ".asdf", "shims"),
29972
+ path.join(homeDir, ".bun", "bin")
29973
+ ] : [];
29974
+ const configuredHints = (process.env.CODEX_PATH_HINTS ?? "").split(path.delimiter).map((entry) => entry.trim()).filter(Boolean);
29975
+ return [
29976
+ "/opt/homebrew/bin",
29977
+ "/usr/local/bin",
29978
+ ...homeEntries,
29979
+ ...configuredHints
29980
+ ];
29981
+ }
29666
29982
  function fileExists$1(candidate) {
29667
29983
  if (!candidate) return null;
29668
29984
  const normalized = path.resolve(candidate);
@@ -29682,8 +29998,7 @@ function resolveCodexFromEnv() {
29682
29998
  }
29683
29999
  function resolveCodexFromPath() {
29684
30000
  const pathValue = process.env.PATH ?? "";
29685
- if (!pathValue) return null;
29686
- const entries = pathValue.split(path.delimiter).map((entry) => entry.trim()).filter(Boolean);
30001
+ const entries = Array.from(new Set([...getPathHintEntries(), ...pathValue.split(path.delimiter).map((entry) => entry.trim()).filter(Boolean)].filter(Boolean)));
29687
30002
  const names = process.platform === "win32" ? [
29688
30003
  "codex.exe",
29689
30004
  "codex.cmd",
@@ -32634,7 +32949,7 @@ const runExternalCodexThreadSync = gen(function* () {
32634
32949
  }
32635
32950
  const syncTargets = [];
32636
32951
  for (const project of readModel.projects) {
32637
- if (project.deletedAt !== null) continue;
32952
+ if (project.deletedAt !== null || isGeneralChatWorkspaceRoot(project.workspaceRoot)) continue;
32638
32953
  const workspaceRoot = project.workspaceRoot;
32639
32954
  const rootKey = projectRootKey(workspaceRoot);
32640
32955
  if (projectIdByRootKey.has(rootKey)) continue;
@@ -32862,7 +33177,7 @@ const makeThreadSnapshotPreparation = gen(function* () {
32862
33177
  importStateRepositories.messageRepository.listByThreadId({ threadId }),
32863
33178
  importStateRepositories.activityRepository.listByThreadId({ threadId }),
32864
33179
  importStateRepositories.proposedPlanRepository.listByThreadId({ threadId })
32865
- ], { concurrency: "inherit" }).pipe(map$3(([messages, activities, proposedPlans]) => {
33180
+ ], { concurrency: "inherit" }).pipe(map$2(([messages, activities, proposedPlans]) => {
32866
33181
  const importedIdPrefix = `${threadId}:`;
32867
33182
  return {
32868
33183
  hasArtifacts: messages.length > 0 || activities.length > 0 || proposedPlans.length > 0,
@@ -33289,17 +33604,17 @@ const make$4 = gen(function* () {
33289
33604
  const assistantDeliveryModeRef = yield* make$11(DEFAULT_ASSISTANT_DELIVERY_MODE);
33290
33605
  const passiveImportedThreadRecoveryLastStartedAtMs = /* @__PURE__ */ new Map();
33291
33606
  const passiveImportedThreadRecoveryInFlight = /* @__PURE__ */ new Map();
33292
- const turnMessageIdsByTurnKey = yield* make$32({
33607
+ const turnMessageIdsByTurnKey = yield* make$13({
33293
33608
  capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
33294
33609
  timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
33295
33610
  lookup: () => succeed(/* @__PURE__ */ new Set())
33296
33611
  });
33297
- const bufferedAssistantTextByMessageId = yield* make$32({
33612
+ const bufferedAssistantTextByMessageId = yield* make$13({
33298
33613
  capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
33299
33614
  timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
33300
33615
  lookup: () => succeed("")
33301
33616
  });
33302
- const bufferedProposedPlanById = yield* make$32({
33617
+ const bufferedProposedPlanById = yield* make$13({
33303
33618
  capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY,
33304
33619
  timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL,
33305
33620
  lookup: () => succeed({
@@ -33318,7 +33633,7 @@ const make$4 = gen(function* () {
33318
33633
  if (!workspaceCwd) return false;
33319
33634
  return isGitRepository(workspaceCwd);
33320
33635
  });
33321
- const rememberAssistantMessageId = (threadId, turnId, messageId) => getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(flatMap((existingIds) => set$3(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), match(existingIds, {
33636
+ const rememberAssistantMessageId = (threadId, turnId, messageId) => getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(flatMap((existingIds) => set$2(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), match(existingIds, {
33322
33637
  onNone: () => new Set([messageId]),
33323
33638
  onSome: (ids) => {
33324
33639
  const nextIds = new Set(ids);
@@ -33332,10 +33647,10 @@ const make$4 = gen(function* () {
33332
33647
  const nextIds = new Set(ids);
33333
33648
  nextIds.delete(messageId);
33334
33649
  if (nextIds.size === 0) return invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
33335
- return set$3(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds);
33650
+ return set$2(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds);
33336
33651
  }
33337
33652
  })));
33338
- const getAssistantMessageIdsForTurn = (threadId, turnId) => getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(map$3((existingIds) => getOrElse(existingIds, () => /* @__PURE__ */ new Set())));
33653
+ const getAssistantMessageIdsForTurn = (threadId, turnId) => getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(map$2((existingIds) => getOrElse(existingIds, () => /* @__PURE__ */ new Set())));
33339
33654
  const clearAssistantMessageIdsForTurn = (threadId, turnId) => invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
33340
33655
  const appendBufferedAssistantText = (messageId, delta) => getOption(bufferedAssistantTextByMessageId, messageId).pipe(flatMap((existingText) => gen(function* () {
33341
33656
  const nextText = match(existingText, {
@@ -33343,7 +33658,7 @@ const make$4 = gen(function* () {
33343
33658
  onSome: (text) => `${text}${delta}`
33344
33659
  });
33345
33660
  if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {
33346
- yield* set$3(bufferedAssistantTextByMessageId, messageId, nextText);
33661
+ yield* set$2(bufferedAssistantTextByMessageId, messageId, nextText);
33347
33662
  return "";
33348
33663
  }
33349
33664
  yield* invalidate(bufferedAssistantTextByMessageId, messageId);
@@ -33353,7 +33668,7 @@ const make$4 = gen(function* () {
33353
33668
  const clearBufferedAssistantText = (messageId) => invalidate(bufferedAssistantTextByMessageId, messageId);
33354
33669
  const appendBufferedProposedPlan = (planId, delta, createdAt) => getOption(bufferedProposedPlanById, planId).pipe(flatMap((existingEntry) => {
33355
33670
  const existing = getOrUndefined(existingEntry);
33356
- return set$3(bufferedProposedPlanById, planId, {
33671
+ return set$2(bufferedProposedPlanById, planId, {
33357
33672
  text: `${existing?.text ?? ""}${delta}`,
33358
33673
  createdAt: existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt
33359
33674
  });
@@ -35200,7 +35515,7 @@ function makeThreadWriter(input) {
35200
35515
  return;
35201
35516
  }
35202
35517
  const sink = sinkResult.sink;
35203
- const scope = yield* make$27();
35518
+ const scope = yield* make$28();
35204
35519
  const loggerLayer = layer$1([yield* batched(makeLineLogger(input.streamLabel), {
35205
35520
  window: input.batchWindowMs,
35206
35521
  flush: (messages) => gen(function* () {
@@ -36077,7 +36392,7 @@ const makeCodexAdapter = (options) => gen(function* () {
36077
36392
  detail: toMessage(cause, "Failed to start Codex adapter session."),
36078
36393
  cause
36079
36394
  })
36080
- }).pipe(map$3((session) => session));
36395
+ }).pipe(map$2((session) => session));
36081
36396
  };
36082
36397
  const sendTurn = (input) => gen(function* () {
36083
36398
  const codexAttachments = yield* forEach(input.attachments ?? [], (attachment) => gen(function* () {
@@ -36111,7 +36426,7 @@ const makeCodexAdapter = (options) => gen(function* () {
36111
36426
  return manager.sendTurn(managerInput);
36112
36427
  },
36113
36428
  catch: (cause) => toRequestError(input.threadId, "turn/start", cause)
36114
- }).pipe(map$3((result) => ({
36429
+ }).pipe(map$2((result) => ({
36115
36430
  ...result,
36116
36431
  threadId: input.threadId
36117
36432
  })));
@@ -36123,7 +36438,7 @@ const makeCodexAdapter = (options) => gen(function* () {
36123
36438
  const readThread = (threadId) => tryPromise({
36124
36439
  try: () => manager.readThread(threadId),
36125
36440
  catch: (cause) => toRequestError(threadId, "thread/read", cause)
36126
- }).pipe(map$3((snapshot) => ({
36441
+ }).pipe(map$2((snapshot) => ({
36127
36442
  threadId,
36128
36443
  turns: snapshot.turns
36129
36444
  })));
@@ -36136,7 +36451,7 @@ const makeCodexAdapter = (options) => gen(function* () {
36136
36451
  return tryPromise({
36137
36452
  try: () => manager.rollbackThread(threadId, numTurns),
36138
36453
  catch: (cause) => toRequestError(threadId, "thread/rollback", cause)
36139
- }).pipe(map$3((snapshot) => ({
36454
+ }).pipe(map$2((snapshot) => ({
36140
36455
  threadId,
36141
36456
  turns: snapshot.turns
36142
36457
  })));
@@ -36506,11 +36821,16 @@ const makeProviderService = (options) => gen(function* () {
36506
36821
  allowRecovery: false
36507
36822
  });
36508
36823
  if (routed.isActive) yield* routed.adapter.stopSession(routed.threadId);
36509
- yield* directory.remove(input.threadId);
36824
+ const existingBinding = yield* directory.getBinding(input.threadId);
36825
+ if (isSome(existingBinding)) yield* directory.upsert({
36826
+ ...existingBinding.value,
36827
+ status: "stopped",
36828
+ runtimePayload: { activeTurnId: null }
36829
+ });
36510
36830
  });
36511
36831
  const listSessions = () => gen(function* () {
36512
36832
  const activeSessions = (yield* forEach(adapters, (adapter) => adapter.listSessions())).flatMap((sessions) => sessions);
36513
- const persistedBindings = yield* directory.listThreadIds().pipe(flatMap((threadIds) => forEach(threadIds, (threadId) => directory.getBinding(threadId).pipe(orElseSucceed(() => none$3())), { concurrency: "unbounded" })), orElseSucceed(() => []));
36833
+ const persistedBindings = yield* directory.listThreadIds().pipe(flatMap((threadIds) => forEach(threadIds, (threadId) => directory.getBinding(threadId).pipe(orElseSucceed(() => none())), { concurrency: "unbounded" })), orElseSucceed(() => []));
36514
36834
  const bindingsByThreadId = /* @__PURE__ */ new Map();
36515
36835
  for (const bindingOption of persistedBindings) {
36516
36836
  const binding = getOrUndefined(bindingOption);
@@ -36525,7 +36845,7 @@ const makeProviderService = (options) => gen(function* () {
36525
36845
  return Object.assign({}, session, overrides);
36526
36846
  });
36527
36847
  });
36528
- const getCapabilities = (provider) => registry.getByProvider(provider).pipe(map$3((adapter) => adapter.capabilities));
36848
+ const getCapabilities = (provider) => registry.getByProvider(provider).pipe(map$2((adapter) => adapter.capabilities));
36529
36849
  const rollbackConversation = (rawInput) => gen(function* () {
36530
36850
  const input = yield* decodeInputOrValidationError({
36531
36851
  operation: "ProviderService.rollbackConversation",
@@ -36603,8 +36923,8 @@ function mergeRuntimePayload(existing, next) {
36603
36923
  const makeProviderSessionDirectory = gen(function* () {
36604
36924
  const repository = yield* ProviderSessionRuntimeRepository;
36605
36925
  const getBinding = (threadId) => repository.getByThreadId({ threadId }).pipe(mapError(toPersistenceError("ProviderSessionDirectory.getBinding:getByThreadId")), flatMap((runtime) => match(runtime, {
36606
- onNone: () => succeed(none$3()),
36607
- onSome: (value) => decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(map$3((provider) => some({
36926
+ onNone: () => succeed(none()),
36927
+ onSome: (value) => decodeProviderKind(value.providerName, "ProviderSessionDirectory.getBinding").pipe(map$2((provider) => some({
36608
36928
  threadId: value.threadId,
36609
36929
  provider,
36610
36930
  adapterKey: value.adapterKey,
@@ -36642,7 +36962,7 @@ const makeProviderSessionDirectory = gen(function* () {
36642
36962
  }))
36643
36963
  })));
36644
36964
  const remove = (threadId) => repository.deleteByThreadId({ threadId }).pipe(mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")));
36645
- const listThreadIds = () => repository.list().pipe(mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")), map$3((rows) => rows.map((row) => row.threadId)));
36965
+ const listThreadIds = () => repository.list().pipe(mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")), map$2((rows) => rows.map((row) => row.threadId)));
36646
36966
  return {
36647
36967
  upsert,
36648
36968
  getProvider,
@@ -36747,16 +37067,6 @@ var PtySpawnError = class extends TaggedErrorClass()("PtySpawnError", {
36747
37067
  */
36748
37068
  var PtyAdapter = class extends Service()("t3/terminal/Services/PTY/PtyAdapter") {};
36749
37069
  //#endregion
36750
- //#region src/terminal/Services/Manager.ts
36751
- var TerminalError = class extends TaggedErrorClass()("TerminalError", {
36752
- message: String$1,
36753
- cause: optional$2(Defect)
36754
- }) {};
36755
- /**
36756
- * TerminalManager - Service tag for terminal session orchestration.
36757
- */
36758
- var TerminalManager = class extends Service()("t3/terminal/Services/Manager/TerminalManager") {};
36759
- //#endregion
36760
37070
  //#region src/terminal/Layers/Manager.ts
36761
37071
  const DEFAULT_HISTORY_LINE_LIMIT = 5e3;
36762
37072
  const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
@@ -37712,6 +38022,10 @@ const DEFAULT_KEYBINDINGS = [
37712
38022
  command: "diff.toggle",
37713
38023
  when: "!terminalFocus"
37714
38024
  },
38025
+ {
38026
+ key: "mod+k",
38027
+ command: "commandPalette.toggle"
38028
+ },
37715
38029
  {
37716
38030
  key: "mod+n",
37717
38031
  command: "chat.new",
@@ -37946,7 +38260,7 @@ function compileResolvedKeybindingsConfig(config) {
37946
38260
  return compiled;
37947
38261
  }
37948
38262
  const ResolvedKeybindingFromConfig = KeybindingRule.pipe(decodeTo(toType(ResolvedKeybindingRule), transformOrFail({
37949
- decode: (rule) => succeed(compileResolvedKeybindingRule(rule)).pipe(filterOrFail(isNotNull, () => new InvalidValue$1(some(rule), { title: "Invalid keybinding rule" })), map$3((resolved) => resolved)),
38263
+ decode: (rule) => succeed(compileResolvedKeybindingRule(rule)).pipe(filterOrFail(isNotNull, () => new InvalidValue$1(some(rule), { title: "Invalid keybinding rule" })), map$2((resolved) => resolved)),
37950
38264
  encode: (resolved) => gen(function* () {
37951
38265
  const key = encodeShortcut(resolved.shortcut);
37952
38266
  if (!key) return yield* fail$1(new InvalidValue$1(some(resolved), { title: "Resolved shortcut cannot be encoded to key string" }));
@@ -38034,11 +38348,11 @@ const makeKeybindings = gen(function* () {
38034
38348
  const { keybindingsConfigPath, stateDir } = yield* ServerConfig$1;
38035
38349
  const fs = yield* FileSystem;
38036
38350
  const path = yield* Path$1;
38037
- const upsertSemaphore = yield* make$28(1);
38351
+ const upsertSemaphore = yield* make$29(1);
38038
38352
  const resolvedConfigCacheKey = "resolved";
38039
38353
  const changesPubSub = yield* unbounded$1();
38040
38354
  const startedRef = yield* make$11(false);
38041
- const startedDeferred = yield* make$26();
38355
+ const startedDeferred = yield* make$27();
38042
38356
  const keybindingsDbPath = path.join(stateDir, SQLITE_DB_FILE);
38043
38357
  const emitChange = (configState) => publish(changesPubSub, configState).pipe(asVoid);
38044
38358
  const readStoredRawConfig = tryPromise({
@@ -38074,7 +38388,7 @@ const makeKeybindings = gen(function* () {
38074
38388
  yield* fs.remove(keybindingsConfigPath).pipe(orElseSucceed(() => void 0));
38075
38389
  return rawConfig;
38076
38390
  });
38077
- const readRawConfig = importLegacyRawConfigOnce().pipe(map$3((rawConfig) => rawConfig ?? "[]"), mapError((cause) => new KeybindingsConfigError({
38391
+ const readRawConfig = importLegacyRawConfigOnce().pipe(map$2((rawConfig) => rawConfig ?? "[]"), mapError((cause) => new KeybindingsConfigError({
38078
38392
  configPath: keybindingsConfigPath,
38079
38393
  detail: "failed to read keybindings config",
38080
38394
  cause
@@ -38104,7 +38418,7 @@ const makeKeybindings = gen(function* () {
38104
38418
  return null;
38105
38419
  }
38106
38420
  return decodedRule.value;
38107
- })).pipe(map$3(filter(isNotNull)));
38421
+ })).pipe(map$2(filter(isNotNull)));
38108
38422
  });
38109
38423
  const loadRuntimeCustomKeybindingsConfig = fn(function* () {
38110
38424
  const rawConfig = yield* readRawConfig;
@@ -38148,21 +38462,21 @@ const makeKeybindings = gen(function* () {
38148
38462
  };
38149
38463
  });
38150
38464
  const writeConfigAtomically = (rules) => {
38151
- return encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(map$3((encoded) => `${encoded}\n`), flatMap((encoded) => writeStoredRawConfig(encoded)), mapError((cause) => new KeybindingsConfigError({
38465
+ return encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(map$2((encoded) => `${encoded}\n`), flatMap((encoded) => writeStoredRawConfig(encoded)), mapError((cause) => new KeybindingsConfigError({
38152
38466
  configPath: keybindingsConfigPath,
38153
38467
  detail: "failed to write keybindings config",
38154
38468
  cause
38155
38469
  })));
38156
38470
  };
38157
- const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(map$3(({ keybindings, issues }) => ({
38471
+ const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(map$2(({ keybindings, issues }) => ({
38158
38472
  keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
38159
38473
  issues
38160
38474
  })));
38161
- const resolvedConfigCache = yield* make$32({
38475
+ const resolvedConfigCache = yield* make$13({
38162
38476
  capacity: 1,
38163
38477
  lookup: () => loadConfigStateFromDisk
38164
38478
  });
38165
- const loadConfigStateFromCacheOrDisk = get$3(resolvedConfigCache, resolvedConfigCacheKey);
38479
+ const loadConfigStateFromCacheOrDisk = get$1(resolvedConfigCache, resolvedConfigCacheKey);
38166
38480
  upsertSemaphore.withPermits(1)(gen(function* () {
38167
38481
  yield* invalidate(resolvedConfigCache, resolvedConfigCacheKey);
38168
38482
  yield* emitChange(yield* loadConfigStateFromCacheOrDisk);
@@ -38223,7 +38537,7 @@ const makeKeybindings = gen(function* () {
38223
38537
  yield* failCause$1(startedDeferred, startupExit.cause).pipe(orDie);
38224
38538
  return yield* failCause(startupExit.cause);
38225
38539
  }
38226
- yield* succeed$4(startedDeferred, void 0).pipe(orDie);
38540
+ yield* succeed$5(startedDeferred, void 0).pipe(orDie);
38227
38541
  }),
38228
38542
  ready: _await(startedDeferred),
38229
38543
  syncDefaultKeybindingsOnStartup,
@@ -38241,7 +38555,7 @@ const makeKeybindings = gen(function* () {
38241
38555
  });
38242
38556
  yield* writeConfigAtomically(cappedConfig);
38243
38557
  const nextResolved = mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(cappedConfig));
38244
- yield* set$3(resolvedConfigCache, resolvedConfigCacheKey, {
38558
+ yield* set$2(resolvedConfigCache, resolvedConfigCacheKey, {
38245
38559
  keybindings: nextResolved,
38246
38560
  issues: []
38247
38561
  });
@@ -38672,7 +38986,7 @@ const makeGitManager = gen(function* () {
38672
38986
  "--json",
38673
38987
  "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt"
38674
38988
  ]
38675
- }).pipe(map$3((result) => result.stdout))).trim();
38989
+ }).pipe(map$2((result) => result.stdout))).trim();
38676
38990
  if (raw.length === 0) continue;
38677
38991
  const parsedJson = yield* try_({
38678
38992
  try: () => JSON.parse(raw),
@@ -38720,7 +39034,7 @@ const makeGitManager = gen(function* () {
38720
39034
  stagedPatch: limitContext(context.stagedPatch, 5e4),
38721
39035
  ...input.includeBranch ? { includeBranch: true } : {},
38722
39036
  ...input.model ? { model: input.model } : {}
38723
- }).pipe(map$3((result) => sanitizeCommitMessage(result)), catch_((error) => logWarning$1(`GitManager.resolveCommitAndBranchSuggestion: falling back to a generic commit message for ${input.cwd}: ${error instanceof Error ? error.message : String(error)}`).pipe(as(buildFallbackCommitAndBranchSuggestion({
39037
+ }).pipe(map$2((result) => sanitizeCommitMessage(result)), catch_((error) => logWarning$1(`GitManager.resolveCommitAndBranchSuggestion: falling back to a generic commit message for ${input.cwd}: ${error instanceof Error ? error.message : String(error)}`).pipe(as(buildFallbackCommitAndBranchSuggestion({
38724
39038
  stagedSummary: context.stagedSummary,
38725
39039
  includeBranch: input.includeBranch
38726
39040
  })))));
@@ -38827,7 +39141,7 @@ const makeGitManager = gen(function* () {
38827
39141
  const pr = details.branch !== null ? yield* findLatestPr(input.cwd, {
38828
39142
  branch: details.branch,
38829
39143
  upstreamRef: details.upstreamRef
38830
- }).pipe(map$3((latest) => latest ? toStatusPr(latest) : null), catch_(() => succeed(null))) : null;
39144
+ }).pipe(map$2((latest) => latest ? toStatusPr(latest) : null), catch_(() => succeed(null))) : null;
38831
39145
  return {
38832
39146
  branch: details.branch,
38833
39147
  hasWorkingTreeChanges: details.hasWorkingTreeChanges,
@@ -38842,7 +39156,7 @@ const makeGitManager = gen(function* () {
38842
39156
  return { pullRequest: yield* gitHubCli.getPullRequest({
38843
39157
  cwd: input.cwd,
38844
39158
  reference: normalizePullRequestReference(input.reference)
38845
- }).pipe(map$3((resolved) => toResolvedPullRequest(resolved))) };
39159
+ }).pipe(map$2((resolved) => toResolvedPullRequest(resolved))) };
38846
39160
  });
38847
39161
  const preparePullRequestThread = fnUntraced(function* (input) {
38848
39162
  const normalizedReference = normalizePullRequestReference(input.reference);
@@ -38881,7 +39195,7 @@ const makeGitManager = gen(function* () {
38881
39195
  ...toPullRequestHeadRemoteInfo(pullRequestSummary)
38882
39196
  };
38883
39197
  const localPullRequestBranch = resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
38884
- const findLocalHeadBranch = (cwd) => gitCore.listBranches({ cwd }).pipe(map$3((result) => {
39198
+ const findLocalHeadBranch = (cwd) => gitCore.listBranches({ cwd }).pipe(map$2((result) => {
38885
39199
  const localBranch = result.branches.find((branch) => !branch.isRemote && branch.name === localPullRequestBranch);
38886
39200
  if (localBranch) return localBranch;
38887
39201
  if (localPullRequestBranch === pullRequest.headBranch) return null;
@@ -39188,7 +39502,7 @@ const makeGitCore = gen(function* () {
39188
39502
  return fail$1(createGitCommandError(operation, cwd, args, `${commandLabel(args)} failed: code=${result.code ?? "null"}`));
39189
39503
  }));
39190
39504
  const runGit = (operation, cwd, args, allowNonZeroExit = false) => executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(asVoid);
39191
- const runGitStdout = (operation, cwd, args, allowNonZeroExit = false) => executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(map$3((result) => result.stdout));
39505
+ const runGitStdout = (operation, cwd, args, allowNonZeroExit = false) => executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(map$2((result) => result.stdout));
39192
39506
  const branchExists = (cwd, branch) => executeGit("GitCore.branchExists", cwd, [
39193
39507
  "show-ref",
39194
39508
  "--verify",
@@ -39197,7 +39511,7 @@ const makeGitCore = gen(function* () {
39197
39511
  ], {
39198
39512
  allowNonZeroExit: true,
39199
39513
  timeoutMs: 5e3
39200
- }).pipe(map$3((result) => result.code === 0));
39514
+ }).pipe(map$2((result) => result.code === 0));
39201
39515
  const resolveAvailableBranchName = (cwd, desiredBranch) => gen(function* () {
39202
39516
  if (!(yield* branchExists(cwd, desiredBranch))) return desiredBranch;
39203
39517
  for (let suffix = 1; suffix <= 100; suffix += 1) {
@@ -39217,7 +39531,7 @@ const makeGitCore = gen(function* () {
39217
39531
  "--abbrev-ref",
39218
39532
  "--symbolic-full-name",
39219
39533
  "@{upstream}"
39220
- ], true).pipe(map$3((stdout) => stdout.trim()));
39534
+ ], true).pipe(map$2((stdout) => stdout.trim()));
39221
39535
  if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") return null;
39222
39536
  const separatorIndex = upstreamRef.indexOf("/");
39223
39537
  if (separatorIndex <= 0) return null;
@@ -39268,7 +39582,7 @@ const makeGitCore = gen(function* () {
39268
39582
  const refreshStatusUpstreamIfStale = (cwd) => gen(function* () {
39269
39583
  const upstream = yield* resolveCurrentUpstream(cwd);
39270
39584
  if (!upstream) return;
39271
- yield* get$3(statusUpstreamRefreshCache, new StatusUpstreamRefreshCacheKey({
39585
+ yield* get$1(statusUpstreamRefreshCache, new StatusUpstreamRefreshCacheKey({
39272
39586
  cwd,
39273
39587
  upstreamRef: upstream.upstreamRef,
39274
39588
  remoteName: upstream.remoteName,
@@ -39280,7 +39594,7 @@ const makeGitCore = gen(function* () {
39280
39594
  if (!upstream) return;
39281
39595
  yield* fetchUpstreamRef(cwd, upstream);
39282
39596
  });
39283
- const resolveDefaultBranchName = (cwd, remoteName) => executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], { allowNonZeroExit: true }).pipe(map$3((result) => {
39597
+ const resolveDefaultBranchName = (cwd, remoteName) => executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], { allowNonZeroExit: true }).pipe(map$2((result) => {
39284
39598
  if (result.code !== 0) return null;
39285
39599
  return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName);
39286
39600
  }));
@@ -39289,13 +39603,13 @@ const makeGitCore = gen(function* () {
39289
39603
  "--verify",
39290
39604
  "--quiet",
39291
39605
  `refs/remotes/${remoteName}/${branch}`
39292
- ], { allowNonZeroExit: true }).pipe(map$3((result) => result.code === 0));
39606
+ ], { allowNonZeroExit: true }).pipe(map$2((result) => result.code === 0));
39293
39607
  const originRemoteExists = (cwd) => executeGit("GitCore.originRemoteExists", cwd, [
39294
39608
  "remote",
39295
39609
  "get-url",
39296
39610
  "origin"
39297
- ], { allowNonZeroExit: true }).pipe(map$3((result) => result.code === 0));
39298
- const listRemoteNames = (cwd) => runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(map$3((stdout) => parseRemoteNames(stdout).toReversed()));
39611
+ ], { allowNonZeroExit: true }).pipe(map$2((result) => result.code === 0));
39612
+ const listRemoteNames = (cwd) => runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(map$2((stdout) => parseRemoteNames(stdout).toReversed()));
39299
39613
  const resolvePrimaryRemoteName = (cwd) => gen(function* () {
39300
39614
  if (yield* originRemoteExists(cwd)) return "origin";
39301
39615
  const [firstRemote] = yield* listRemoteNames(cwd);
@@ -39307,20 +39621,20 @@ const makeGitCore = gen(function* () {
39307
39621
  "config",
39308
39622
  "--get",
39309
39623
  `branch.${branch}.pushRemote`
39310
- ], true).pipe(map$3((stdout) => stdout.trim()));
39624
+ ], true).pipe(map$2((stdout) => stdout.trim()));
39311
39625
  if (branchPushRemote.length > 0) return branchPushRemote;
39312
39626
  const pushDefaultRemote = yield* runGitStdout("GitCore.resolvePushRemoteName.remotePushDefault", cwd, [
39313
39627
  "config",
39314
39628
  "--get",
39315
39629
  "remote.pushDefault"
39316
- ], true).pipe(map$3((stdout) => stdout.trim()));
39630
+ ], true).pipe(map$2((stdout) => stdout.trim()));
39317
39631
  if (pushDefaultRemote.length > 0) return pushDefaultRemote;
39318
39632
  return yield* resolvePrimaryRemoteName(cwd).pipe(catch_(() => succeed(null)));
39319
39633
  });
39320
39634
  const ensureRemote = (input) => gen(function* () {
39321
39635
  const preferredName = sanitizeRemoteName(input.preferredName);
39322
39636
  const normalizedTargetUrl = normalizeRemoteUrl(input.url);
39323
- const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, ["remote", "-v"]).pipe(map$3((stdout) => parseRemoteFetchUrls(stdout)));
39637
+ const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, ["remote", "-v"]).pipe(map$2((stdout) => parseRemoteFetchUrls(stdout)));
39324
39638
  for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) return remoteName;
39325
39639
  let remoteName = preferredName;
39326
39640
  let suffix = 1;
@@ -39341,7 +39655,7 @@ const makeGitCore = gen(function* () {
39341
39655
  "config",
39342
39656
  "--get",
39343
39657
  `branch.${branch}.gh-merge-base`
39344
- ], true).pipe(map$3((stdout) => stdout.trim()));
39658
+ ], true).pipe(map$2((stdout) => stdout.trim()));
39345
39659
  const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(catch_(() => succeed(null)));
39346
39660
  const defaultBranch = primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName);
39347
39661
  const candidates = [
@@ -39486,7 +39800,7 @@ const makeGitCore = gen(function* () {
39486
39800
  behindCount
39487
39801
  };
39488
39802
  });
39489
- const status = (input) => statusDetails(input.cwd).pipe(map$3((details) => ({
39803
+ const status = (input) => statusDetails(input.cwd).pipe(map$2((details) => ({
39490
39804
  branch: details.branch,
39491
39805
  hasWorkingTreeChanges: details.hasWorkingTreeChanges,
39492
39806
  workingTree: details.workingTree,
@@ -39509,7 +39823,7 @@ const makeGitCore = gen(function* () {
39509
39823
  "diff",
39510
39824
  "--cached",
39511
39825
  "--name-status"
39512
- ]).pipe(map$3((stdout) => stdout.trim()));
39826
+ ]).pipe(map$2((stdout) => stdout.trim()));
39513
39827
  if (stagedSummary.length === 0) return null;
39514
39828
  const changedFileCount = stagedSummary.split(/\r?\n/g).filter((line) => line.trim().length > 0).length;
39515
39829
  if (changedFileCount > LARGE_COMMIT_PATCH_MAX_FILES) return {
@@ -39537,7 +39851,7 @@ const makeGitCore = gen(function* () {
39537
39851
  const trimmedBody = body.trim();
39538
39852
  if (trimmedBody.length > 0) args.push("-m", trimmedBody);
39539
39853
  yield* runGit("GitCore.commit.commit", cwd, args);
39540
- return { commitSha: yield* runGitStdout("GitCore.commit.revParseHead", cwd, ["rev-parse", "HEAD"]).pipe(map$3((stdout) => stdout.trim())) };
39854
+ return { commitSha: yield* runGitStdout("GitCore.commit.revParseHead", cwd, ["rev-parse", "HEAD"]).pipe(map$2((stdout) => stdout.trim())) };
39541
39855
  });
39542
39856
  const pushCurrentBranch = (cwd, fallbackBranch) => gen(function* () {
39543
39857
  const details = yield* statusDetails(cwd);
@@ -39604,12 +39918,12 @@ const makeGitCore = gen(function* () {
39604
39918
  const branch = details.branch;
39605
39919
  if (!branch) return yield* createGitCommandError("GitCore.pullCurrentBranch", cwd, ["pull", "--ff-only"], "Cannot pull from detached HEAD.");
39606
39920
  if (!details.hasUpstream) return yield* createGitCommandError("GitCore.pullCurrentBranch", cwd, ["pull", "--ff-only"], "Current branch has no upstream configured. Push with upstream first.");
39607
- const beforeSha = yield* runGitStdout("GitCore.pullCurrentBranch.beforeSha", cwd, ["rev-parse", "HEAD"], true).pipe(map$3((stdout) => stdout.trim()));
39921
+ const beforeSha = yield* runGitStdout("GitCore.pullCurrentBranch.beforeSha", cwd, ["rev-parse", "HEAD"], true).pipe(map$2((stdout) => stdout.trim()));
39608
39922
  yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
39609
39923
  timeoutMs: 3e4,
39610
39924
  fallbackErrorMessage: "git pull failed"
39611
39925
  });
39612
- const afterSha = yield* runGitStdout("GitCore.pullCurrentBranch.afterSha", cwd, ["rev-parse", "HEAD"], true).pipe(map$3((stdout) => stdout.trim()));
39926
+ const afterSha = yield* runGitStdout("GitCore.pullCurrentBranch.afterSha", cwd, ["rev-parse", "HEAD"], true).pipe(map$2((stdout) => stdout.trim()));
39613
39927
  const refreshed = yield* statusDetails(cwd);
39614
39928
  return {
39615
39929
  status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
@@ -39647,7 +39961,7 @@ const makeGitCore = gen(function* () {
39647
39961
  "config",
39648
39962
  "--get",
39649
39963
  key
39650
- ], true).pipe(map$3((stdout) => stdout.trim()), map$3((trimmed) => trimmed.length > 0 ? trimmed : null));
39964
+ ], true).pipe(map$2((stdout) => stdout.trim()), map$2((trimmed) => trimmed.length > 0 ? trimmed : null));
39651
39965
  const listBranches = (input) => gen(function* () {
39652
39966
  const branchRecencyPromise = readBranchRecency(input.cwd).pipe(catch_(() => succeed(/* @__PURE__ */ new Map())));
39653
39967
  const localBranchResult = yield* executeGit("GitCore.listBranches.branchNoColor", input.cwd, ["branch", "--no-color"], {
@@ -39709,7 +40023,7 @@ const makeGitCore = gen(function* () {
39709
40023
  let currentPath = null;
39710
40024
  for (const line of worktreeList.stdout.split("\n")) if (line.startsWith("worktree ")) {
39711
40025
  const candidatePath = line.slice(9);
39712
- currentPath = (yield* fileSystem.stat(candidatePath).pipe(map$3(() => true), catch_(() => succeed(false)))) ? candidatePath : null;
40026
+ currentPath = (yield* fileSystem.stat(candidatePath).pipe(map$2(() => true), catch_(() => succeed(false)))) ? candidatePath : null;
39713
40027
  } else if (line.startsWith("branch refs/heads/") && currentPath) worktreeMap.set(line.slice(18), currentPath);
39714
40028
  else if (line === "") currentPath = null;
39715
40029
  }
@@ -39850,7 +40164,7 @@ const makeGitCore = gen(function* () {
39850
40164
  ], {
39851
40165
  timeoutMs: 5e3,
39852
40166
  allowNonZeroExit: true
39853
- }).pipe(map$3((result) => result.code === 0)), executeGit("GitCore.checkoutBranch.remoteExists", input.cwd, [
40167
+ }).pipe(map$2((result) => result.code === 0)), executeGit("GitCore.checkoutBranch.remoteExists", input.cwd, [
39854
40168
  "show-ref",
39855
40169
  "--verify",
39856
40170
  "--quiet",
@@ -39858,7 +40172,7 @@ const makeGitCore = gen(function* () {
39858
40172
  ], {
39859
40173
  timeoutMs: 5e3,
39860
40174
  allowNonZeroExit: true
39861
- }).pipe(map$3((result) => result.code === 0))], { concurrency: "unbounded" });
40175
+ }).pipe(map$2((result) => result.code === 0))], { concurrency: "unbounded" });
39862
40176
  const localTrackingBranch = remoteExists ? yield* executeGit("GitCore.checkoutBranch.localTrackingBranch", input.cwd, [
39863
40177
  "for-each-ref",
39864
40178
  "--format=%(refname:short) %(upstream:short)",
@@ -39866,7 +40180,7 @@ const makeGitCore = gen(function* () {
39866
40180
  ], {
39867
40181
  timeoutMs: 5e3,
39868
40182
  allowNonZeroExit: true
39869
- }).pipe(map$3((result) => result.code === 0 ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) : null)) : null;
40183
+ }).pipe(map$2((result) => result.code === 0 ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) : null)) : null;
39870
40184
  const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
39871
40185
  const localTrackedBranchTargetExists = remoteExists && localTrackedBranchCandidate ? yield* executeGit("GitCore.checkoutBranch.localTrackedBranchTargetExists", input.cwd, [
39872
40186
  "show-ref",
@@ -39876,7 +40190,7 @@ const makeGitCore = gen(function* () {
39876
40190
  ], {
39877
40191
  timeoutMs: 5e3,
39878
40192
  allowNonZeroExit: true
39879
- }).pipe(map$3((result) => result.code === 0)) : false;
40193
+ }).pipe(map$2((result) => result.code === 0)) : false;
39880
40194
  const checkoutArgs = localInputExists ? ["checkout", input.branch] : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists ? ["checkout", input.branch] : remoteExists && !localTrackingBranch ? [
39881
40195
  "checkout",
39882
40196
  "--track",
@@ -39896,7 +40210,7 @@ const makeGitCore = gen(function* () {
39896
40210
  "branch",
39897
40211
  "--list",
39898
40212
  "--format=%(refname:short)"
39899
- ]).pipe(map$3((stdout) => stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0)));
40213
+ ]).pipe(map$2((stdout) => stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0)));
39900
40214
  return {
39901
40215
  status,
39902
40216
  statusDetails,
@@ -40031,7 +40345,7 @@ const makeGitHubCli = sync(() => {
40031
40345
  "--json",
40032
40346
  "number,title,url,baseRefName,headRefName"
40033
40347
  ]
40034
- }).pipe(map$3((result) => result.stdout.trim()), flatMap((raw) => raw.length === 0 ? succeed([]) : decodeGitHubJson(raw, Array$1(RawGitHubPullRequestSchema), "listOpenPullRequests", "GitHub CLI returned invalid PR list JSON.")), map$3((pullRequests) => pullRequests.map(normalizePullRequestSummary))),
40348
+ }).pipe(map$2((result) => result.stdout.trim()), flatMap((raw) => raw.length === 0 ? succeed([]) : decodeGitHubJson(raw, Array$1(RawGitHubPullRequestSchema), "listOpenPullRequests", "GitHub CLI returned invalid PR list JSON.")), map$2((pullRequests) => pullRequests.map(normalizePullRequestSummary))),
40035
40349
  getPullRequest: (input) => execute({
40036
40350
  cwd: input.cwd,
40037
40351
  args: [
@@ -40041,7 +40355,7 @@ const makeGitHubCli = sync(() => {
40041
40355
  "--json",
40042
40356
  "number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner"
40043
40357
  ]
40044
- }).pipe(map$3((result) => result.stdout.trim()), flatMap((raw) => decodeGitHubJson(raw, RawGitHubPullRequestSchema, "getPullRequest", "GitHub CLI returned invalid pull request JSON.")), map$3(normalizePullRequestSummary)),
40358
+ }).pipe(map$2((result) => result.stdout.trim()), flatMap((raw) => decodeGitHubJson(raw, RawGitHubPullRequestSchema, "getPullRequest", "GitHub CLI returned invalid pull request JSON.")), map$2(normalizePullRequestSummary)),
40045
40359
  getRepositoryCloneUrls: (input) => execute({
40046
40360
  cwd: input.cwd,
40047
40361
  args: [
@@ -40051,7 +40365,7 @@ const makeGitHubCli = sync(() => {
40051
40365
  "--json",
40052
40366
  "nameWithOwner,url,sshUrl"
40053
40367
  ]
40054
- }).pipe(map$3((result) => result.stdout.trim()), flatMap((raw) => decodeGitHubJson(raw, RawGitHubRepositoryCloneUrlsSchema, "getRepositoryCloneUrls", "GitHub CLI returned invalid repository JSON.")), map$3(normalizeRepositoryCloneUrls)),
40368
+ }).pipe(map$2((result) => result.stdout.trim()), flatMap((raw) => decodeGitHubJson(raw, RawGitHubRepositoryCloneUrlsSchema, "getRepositoryCloneUrls", "GitHub CLI returned invalid repository JSON.")), map$2(normalizeRepositoryCloneUrls)),
40055
40369
  createPullRequest: (input) => execute({
40056
40370
  cwd: input.cwd,
40057
40371
  args: [
@@ -40077,7 +40391,7 @@ const makeGitHubCli = sync(() => {
40077
40391
  "--jq",
40078
40392
  ".defaultBranchRef.name"
40079
40393
  ]
40080
- }).pipe(map$3((value) => {
40394
+ }).pipe(map$2((value) => {
40081
40395
  const trimmed = value.stdout.trim();
40082
40396
  return trimmed.length > 0 ? trimmed : null;
40083
40397
  })),
@@ -40207,13 +40521,13 @@ const makeCodexTextGeneration = gen(function* () {
40207
40521
  ], {
40208
40522
  cwd,
40209
40523
  shell: process.platform === "win32",
40210
- stdin: { stream: make$29(new TextEncoder().encode(prompt)) }
40524
+ stdin: { stream: make$30(new TextEncoder().encode(prompt)) }
40211
40525
  });
40212
40526
  const child = yield* commandSpawner.spawn(command).pipe(mapError((cause) => normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process")));
40213
40527
  const [stdout, stderr, exitCode] = yield* all([
40214
40528
  readStreamAsString(operation, child.stdout),
40215
40529
  readStreamAsString(operation, child.stderr),
40216
- child.exitCode.pipe(map$3((value) => Number(value)), mapError((cause) => normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code")))
40530
+ child.exitCode.pipe(map$2((value) => Number(value)), mapError((cause) => normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code")))
40217
40531
  ], { concurrency: "unbounded" });
40218
40532
  if (exitCode !== 0) {
40219
40533
  const stderrDetail = stderr.trim();
@@ -40282,7 +40596,7 @@ const makeCodexTextGeneration = gen(function* () {
40282
40596
  prompt,
40283
40597
  outputSchemaJson,
40284
40598
  ...input.model ? { model: input.model } : {}
40285
- }).pipe(map$3((generated) => ({
40599
+ }).pipe(map$2((generated) => ({
40286
40600
  subject: sanitizeCommitSubject(generated.subject),
40287
40601
  body: generated.body.trim(),
40288
40602
  ..."branch" in generated && typeof generated.branch === "string" ? { branch: sanitizeFeatureBranchName(generated.branch) } : {}
@@ -40319,7 +40633,7 @@ const makeCodexTextGeneration = gen(function* () {
40319
40633
  body: String$1
40320
40634
  }),
40321
40635
  ...input.model ? { model: input.model } : {}
40322
- }).pipe(map$3((generated) => ({
40636
+ }).pipe(map$2((generated) => ({
40323
40637
  title: sanitizePrTitle(generated.title),
40324
40638
  body: generated.body.trim()
40325
40639
  })));
@@ -40574,9 +40888,8 @@ function makeServerRuntimeServicesLayer() {
40574
40888
  const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(provideMerge(runtimeServicesLayer));
40575
40889
  const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(provideMerge(runtimeServicesLayer), provideMerge(gitCoreLayer), provideMerge(textGenerationLayer));
40576
40890
  const checkpointReactorLayer = CheckpointReactorLive.pipe(provideMerge(runtimeServicesLayer));
40577
- const orchestrationReactorLayer = OrchestrationReactorLive.pipe(provideMerge(runtimeIngestionLayer), provideMerge(providerCommandReactorLayer), provideMerge(checkpointReactorLayer));
40578
40891
  const terminalLayer = TerminalManagerLive.pipe(provide$1(typeof Bun !== "undefined" && process.platform !== "win32" ? BunPtyAdapterLive : NodePtyAdapterLive));
40579
- return mergeAll(orchestrationReactorLayer, gitCoreLayer, GitManagerLive.pipe(provideMerge(gitCoreLayer), provideMerge(GitHubCliLive), provideMerge(textGenerationLayer)), terminalLayer, KeybindingsLive).pipe(provideMerge(layer$2));
40892
+ return mergeAll(OrchestrationReactorLive.pipe(provideMerge(runtimeIngestionLayer), provideMerge(providerCommandReactorLayer), provideMerge(checkpointReactorLayer), provideMerge(terminalLayer)), gitCoreLayer, GitManagerLive.pipe(provideMerge(gitCoreLayer), provideMerge(GitHubCliLive), provideMerge(textGenerationLayer)), terminalLayer, KeybindingsLive).pipe(provideMerge(layer$2));
40580
40893
  }
40581
40894
  //#endregion
40582
40895
  //#region src/provider/Services/ProviderHealth.ts
@@ -40733,7 +41046,7 @@ const readCodexConfigModelProvider = gen(function* () {
40733
41046
  * required because authentication is handled through provider-specific
40734
41047
  * environment variables.
40735
41048
  */
40736
- const hasCustomModelProvider = map$3(readCodexConfigModelProvider, (provider) => provider !== void 0 && !OPENAI_AUTH_PROVIDERS.has(provider));
41049
+ const hasCustomModelProvider = map$2(readCodexConfigModelProvider, (provider) => provider !== void 0 && !OPENAI_AUTH_PROVIDERS.has(provider));
40737
41050
  const collectStreamAsString = (stream) => runFold(stream, () => "", (acc, chunk) => acc + new TextDecoder().decode(chunk));
40738
41051
  const runCodexCommand$1 = (args, env) => gen(function* () {
40739
41052
  const spawner = yield* ChildProcessSpawner;
@@ -40745,7 +41058,7 @@ const runCodexCommand$1 = (args, env) => gen(function* () {
40745
41058
  const [stdout, stderr, exitCode] = yield* all([
40746
41059
  collectStreamAsString(child.stdout),
40747
41060
  collectStreamAsString(child.stderr),
40748
- child.exitCode.pipe(map$3(Number))
41061
+ child.exitCode.pipe(map$2(Number))
40749
41062
  ], { concurrency: "unbounded" });
40750
41063
  return {
40751
41064
  stdout,
@@ -40847,7 +41160,7 @@ const ProviderHealthLive = effect(ProviderHealth, gen(function* () {
40847
41160
  const fileSystem = yield* FileSystem;
40848
41161
  const path = yield* Path$1;
40849
41162
  const childProcessSpawner = yield* ChildProcessSpawner;
40850
- const loadStatuses = checkCodexProviderStatus.pipe(map$3(of), provideService(FileSystem, fileSystem), provideService(Path$1, path), provideService(ChildProcessSpawner, childProcessSpawner));
41163
+ const loadStatuses = checkCodexProviderStatus.pipe(map$2(of), provideService(FileSystem, fileSystem), provideService(Path$1, path), provideService(ChildProcessSpawner, childProcessSpawner));
40851
41164
  const statusesRef = yield* make$11(yield* loadStatuses);
40852
41165
  return {
40853
41166
  getStatuses: get(statusesRef),
@@ -43690,7 +44003,8 @@ function resolveFallbackAccountKey(profileName) {
43690
44003
  }
43691
44004
  var ProfileManager = class {
43692
44005
  constructor() {
43693
- this.codexDir = join$1(process.env.HOME || process.env.USERPROFILE || "", ".codex");
44006
+ const homeDir = process.env.HOME || process.env.USERPROFILE || "";
44007
+ this.codexDir = join$1(homeDir, ".codex");
43694
44008
  this.profileHomesRoot = join$1(getUserDataDir(), "profile-homes");
43695
44009
  this.activeAuth = join$1(this.codexDir, "auth.json");
43696
44010
  this.activeAuthBackup = `${this.activeAuth}.swap`;
@@ -47884,7 +48198,7 @@ const makeServerPushBus = (input) => gen(function* () {
47884
48198
  const nextSequence = yield* make$11(0);
47885
48199
  const queue = yield* unbounded();
47886
48200
  const encodePush = encodeUnknownEffect(fromJsonString(WsPush));
47887
- const settleDelivery = (job, delivered) => job.delivered === null ? void_$1 : succeed$4(job.delivered, delivered).pipe(orDie);
48201
+ const settleDelivery = (job, delivered) => job.delivered === null ? void_$1 : succeed$5(job.delivered, delivered).pipe(orDie);
47888
48202
  const send = fnUntraced(function* (job) {
47889
48203
  const push = {
47890
48204
  type: "push",
@@ -47893,7 +48207,7 @@ const makeServerPushBus = (input) => gen(function* () {
47893
48207
  data: job.data
47894
48208
  };
47895
48209
  const recipients = job.target.kind === "all" ? yield* get(input.clients) : new Set([job.target.client]);
47896
- return yield* encodePush(push).pipe(map$3((message) => {
48210
+ return yield* encodePush(push).pipe(map$2((message) => {
47897
48211
  let recipientCount = 0;
47898
48212
  for (const client of recipients) {
47899
48213
  if (client.readyState !== client.OPEN) continue;
@@ -47914,7 +48228,7 @@ const makeServerPushBus = (input) => gen(function* () {
47914
48228
  return {
47915
48229
  publishAll: publish({ kind: "all" }),
47916
48230
  publishClient: (client, channel, data) => gen(function* () {
47917
- const delivered = yield* make$26();
48231
+ const delivered = yield* make$27();
47918
48232
  yield* offer$1(queue, {
47919
48233
  channel,
47920
48234
  data,
@@ -47931,12 +48245,12 @@ const makeServerPushBus = (input) => gen(function* () {
47931
48245
  //#endregion
47932
48246
  //#region src/wsServer/readiness.ts
47933
48247
  const makeServerReadiness = gen(function* () {
47934
- const httpListening = yield* make$26();
47935
- const pushBusReady = yield* make$26();
47936
- const keybindingsReady = yield* make$26();
47937
- const terminalSubscriptionsReady = yield* make$26();
47938
- const orchestrationSubscriptionsReady = yield* make$26();
47939
- const complete = (deferred) => succeed$4(deferred, void 0).pipe(orDie);
48248
+ const httpListening = yield* make$27();
48249
+ const pushBusReady = yield* make$27();
48250
+ const keybindingsReady = yield* make$27();
48251
+ const terminalSubscriptionsReady = yield* make$27();
48252
+ const orchestrationSubscriptionsReady = yield* make$27();
48253
+ const complete = (deferred) => succeed$5(deferred, void 0).pipe(orDie);
47940
48254
  return {
47941
48255
  awaitServerReady: all([
47942
48256
  _await(httpListening),
@@ -47982,7 +48296,7 @@ const handleOrchestrationRequest = fnUntraced(function* (body, context) {
47982
48296
  case ORCHESTRATION_WS_METHODS.replayEvents: return yield* runCollect(context.orchestrationEngine.readEvents(clamp(body.fromSequenceExclusive, {
47983
48297
  maximum: Number.MAX_SAFE_INTEGER,
47984
48298
  minimum: 0
47985
- }))).pipe(map$3((events) => Array.from(events)));
48299
+ }))).pipe(map$2((events) => Array.from(events)));
47986
48300
  default: return unhandledRequest;
47987
48301
  }
47988
48302
  });
@@ -47993,7 +48307,7 @@ const decodeJsonResult = (schema) => {
47993
48307
  return (input) => {
47994
48308
  const result = decode(input);
47995
48309
  if (isFailure(result)) return fail$3(result.cause);
47996
- return succeed$3(result.value);
48310
+ return succeed$4(result.value);
47997
48311
  };
47998
48312
  };
47999
48313
  const formatSchemaError = (cause) => {
@@ -49291,7 +49605,8 @@ function limitModelUsage(data, maxModels = MAX_MODELS) {
49291
49605
  function buildProjectBreakdown(metrics) {
49292
49606
  const projectMap = /* @__PURE__ */ new Map();
49293
49607
  for (const metric of metrics) {
49294
- const key = metric.projectPath?.trim() || "Unknown";
49608
+ const rawProjectPath = metric.projectPath?.trim() || null;
49609
+ const key = rawProjectPath && isGeneralChatWorkspaceRoot(rawProjectPath) ? GENERAL_CHAT_ANALYTICS_BUCKET : rawProjectPath || "Unknown";
49295
49610
  const entry = projectMap.get(key) ?? {
49296
49611
  sessions: 0,
49297
49612
  cost: 0,
@@ -50427,6 +50742,36 @@ async function inspectCodexRuntime(input) {
50427
50742
  };
50428
50743
  }
50429
50744
  //#endregion
50745
+ //#region src/generalChat.ts
50746
+ const GENERAL_CHAT_AGENTS_CONTENT = `# AGENTS.md — General Chat
50747
+
50748
+ You are the assistant for CodexUse's General Chat surface.
50749
+
50750
+ Default behavior:
50751
+ - Talk like a normal general-purpose assistant.
50752
+ - Prefer direct answers, discussion, brainstorming, explanations, and everyday help.
50753
+ - Treat this workspace as internal app scaffolding, not as a user project.
50754
+ - For this General Chat workspace, treat this local AGENTS.md as the primary instruction source for behavior and tone.
50755
+ - Ignore or de-prioritize global CODEX_HOME AGENTS.md guidance that is mainly about coding workflows, repository work, file inspection, shell commands, patches, tests, PRs, or other project-task behavior, unless the user explicitly asks to switch into that kind of work.
50756
+ - Do not let coding-oriented global instructions push the conversation into repo/tooling behavior when the user is just using General Chat as a normal assistant.
50757
+ - Do not inspect files, run shell commands, modify the workspace, or take project actions unless the user clearly asks for that kind of help.
50758
+ - If the user explicitly switches into coding or workspace work, proceed deliberately and explain that you are leaving the default general-chat mode.
50759
+ `;
50760
+ function getGeneralChatConfig() {
50761
+ return { workspaceRoot: resolveGeneralChatWorkspaceRoot() };
50762
+ }
50763
+ async function ensureGeneralChatWorkspaceArtifacts() {
50764
+ const workspaceRoot = resolveGeneralChatWorkspaceRoot();
50765
+ const agentsPath = resolveGeneralChatAgentsPath();
50766
+ await promises.mkdir(workspaceRoot, { recursive: true });
50767
+ try {
50768
+ await promises.access(agentsPath);
50769
+ } catch {
50770
+ await promises.writeFile(agentsPath, GENERAL_CHAT_AGENTS_CONTENT, "utf8");
50771
+ }
50772
+ return workspaceRoot;
50773
+ }
50774
+ //#endregion
50430
50775
  //#region src/telegram/bridge.ts
50431
50776
  var TelegramApiRequestError = class extends Error {
50432
50777
  constructor(message) {
@@ -52435,6 +52780,7 @@ const createServer = fn(function* () {
52435
52780
  clients,
52436
52781
  logOutgoingPush
52437
52782
  });
52783
+ const generalChatConfig = getGeneralChatConfig();
52438
52784
  yield* readiness.markPushBusReady;
52439
52785
  yield* keybindingsManager.start.pipe(mapError((cause) => new ServerLifecycleError({
52440
52786
  operation: "keybindingsRuntimeStart",
@@ -52442,7 +52788,7 @@ const createServer = fn(function* () {
52442
52788
  })));
52443
52789
  yield* readiness.markKeybindingsReady;
52444
52790
  const normalizeProjectWorkspaceRoot = fnUntraced(function* (workspaceRoot) {
52445
- const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
52791
+ const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath$1(workspaceRoot.trim()));
52446
52792
  const workspaceStat = yield* fileSystem.stat(normalizedWorkspaceRoot).pipe(catch_(() => succeed(null)));
52447
52793
  if (!workspaceStat) return yield* new RouteRequestError({ message: `Project directory does not exist: ${normalizedWorkspaceRoot}` });
52448
52794
  if (workspaceStat.type !== "Directory") return yield* new RouteRequestError({ message: `Project path is not a directory: ${normalizedWorkspaceRoot}` });
@@ -52812,7 +53158,7 @@ const createServer = fn(function* () {
52812
53158
  const checkpointDiffQuery = yield* CheckpointDiffQuery;
52813
53159
  const orchestrationReactor = yield* OrchestrationReactor;
52814
53160
  const { openInEditor } = yield* Open;
52815
- const subscriptionsScope = yield* make$27("sequential");
53161
+ const subscriptionsScope = yield* make$28("sequential");
52816
53162
  yield* addFinalizer$1(() => close(subscriptionsScope, void_$3));
52817
53163
  yield* runForEach(orchestrationEngine.streamDomainEvents, (event) => gen(function* () {
52818
53164
  yield* pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event);
@@ -52824,7 +53170,8 @@ const createServer = fn(function* () {
52824
53170
  reason: "projectPolicy",
52825
53171
  issues: [],
52826
53172
  providers: providerStatuses,
52827
- projectPolicy
53173
+ projectPolicy,
53174
+ generalChat: generalChatConfig
52828
53175
  });
52829
53176
  })).pipe(forkIn(subscriptionsScope));
52830
53177
  yield* runForEach(keybindingsManager.streamChanges, (event) => gen(function* () {
@@ -52835,7 +53182,8 @@ const createServer = fn(function* () {
52835
53182
  reason: "keybindings",
52836
53183
  issues: event.issues,
52837
53184
  providers: providerStatuses,
52838
- projectPolicy
53185
+ projectPolicy,
53186
+ generalChat: generalChatConfig
52839
53187
  });
52840
53188
  })).pipe(forkIn(subscriptionsScope));
52841
53189
  yield* provide$2(orchestrationReactor.start, subscriptionsScope);
@@ -53000,7 +53348,7 @@ const createServer = fn(function* () {
53000
53348
  watchedGitStatusCwdsByClient.delete(client);
53001
53349
  for (const cwd of watchedCwds) removeGitStatusWatcherSubscriber(client, cwd);
53002
53350
  };
53003
- yield* addFinalizer$1(sync(() => {
53351
+ yield* addFinalizer$1(() => sync(() => {
53004
53352
  for (const watcher of watchedGitStatusesByCwd.values()) clearInterval(watcher.intervalId);
53005
53353
  watchedGitStatusesByCwd.clear();
53006
53354
  }));
@@ -53015,9 +53363,14 @@ const createServer = fn(function* () {
53015
53363
  writeSettings: (settings) => writeAppSettings(settings),
53016
53364
  isProEnabled: async () => (await licenseService.getStatus()).isPro
53017
53365
  });
53018
- yield* promise(async () => {
53019
- await telegramBridge.applyRuntimeSettings(await readResolvedTelegramRuntimeSettings());
53020
- });
53366
+ let telegramRuntimeSettingsQueue = Promise.resolve();
53367
+ const queueTelegramRuntimeSettingsApply = (settings) => {
53368
+ const applyTask = telegramRuntimeSettingsQueue.catch(() => void 0).then(async () => {
53369
+ await telegramBridge.applyRuntimeSettings(settings);
53370
+ });
53371
+ telegramRuntimeSettingsQueue = applyTask.catch(() => void 0);
53372
+ return applyTask;
53373
+ };
53021
53374
  yield* addFinalizer$1(() => promise(() => telegramBridge.dispose()));
53022
53375
  const refreshTray = () => {
53023
53376
  sendDesktopParentMessage$1({ type: "t3-server:refresh-tray" });
@@ -53095,6 +53448,9 @@ const createServer = fn(function* () {
53095
53448
  });
53096
53449
  });
53097
53450
  yield* readiness.markHttpListening;
53451
+ readResolvedTelegramRuntimeSettings().then((settings) => queueTelegramRuntimeSettingsApply(settings)).catch((error) => {
53452
+ logger.warn("Failed to apply Telegram runtime settings during startup", { error: error instanceof Error ? error.message : String(error) });
53453
+ });
53098
53454
  yield* addFinalizer$1(() => all([
53099
53455
  closeAllClients,
53100
53456
  closeWebSocketServer.pipe(ignoreCause({ log: true })),
@@ -53123,6 +53479,13 @@ const createServer = fn(function* () {
53123
53479
  catch: (cause) => new RouteRequestError({ message: `Failed to search workspace entries: ${String(cause)}` })
53124
53480
  });
53125
53481
  }
53482
+ case WS_METHODS.filesystemBrowse: {
53483
+ const body = stripRequestTag(request.body);
53484
+ return yield* tryPromise({
53485
+ try: () => browseFilesystemEntries(body),
53486
+ catch: (cause) => new RouteRequestError({ message: `Failed to browse filesystem entries: ${cause instanceof Error ? cause.message : String(cause)}` })
53487
+ });
53488
+ }
53126
53489
  case WS_METHODS.projectsEnsure: {
53127
53490
  const body = stripRequestTag(request.body);
53128
53491
  const workspaceRoot = yield* normalizeProjectWorkspaceRoot(body.cwd);
@@ -53162,6 +53525,37 @@ const createServer = fn(function* () {
53162
53525
  created: true
53163
53526
  };
53164
53527
  }
53528
+ case WS_METHODS.generalChatEnsure: {
53529
+ const workspaceRoot = yield* tryPromise({
53530
+ try: () => ensureGeneralChatWorkspaceArtifacts(),
53531
+ catch: (cause) => new RouteRequestError({ message: `Failed to prepare General Chat workspace: ${String(cause)}` })
53532
+ });
53533
+ const existingProject = findActiveProjectByCanonicalRoot((yield* projectionReadModelQuery.getSnapshot()).projects, workspaceRoot);
53534
+ if (existingProject) return {
53535
+ projectId: existingProject.id,
53536
+ workspaceRoot: existingProject.workspaceRoot,
53537
+ created: false
53538
+ };
53539
+ const createdAt = (/* @__PURE__ */ new Date()).toISOString();
53540
+ const projectId = ProjectId.makeUnsafe(crypto.randomUUID());
53541
+ yield* orchestrationEngine.dispatch({
53542
+ type: "project.create",
53543
+ commandId: CommandId.makeUnsafe(crypto.randomUUID()),
53544
+ projectId,
53545
+ title: GENERAL_CHAT_PROJECT_TITLE,
53546
+ workspaceRoot,
53547
+ defaultModelSelection: {
53548
+ provider: "codex",
53549
+ model: DEFAULT_MODEL_BY_PROVIDER.codex
53550
+ },
53551
+ createdAt
53552
+ });
53553
+ return {
53554
+ projectId,
53555
+ workspaceRoot,
53556
+ created: true
53557
+ };
53558
+ }
53165
53559
  case WS_METHODS.projectsWriteFile: {
53166
53560
  const body = stripRequestTag(request.body);
53167
53561
  const target = yield* resolveWorkspaceWritePath({
@@ -53215,7 +53609,10 @@ const createServer = fn(function* () {
53215
53609
  }
53216
53610
  case WS_METHODS.gitCreateWorktree: {
53217
53611
  const body = stripRequestTag(request.body);
53218
- return yield* git.createWorktree(body);
53612
+ const result = yield* git.createWorktree(body);
53613
+ yield* promise(() => scheduleWatchedGitStatusRefresh(body.cwd));
53614
+ yield* promise(() => scheduleWatchedGitStatusRefresh(result.worktree.path));
53615
+ return result;
53219
53616
  }
53220
53617
  case WS_METHODS.gitRemoveWorktree: {
53221
53618
  const body = stripRequestTag(request.body);
@@ -53223,11 +53620,15 @@ const createServer = fn(function* () {
53223
53620
  }
53224
53621
  case WS_METHODS.gitCreateBranch: {
53225
53622
  const body = stripRequestTag(request.body);
53226
- return yield* git.createBranch(body);
53623
+ const result = yield* git.createBranch(body);
53624
+ yield* promise(() => scheduleWatchedGitStatusRefresh(body.cwd));
53625
+ return result;
53227
53626
  }
53228
53627
  case WS_METHODS.gitCheckout: {
53229
53628
  const body = stripRequestTag(request.body);
53230
- return yield* scoped(git.checkoutBranch(body));
53629
+ const result = yield* scoped(git.checkoutBranch(body));
53630
+ yield* promise(() => scheduleWatchedGitStatusRefresh(body.cwd));
53631
+ return result;
53231
53632
  }
53232
53633
  case WS_METHODS.gitInit: {
53233
53634
  const body = stripRequestTag(request.body);
@@ -53268,7 +53669,8 @@ const createServer = fn(function* () {
53268
53669
  issues: keybindingsConfig.issues,
53269
53670
  providers,
53270
53671
  availableEditors,
53271
- projectPolicy
53672
+ projectPolicy,
53673
+ generalChat: generalChatConfig
53272
53674
  };
53273
53675
  }
53274
53676
  case WS_METHODS.serverRefreshProviders: {
@@ -53300,7 +53702,7 @@ const createServer = fn(function* () {
53300
53702
  const body = stripRequestTag(request.body);
53301
53703
  return yield* promise(async () => {
53302
53704
  return await writeAppSettings(await sanitizeAccountPoolSettingsForLicense(body.settings), async (updatedSettings) => {
53303
- await telegramBridge.applyRuntimeSettings(resolveTelegramRuntimeSettings(updatedSettings));
53705
+ await queueTelegramRuntimeSettingsApply(resolveTelegramRuntimeSettings(updatedSettings));
53304
53706
  });
53305
53707
  });
53306
53708
  }
@@ -53798,18 +54200,18 @@ var CliConfig = class CliConfig extends Service()("t3/main/CliConfig") {
53798
54200
  }
53799
54201
  };
53800
54202
  const CliEnvConfig = all$1({
53801
- mode: string$3("T3CODE_MODE").pipe(option, map$6(match({
54203
+ mode: string$3("T3CODE_MODE").pipe(option, map$5(match({
53802
54204
  onNone: () => "web",
53803
54205
  onSome: (value) => value === "desktop" ? "desktop" : "web"
53804
54206
  }))),
53805
- port: port("T3CODE_PORT").pipe(option, map$6(getOrUndefined)),
53806
- host: string$3("T3CODE_HOST").pipe(option, map$6(getOrUndefined)),
53807
- stateDir: string$3("T3CODE_STATE_DIR").pipe(option, map$6(getOrUndefined)),
53808
- devUrl: url("VITE_DEV_SERVER_URL").pipe(option, map$6(getOrUndefined)),
53809
- noBrowser: boolean$3("T3CODE_NO_BROWSER").pipe(option, map$6(getOrUndefined)),
53810
- authToken: string$3("T3CODE_AUTH_TOKEN").pipe(option, map$6(getOrUndefined)),
53811
- autoBootstrapProjectFromCwd: boolean$3("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(option, map$6(getOrUndefined)),
53812
- logWebSocketEvents: boolean$3("T3CODE_LOG_WS_EVENTS").pipe(option, map$6(getOrUndefined))
54207
+ port: port("T3CODE_PORT").pipe(option, map$5(getOrUndefined)),
54208
+ host: string$3("T3CODE_HOST").pipe(option, map$5(getOrUndefined)),
54209
+ stateDir: string$3("T3CODE_STATE_DIR").pipe(option, map$5(getOrUndefined)),
54210
+ devUrl: url("VITE_DEV_SERVER_URL").pipe(option, map$5(getOrUndefined)),
54211
+ noBrowser: boolean$3("T3CODE_NO_BROWSER").pipe(option, map$5(getOrUndefined)),
54212
+ authToken: string$3("T3CODE_AUTH_TOKEN").pipe(option, map$5(getOrUndefined)),
54213
+ autoBootstrapProjectFromCwd: boolean$3("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(option, map$5(getOrUndefined)),
54214
+ logWebSocketEvents: boolean$3("T3CODE_LOG_WS_EVENTS").pipe(option, map$5(getOrUndefined))
53813
54215
  });
53814
54216
  const resolveBooleanFlag = (flag, envValue) => getOrElse(filter$1(flag, Boolean), () => envValue);
53815
54217
  const ServerConfigLive = (input) => effect(ServerConfig$1, gen(function* () {
@@ -53979,52 +54381,7 @@ var version = "0.0.10";
53979
54381
  * @since 4.0.0
53980
54382
  */
53981
54383
  const TypeId$8 = "~effect/http/Cookies";
53982
- /**
53983
- * @since 4.0.0
53984
- * @category refinements
53985
- */
53986
- const isCookies = (u) => hasProperty(u, TypeId$8);
53987
- /**
53988
- * @since 4.0.0
53989
- * @category Schemas
53990
- */
53991
- const CookiesSchema = /* @__PURE__ */ declare(isCookies, {
53992
- typeConstructor: { _tag: "effect/http/Cookies" },
53993
- generation: {
53994
- runtime: `Cookies.CookiesSchema`,
53995
- Type: `Cookies.Cookies`,
53996
- Encoded: `typeof Cookies.CookiesSchema["Encoded"]`,
53997
- importDeclaration: `import * as Cookies from "effect/unstable/http/Cookies"`
53998
- },
53999
- expected: "Cookies",
54000
- toCodecJson: () => link$1()(Array$1(String$1), transform$1({
54001
- decode: (input) => fromSetCookie(input),
54002
- encode: (cookies) => toSetCookieHeaders(cookies)
54003
- })),
54004
- toCodecIso: () => link$1()(Record(String$1, CookieSchema), transform$1({
54005
- decode: (input) => fromReadonlyRecord(input),
54006
- encode: (cookies) => cookies.cookies
54007
- }))
54008
- });
54009
54384
  const CookieTypeId = "~effect/http/Cookies/Cookie";
54010
- /**
54011
- * @since 4.0.0
54012
- * @category Guards
54013
- */
54014
- const isCookie = (u) => hasProperty(u, CookieTypeId);
54015
- /**
54016
- * @since 4.0.0
54017
- * @category Schemas
54018
- */
54019
- const CookieSchema = /* @__PURE__ */ declare(isCookie, {
54020
- typeConstructor: { _tag: "effect/http/Cookie" },
54021
- generation: {
54022
- runtime: `Cookies.CookieSchema`,
54023
- Type: `Cookies.Cookie`,
54024
- importDeclaration: `import * as Cookie from "effect/unstable/http/Cookies"`
54025
- },
54026
- expected: "Cookie"
54027
- });
54028
54385
  const CookieErrorTypeId = "~effect/http/Cookies/CookieError";
54029
54386
  /**
54030
54387
  * @since 4.0.0
@@ -54062,7 +54419,7 @@ const Proto$5 = {
54062
54419
  toJSON() {
54063
54420
  return {
54064
54421
  _id: "effect/Cookies",
54065
- cookies: map$7(this.cookies, (cookie) => cookie.toJSON())
54422
+ cookies: map$6(this.cookies, (cookie) => cookie.toJSON())
54066
54423
  };
54067
54424
  },
54068
54425
  pipe() {
@@ -54208,109 +54565,6 @@ const CookieProto = {
54208
54565
  };
54209
54566
  }
54210
54567
  };
54211
- /**
54212
- * Create a new cookie
54213
- *
54214
- * @since 4.0.0
54215
- * @category constructors
54216
- */
54217
- function makeCookie(name, value, options) {
54218
- if (!fieldContentRegExp.test(name)) return fail$3(CookiesError.fromReason("InvalidCookieName"));
54219
- const encodedValue = encodeURIComponent(value);
54220
- if (encodedValue && !fieldContentRegExp.test(encodedValue)) return fail$3(CookiesError.fromReason("InvalidCookieValue"));
54221
- if (options !== void 0) {
54222
- if (options.domain !== void 0 && !fieldContentRegExp.test(options.domain)) return fail$3(CookiesError.fromReason("InvalidCookieDomain"));
54223
- if (options.path !== void 0 && !fieldContentRegExp.test(options.path)) return fail$3(CookiesError.fromReason("InvalidCookiePath"));
54224
- if (options.maxAge !== void 0 && !isFinite$1(fromInputUnsafe(options.maxAge))) return fail$3(CookiesError.fromReason("CookieInfinityMaxAge"));
54225
- }
54226
- return succeed$3(Object.assign(Object.create(CookieProto), {
54227
- name,
54228
- value,
54229
- valueEncoded: encodedValue,
54230
- options
54231
- }));
54232
- }
54233
- /**
54234
- * Create a new cookie, throwing an error if invalid
54235
- *
54236
- * @since 4.0.0
54237
- * @category constructors
54238
- */
54239
- const makeCookieUnsafe = (name, value, options) => getOrThrow(makeCookie(name, value, options));
54240
- /**
54241
- * Serialize a cookie into a string
54242
- *
54243
- * Adapted from https://github.com/fastify/fastify-cookie under MIT License
54244
- *
54245
- * @since 4.0.0
54246
- * @category encoding
54247
- */
54248
- function serializeCookie(self) {
54249
- let str = self.name + "=" + self.valueEncoded;
54250
- if (self.options === void 0) return str;
54251
- const options = self.options;
54252
- if (options.maxAge !== void 0) {
54253
- const maxAge = toSeconds(fromInputUnsafe(options.maxAge));
54254
- str += "; Max-Age=" + Math.trunc(maxAge);
54255
- }
54256
- if (options.domain !== void 0) str += "; Domain=" + options.domain;
54257
- if (options.path !== void 0) str += "; Path=" + options.path;
54258
- if (options.priority !== void 0) switch (options.priority) {
54259
- case "low":
54260
- str += "; Priority=Low";
54261
- break;
54262
- case "medium":
54263
- str += "; Priority=Medium";
54264
- break;
54265
- case "high":
54266
- str += "; Priority=High";
54267
- break;
54268
- }
54269
- if (options.expires !== void 0) str += "; Expires=" + options.expires.toUTCString();
54270
- if (options.httpOnly) str += "; HttpOnly";
54271
- if (options.secure) str += "; Secure";
54272
- if (options.partitioned) str += "; Partitioned";
54273
- if (options.sameSite !== void 0) switch (options.sameSite) {
54274
- case "lax":
54275
- str += "; SameSite=Lax";
54276
- break;
54277
- case "strict":
54278
- str += "; SameSite=Strict";
54279
- break;
54280
- case "none":
54281
- str += "; SameSite=None";
54282
- break;
54283
- }
54284
- return str;
54285
- }
54286
- /**
54287
- * @since 4.0.0
54288
- * @category encoding
54289
- */
54290
- const toRecord$1 = (self) => {
54291
- const record = {};
54292
- const cookies = Object.values(self.cookies);
54293
- for (let index = 0; index < cookies.length; index++) {
54294
- const cookie = cookies[index];
54295
- record[cookie.name] = cookie.value;
54296
- }
54297
- return record;
54298
- };
54299
- /**
54300
- * @since 4.0.0
54301
- * @category Schemas
54302
- */
54303
- const schemaRecord$1 = /* @__PURE__ */ CookiesSchema.pipe(/* @__PURE__ */ decodeTo(/* @__PURE__ */ Record(String$1, String$1), /* @__PURE__ */ transform$1({
54304
- decode: toRecord$1,
54305
- encode: (self) => fromIterable(Object.entries(self).map(([name, value]) => makeCookieUnsafe(name, value)))
54306
- })));
54307
- /**
54308
- * Serialize a Cookies object into Headers object containing one or more Set-Cookie headers
54309
- *
54310
- * @since 4.0.0
54311
- * @category encoding
54312
- */
54313
- const toSetCookieHeaders = (self) => Object.values(self.cookies).map(serializeCookie);
54314
54568
  const tryDecodeURIComponent = (str) => {
54315
54569
  try {
54316
54570
  return decodeURIComponent(str);
@@ -54334,7 +54588,7 @@ const Proto$4 = /* @__PURE__ */ Object.create(null);
54334
54588
  Object.defineProperties(Proto$4, {
54335
54589
  [TypeId$7]: { value: TypeId$7 },
54336
54590
  [symbolRedactable]: { value(context) {
54337
- return redact(this, get$2(context, CurrentRedactedNames));
54591
+ return redact(this, get$4(context, CurrentRedactedNames));
54338
54592
  } },
54339
54593
  toJSON: { value() {
54340
54594
  return redact$1(this);
@@ -54424,8 +54678,8 @@ const redact = /* @__PURE__ */ dual(2, (self, key) => {
54424
54678
  const modify = (key) => {
54425
54679
  if (typeof key === "string") {
54426
54680
  const k = key.toLowerCase();
54427
- if (k in self) out[k] = make$30(self[k]);
54428
- } else for (const name in self) if (key.test(name)) out[name] = make$30(self[name]);
54681
+ if (k in self) out[k] = make$31(self[k]);
54682
+ } else for (const name in self) if (key.test(name)) out[name] = make$31(self[name]);
54429
54683
  };
54430
54684
  if (Array.isArray(key)) for (let i = 0; i < key.length; i++) modify(key[i]);
54431
54685
  else modify(key);
@@ -54686,7 +54940,7 @@ const fromInputNested = (input) => {
54686
54940
  * @since 4.0.0
54687
54941
  * @category Equivalence
54688
54942
  */
54689
- const Equivalence = /* @__PURE__ */ make$31((a, b) => arrayEquivalence(a.params, b.params));
54943
+ const Equivalence = /* @__PURE__ */ make$32((a, b) => arrayEquivalence(a.params, b.params));
54690
54944
  const arrayEquivalence = /* @__PURE__ */ makeEquivalence$1(/* @__PURE__ */ makeEquivalence$2([/* @__PURE__ */ strictEqual(), /* @__PURE__ */ strictEqual()]));
54691
54945
  /**
54692
54946
  * @since 4.0.0
@@ -54744,7 +54998,7 @@ const makeUrl = (url, params, hash) => {
54744
54998
  if (value !== void 0) urlInstance.searchParams.append(key, value);
54745
54999
  }
54746
55000
  if (hash !== void 0) urlInstance.hash = hash;
54747
- return succeed$3(urlInstance);
55001
+ return succeed$4(urlInstance);
54748
55002
  } catch (e) {
54749
55003
  return fail$3(new UrlParamsError({ cause: e }));
54750
55004
  }
@@ -55040,15 +55294,6 @@ const TypeId$1 = "~effect/http/HttpClientResponse";
55040
55294
  * @category constructors
55041
55295
  */
55042
55296
  const fromWeb = (request, source) => new WebHttpClientResponse(request, source);
55043
- /**
55044
- * @since 4.0.0
55045
- * @category filters
55046
- */
55047
- const filterStatusOk$1 = (self) => self.status >= 200 && self.status < 300 ? succeed(self) : fail$1(new HttpClientError({ reason: new StatusCodeError({
55048
- response: self,
55049
- request: self.request,
55050
- description: "non 2xx status code"
55051
- }) }));
55052
55297
  var WebHttpClientResponse = class extends Class$1 {
55053
55298
  [TypeId$2];
55054
55299
  [TypeId$1];
@@ -55187,13 +55432,6 @@ const HttpClient = /* @__PURE__ */ Service("effect/HttpClient");
55187
55432
  */
55188
55433
  const transformResponse = /* @__PURE__ */ dual(2, (self, f) => makeWith((request) => f(self.postprocess(request)), self.preprocess));
55189
55434
  /**
55190
- * Filters responses that return a 2xx status code.
55191
- *
55192
- * @since 4.0.0
55193
- * @category filters
55194
- */
55195
- const filterStatusOk = /* @__PURE__ */ transformResponse(/* @__PURE__ */ flatMap(filterStatusOk$1));
55196
- /**
55197
55435
  * @since 4.0.0
55198
55436
  * @category constructors
55199
55437
  */
@@ -55293,7 +55531,7 @@ const SpanNameGenerator = /* @__PURE__ */ Reference("effect/http/HttpClient/Span
55293
55531
  /**
55294
55532
  * @since 4.0.0
55295
55533
  */
55296
- const layerMergedServices = (effect$1) => effect(HttpClient)(servicesWith((services) => map$3(effect$1, (client) => transformResponse(client, updateServices((input) => merge$2(services, input))))));
55534
+ const layerMergedServices = (effect$1) => effect(HttpClient)(servicesWith$1((services) => map$2(effect$1, (client) => transformResponse(client, updateServices$1((input) => merge$2(services, input))))));
55297
55535
  const responseRegistry = /* @__PURE__ */ (() => {
55298
55536
  if ("FinalizationRegistry" in globalThis && globalThis.FinalizationRegistry) {
55299
55537
  const registry = /* @__PURE__ */ new FinalizationRegistry((controller) => {
@@ -55372,7 +55610,7 @@ var InterruptibleResponse = class {
55372
55610
  get stream() {
55373
55611
  return suspend$3(() => {
55374
55612
  responseRegistry.unregister(this.original);
55375
- return onExit(this.original.stream, (exit) => {
55613
+ return onExit$1(this.original.stream, (exit) => {
55376
55614
  if (hasInterrupts$1(exit)) this.controller.abort();
55377
55615
  return void_$1;
55378
55616
  });
@@ -55404,7 +55642,7 @@ const fetch$1 = /* @__PURE__ */ make((request, url, signal, fiber) => {
55404
55642
  const fetch = fiber.getRef(Fetch);
55405
55643
  const options = fiber.services.mapUnsafe.get(RequestInit.key) ?? {};
55406
55644
  const headers = options.headers ? merge(fromInput$1(options.headers), request.headers) : request.headers;
55407
- const send = (body) => map$3(tryPromise({
55645
+ const send = (body) => map$2(tryPromise({
55408
55646
  try: () => fetch(url, {
55409
55647
  ...options,
55410
55648
  method: request.method,
@@ -55436,6 +55674,6 @@ const layer = /* @__PURE__ */ layerMergedServices(/* @__PURE__ */ succeed(fetch$
55436
55674
  const RuntimeLayer = empty$6.pipe(provideMerge(CliConfig.layer), provideMerge(ServerLive), provideMerge(OpenLive), provideMerge(NetService.layer), provideMerge(layer$2), provideMerge(layer));
55437
55675
  run$1(t3Cli, { version }).pipe(provide(RuntimeLayer), runMain);
55438
55676
  //#endregion
55439
- export {};
55677
+ export { make$13 as n, get$1 as t };
55440
55678
 
55441
55679
  //# sourceMappingURL=index.mjs.map