{"version":3,"file":"bin.mjs","names":["Exit.isSuccess","Cause.hasInterruptsOnly","Cause.squash","Effect.isEffect","Effect.runFork","Effect.tapCause","Effect.void","Effect.logError","runMain","NodeRuntime.runMain","TypeId","Predicate.hasProperty","Schema.TaggedErrorClass","Schema.String","Runtime.errorExitCode","Runtime.errorReported","Proto","Config.TrueValues","Config.FalseValues","toCodecStringTree","Schema.toCodecStringTree","Schema.decodeUnknownEffect","Effect.mapError","boolean","Config.Boolean","integer","Schema.Int","string","Effect.succeed","choice","Effect.fail","annotate","TypeId","Ansi.annotate","Ansi.bold","Ansi.combine","Ansi.italicized","Ansi.red","Effect.succeed","Option.none","Effect.fail","integer","map","Redacted.make","run","Terminal.Terminal","Terminal.QuitError","Effect.scoped","Effect.suspend","Effect.flatMap","Effect.isEffect","Effect.orDie","Queue.take","Effect.map","Effect.raceFirst","Effect.ensuring","Ansi.cursorShow","Ansi.eraseLine","Ansi.cursorTo","Ansi.eraseLines","Arr.map","Arr.reduce","Ansi.cursorDown","Effect.fnUntraced","Ansi.cursorLeft","Ansi.cyanBright","Ansi.blackBright","Ansi.cursorHide","Ansi.green","Option.getOrElse","Option.isSome","Arr.match","Arr.isReadonlyArrayNonEmpty","Ansi.cursorSavePosition","Ansi.cursorRestorePosition","Ansi.underlined","Option.match","Effect.match","Option.some","Arr.empty","Arr.findFirstIndex","Arr.findFirst","Arr.findLast","Effect.sync","EffectNumber.round","Ansi.strikethrough","Ansi.white","Ansi.cursorMove","TypeId","Proto","Predicate.hasProperty","Option.none","string","Primitive.string","boolean","Primitive.boolean","integer","Primitive.integer","choiceWithValue","Primitive.choice","choice","withAlias","withDescription","Option.some","map","Effect.map","Effect.flatMap","optional","Effect.fnUntraced","Primitive.isBoolean","Effect.catchTags","Effect.succeed","withDefault","Effect.isEffect","Option.getOrElse","Option.match","Option.fromUndefinedOr","withMetavar","withSchema","Schema.decodeUnknownEffect","Effect.mapError","CliError.InvalidValue","CliError.MissingArgument","CliError.MissingOption","Predicate.isNotUndefined","Option.getOrUndefined","string","Param.string","Param.argumentKind","optional","Param.optional","withDescription","Param.withDescription","withSchema","Param.withSchema","effect.ConsoleRef","core.withFiber","effect.sync","Option.getOrElse","generateFunction","generate","generate","generate","Bash.generate","Zsh.generate","Fish.generate","Param.string","Param.flagKind","Param.boolean","Param.integer","Param.choiceWithValue","Param.choice","Param.withAlias","withDescription","Param.withDescription","Param.withMetavar","Param.optional","Param.withDefault","Param.map","Param.withSchema","Param.isParam","TypeId","Proto","Context.Service","Context.empty","Predicate.isNotUndefined","Effect.fail","CliError.ShowHelp","makeParser","Param.extractSingleParams","Param.getParamMetadata","Primitive.getTypeName","Arr.map","Primitive.getChoiceKeys","Option.match","Option.some","Effect.fnUntraced","CliError.UnexpectedArgument","CliError.DuplicateOption","Primitive.getChoiceKeys","Param.extractSingleParams","Option.getOrUndefined","Param.getParamMetadata","Param.extractSingleParams","Effect.gen","Context.Service","CliOutput.Formatter","HelpInternal.getHelpForCommandPath","Console.log","Version","Effect.void","Flag.optional","Option.map","Option.isNone","CommandDescriptor.fromCommand","Completions_.generate","Context.Reference","GlobalFlag.BuiltIns","Option.match","Effect.gen","Param.extractSingleParams","Param.isFlagParam","Option.none","Option.some","Primitive.isBoolean","CliError.InvalidValue","Primitive.getChoiceKeys","Primitive.getTypeName","Primitive.isTrueValue","Primitive.isFalseValue","CliError.UnrecognizedOption","CliError.UnknownSubcommand","run","Console.log","Prompt.run","Prompt.select","Param.getUnderlyingSingleOrThrow","Param.getParamMetadata","Prompt.confirm","Prompt.integer","Option.getOrElse","Option.isSome","Effect.map","Primitive.getChoiceKeys","Prompt.date","Prompt.float","Prompt.password","Redacted.value","Prompt.text","Option.getOrUndefined","Ansi.magenta","Ansi.annotate","Ansi.bold","Ansi.cyanBright","Ansi.blackBright","Ansi.white","Ansi.green","Ansi.red","Predicate.hasProperty","TypeId","make","Predicate.isNotUndefined","Effect.fnUntraced","Option.isNone","internal","CliError.ShowHelp","Effect.provideService","Param.extractSingleParams","CliError.UnrecognizedOption","Effect.gen","CliConfig.CliConfig","CliOutput.Formatter","error","Console.log","Console.error","run","Effect.flatMap","Lexer.lex","Parser.createFlagRegistry","Param.isFlagParam","Parser.consumeGlobalFlags","Parser.parseArgs","Parser.getCommandPath","GlobalFlag.Wizard","Wizard.renderIntroduction","Wizard.run","Wizard.renderCompletion","Prompt.run","Prompt.toggle","Effect.catchTag","Wizard.renderQuit","Effect.result","GlobalFlag.LogLevel","Option.none","Option.match","Context.empty","Context.make","References.MinimumLogLevel","Effect.provideContext","Effect.catchFilter","CliError.isCliError","Result.succeed","Result.fail","Effect.andThen","Effect.fail","Terminal.isQuitError","Effect.interrupt","Data.TaggedError","Predicate.isObject","Predicate.hasProperty","Predicate.isString","Context.Service","make","Effect.callback","Effect.succeed","Effect.sync","Effect.gen","Effect.zipWith","Effect.fail","layer","Layer.sync","Schema.decodeTo","Schema.String","SchemaTransformation.transformOrFail","Effect.succeed","Schema.isNonEmpty","Schema.isGreaterThanOrEqualTo","Schema.isBetween","Schema.decodeUnknownOption","Schema.Array","Schema.Unknown","SchemaTransformation.transform","Option.isSome","Schema.brand","brand","Schema.isMaxLength","Schema.isPattern","Schema.brand","Schema.is","isProviderDriverKind","Schema.Struct","Schema.withDecodingDefault","Effect.succeed","Schema.optionalKey","Schema.Boolean","Schema.Array","Schema.optional","Schema.Unknown","Schema.Record","Schema.Literals","Schema.Struct","Schema.NullOr","Schema.Number","Schema.Boolean","Schema.DateTimeUtc","Schema.Union","Schema.Literal","Schema.optionalKey","Schema.String","Schema.isMaxLength","Schema.Array","StreamSchemaTypeId","Empty","isStreamSchema","Schema.isSchema","Predicate.hasProperty","SchemaAST.isVoid","SchemaAST.toEncoded","Schema.Literals","Schema.Array","Schema.Struct","Schema.Literal","Schema.DateTimeUtc","Schema.optionalKey","HttpApiSchema.asFormUrlEncoded","Schema.Number","Schema.NullOr","Schema.Boolean","Schema.TaggedErrorClass","Schema.String","Schema.Union","Schema.Literals","Schema.Struct","Schema.withDecodingDefault","Effect.succeed","Schema.optionalKey","Schema.Boolean","Schema.Literal","parse","make","QS.parse","assert","make","internal.make","TypeId","make","FindMyWay.make","Effect.contextWith","Effect.void","HttpServerResponse.isHttpServerResponse","Effect.succeed","Effect.isEffect","Effect.flatMap","HttpServerRequest.HttpServerRequest","Effect.sync","Effect.withFiber","Context.getUnsafe","Effect.fail","HttpServerError.HttpServerError","HttpServerError.RouteNotFound","Option.isSome","Context.add","HttpServerRequest.ParsedSearchParams","Context.getOrUndefined","Tracer.ParentSpan","Effect.updateContext","Effect.interruptible","Arr.reverse","Context.Service","Layer.effectDiscard","add","layer","Option.some","Option.none","Option.match","Effect.gen","Layer.effectContext","Effect.map","Context.makeUnsafe","Layer.succeedContext","context","Effect.context","Layer.CurrentMemoMap","Context.get","Scope.Scope","Layer.buildWithMemoMap","Layer.provide","Layer.provideMerge","Arr.empty","Arr.fromIterable","HttpMiddleware.cors","HttpMiddleware.withLoggerDisabled","HttpMiddleware.logger","Layer.succeed","HttpServer.serve","Layer.unwrap","HttpServer.withLogAddress","TypeId","Arr.isArrayNonEmpty","HttpApiSchema.NoContent","Proto","makeProto","HttpRouter.prefixPath","Context.add","Context.merge","make","Schema.toCodecStringTree","Context.empty","Schema.isSchema","Schema.Struct","HttpApiSchema.asFormUrlEncoded","HttpApiSchema.getPayloadEncoding","MediaType.normalize","reservedStreamFailureEvent","Arr.ensure","HttpApiSchema.isStreamSchema","HttpApiSchema.getStatusStream","HttpApiSchema.getStatusSuccess","HttpApiSchema.isNoContent","HttpApiSchema.getResponseEncoding","HttpApiSchema.isStreamSse","AST.toEncoded","AST.isUnion","AST.isSuspend","AST.isObjects","AST.isLiteral","Schema.toCodecJson","get","TypeId","Proto","makeProto","Context.merge","Record.map","Context.add","make","Context.empty","HttpApiEndpoint.getSuccessSchemas","HttpApiSchema.getStatusSuccess","HttpApiEndpoint.getErrorSchemas","HttpApiSchema.getStatusError","HttpApiSchema.isStreamSchema","Context.Service","TypeId","Proto","makeProto","Record.map","Context.merge","Context.add","make","Context.empty","Schema.ErrorClass","ErrorReporter.ignore","HttpServerRespondable.symbol","Effect.succeed","Data.TaggedClass","Effect.mapError","TypeId","Service","Context.Service","Schema.Literals","Schema.Struct","Schema.optional","Schema.Boolean","Schema.Literal","Schema.Array","Schema.Union","Schema.Record","Schema.String","Schema.Unknown","Schema.decodeTo","SchemaTransformation.transformOrFail","Effect.succeed","Schema.Literals","Schema.Struct","Schema.optionalKey","Schema.optional","Schema.Unknown","Schema.decodeTo","SchemaTransformation.transformOrFail","Effect.succeed","RuntimeMode","DEFAULT_RUNTIME_MODE","Schema.Record","Schema.String","Schema.isMaxLength","Schema.isPattern","Schema.Literal","Schema.isLessThanOrEqualTo","Schema.Union","Schema.Boolean","Schema.NullOr","Schema.Array","Schema.withDecodingDefault","Schema.makeFilter","ProjectCreatedPayload","ProjectMetaUpdatedPayload","ProjectDeletedPayload","ThreadCreatedPayload","ThreadDeletedPayload","ThreadArchivedPayload","ThreadUnarchivedPayload","ThreadSettledPayload","ThreadUnsettledPayload","ThreadSnoozedPayload","ThreadUnsnoozedPayload","ThreadPinnedPayload","ThreadUnpinnedPayload","ThreadMetaUpdatedPayload","ThreadRuntimeModeSetPayload","ThreadInteractionModeSetPayload","ThreadRevertedPayload","ThreadSessionSetPayload","ThreadProposedPlanUpsertedPayload","ThreadTurnDiffCompletedPayload","ThreadActivityAppendedPayload","SchemaIssue.InvalidValue","Struct.assign","Schema.isMinLength","Schema.isBetween","Schema.TaggedErrorClass","Schema.Defect","TypeId","Proto","Context.empty","Context.add","Context.Service","Title","JsonSchema.toMultiDocumentOpenApi3_1","InternalToJsonSchemaDocument.toJsonSchemaMultiDocument","InternalToRepresentation.toRepresentations","Arr.map","Schema.toCodecJsonAST","Context.getOption","Option.isSome","Context.get","Context.getOrElse","SchemaAST.getAST","SchemaAST.Union","HttpApiSchema.isStreamSse","Schema.toCodecJson","Schema.Cause","Schema.Defect","reservedStreamFailureEvent","SchemaAST.getLastEncoding","SchemaAST.isObjects","SchemaAST.isOptional","HttpApiMiddleware.isSecurity","Equal.equals","hasBody","HttpMethod.hasBody","HttpApiEndpoint.getPayloadSchemas","HttpApiSchema.isNoContent","HttpApiSchema.getPayloadEncoding","HttpApiEndpoint.getErrorSchemas","HttpApiSchema.getStatusError","HttpApi.AdditionalSchemas","SchemaAST.resolveIdentifier","Arr.isArrayNonEmpty","JsonPatch.apply","HttpApiEndpoint.getSuccessSchemas","HttpApiSchema.getStatusSuccess","HttpApiSchema.isStreamSchema","HttpApiSchema.getResponseEncoding","HttpApiSchema.getStatusStream","SchemaAST.resolveDescription","SchemaAST.isDeclaration","Option.map","Option.getOrUndefined","Schema.Literal","Schema.Literals","Schema.Struct","Schema.Boolean","Schema.isGreaterThanOrEqualTo","Schema.optional","Schema.NullOr","Schema.Array","Schema.isLessThanOrEqualTo","Schema.String","Schema.Int","Schema.TaggedErrorClass","Schema.Number","Schema.Union","Context.Service","HttpApiSecurity.http","HttpApiSecurity.annotate","OpenApi.Description","HttpApiMiddleware.Service","HttpApiSchema.asFormUrlEncoded","Schema.isGreaterThan","HttpApiGroup.make","HttpApiEndpoint.get","OpenApi.Summary","HttpApiEndpoint.post","HttpApiEndpoint.delete","HttpApi.make","OpenApi.Title","OpenApi.Version","Schema.Struct","Schema.optionalKey","Schema.String","Schema.Literals","Schema.TaggedErrorClass","Schema.Literal","HttpServerRespondable.symbol","HttpServerResponse.schemaJson","Schema.Union","Schema.Unknown","Context.Service","HttpApiMiddleware.Service","Schema.Boolean","Schema.NullOr","Schema.optional","Schema.Number","HttpApiGroup.make","HttpApiEndpoint.get","HttpApiEndpoint.post","Schema.Array","HttpApi.make","Schema.Union","Schema.Struct","Schema.Literal","Schema.String","Schema.Literals","Schema.TaggedErrorClass","Schema.Struct","Schema.Literal","Schema.Boolean","Schema.optional","Schema.String","Schema.optionalKey","Schema.Literals","Schema.Struct","Schema.Boolean","Schema.optional","decode","Schema.decodeEffect","Schema.NonEmptyArray","Channel.fromTransform","Effect.succeed","Effect.flatMap","TypeId","make","context","Effect.context","RcMap.make","Effect.contextWith","Layer.buildWithMemoMap","Context.get","Scope.Scope","Effect.scoped","RcMap.get","Layer.effectContext","RcMap.invalidate","fromRecord","Context.Service","Layer.effect","Layer.provide","Layer.unwrap","Effect.map","Effect.flatMap","effect.CurrentLoggers","effect.consolePretty","effect.tracerLogger","layer","Layer.effect","effect.fnUntraced","isEffect","TypeId","Proto","makeUnsafe","Semaphore.makeUnsafe","Ref.makeUnsafe","make","Effect.sync","Effect.suspend","Effect.map","TypeId","make","Effect.sync","makeUnsafe","modify","Effect.flatMap","Effect.tx","update","get","set","TypeId","Effect.map","TxRef.make","Chunk.empty","TxRef.modify","TxRef.update","TxRef.get","TxRef.set","Chunk.append","size","Chunk.size","isEmpty","Chunk.isEmpty","Chunk.drop","TypeId","Effect.gen","TxChunk.empty","TxRef.make","Effect.tx","TxRef.get","TxChunk.append","TxChunk.drop","Effect.txRetry","Effect.failCause","TxChunk.get","head","Chunk.head","Option.isNone","TxRef.set","TxChunk.size","TxChunk.isEmpty","Effect.withFiber","Cause.interrupt","TxChunk.set","Chunk.empty","Chunk.toArray","Effect.ignore","Schema.isMaxLength","Schema.isBetween","Schema.makeFilter","Schema.Struct","Schema.isGreaterThan","Schema.Literals","Schema.Union","Schema.TaggedStruct","Schema.Int","Schema.String","Schema.Boolean","Schema.optional","Schema.Array","Schema.Literal","Schema.isLessThan","Schema.NullOr","Schema.TaggedErrorClass","Schema.Number","Schema.Defect","Schema.isTrimmed","Schema.isNonEmpty","Schema.isMaxLength","Schema.optional","Schema.isGreaterThan","Schema.isLessThanOrEqualTo","Schema.Literals","Schema.Struct","Schema.Boolean","Schema.NullOr","Schema.String","Schema.makeFilter","Schema.Union","Schema.Literal","Schema.isLessThan","Schema.Array","Schema.Number","Schema.Unknown","Schema.Int","Schema.TaggedErrorClass","Schema.isGreaterThanOrEqualTo","Schema.Defect","Schema.Struct","Schema.String","Schema.optionalKey","Schema.Boolean","Schema.Array","Schema.suspend","Schema.Literals","Schema.NullOr","Schema.Number","Schema.Literal","Schema.Union","Schema.isTrimmed","Schema.isNonEmpty","Schema.Int","Schema.isGreaterThan","Schema.Uint8Array","TrimmedNonEmptyStringSchema","Schema.isGreaterThanOrEqualTo","Schema.isLessThanOrEqualTo","Schema.isMaxLength","Schema.isPattern","Schema.Record","Schema.isMaxProperties","Schema.Struct","Schema.optional","Schema.NullOr","Schema.Boolean","Schema.isNonEmpty","Schema.Literals","Schema.isGreaterThan","Schema.String","Schema.Int","Schema.Literal","Schema.Array","Schema.Union","Schema.TaggedErrorClass","Schema.Defect","Schema.Number","Schema.Literals","Schema.Struct","Schema.optional","RuntimeMode","Schema.Unknown","Schema.isMaxLength","Schema.Array","Schema.String","TrimmedNonEmptyStringSchema","Schema.Record","Schema.String","Schema.Unknown","Schema.Union","Schema.Literal","Schema.TemplateLiteral","Schema.Struct","Schema.optional","Schema.Literals","Schema.Boolean","Schema.NullOr","Schema.Number","Schema.Array","Schema.Int","Schema.withConstructorDefault","Effect.succeed","Schema.TemplateLiteral","Schema.Literal","Schema.isMaxLength","Schema.isPattern","Schema.Union","Schema.Literals","Schema.isMinLength","Schema.Struct","Schema.optional","Schema.Array","Schema.Boolean","Schema.suspend","Schema.NonEmptyString","Schema.TaggedErrorClass","Schema.String","Schema.Defect","Schema.Literals","Schema.Struct","Schema.TaggedErrorClass","Schema.String","Schema.Array","Schema.Defect","Schema.Union","Schema.is","Schema.Literals","Schema.isBetween","Schema.isMaxLength","Schema.Struct","Schema.withDecodingDefault","Effect.succeed","Schema.Array","Schema.Record","Schema.String","Schema.NullOr","Schema.decodeSync","Schema.decodeTo","SchemaTransformation.transformOrFail","Schema.annotate","Schema.annotateKey","Duration.seconds","Duration.minutes","Schema.optionalKey","Schema.DurationFromMillis","Schema.Boolean","Schema.Literal","Duration.toMillis","Schema.TaggedErrorClass","Schema.optional","Schema.Defect","Schema.Struct","Schema.Literal","Schema.Number","Schema.Union","Schema.Literals","Schema.optional","Schema.Boolean","Schema.NullOr","Schema.isGreaterThanOrEqualTo","Schema.isLessThanOrEqualTo","Schema.withDecodingDefault","Effect.succeed","Schema.isMaxLength","Schema.Array","Schema.optionalKey","Schema.DateTimeUtc","Schema.Option","Schema.Record","Schema.Int","ServerConfig","Schema.TaggedErrorClass","Schema.Defect","Schema.Literals","Schema.Struct","Schema.DateTimeUtc","Schema.Option","Schema.Boolean","Schema.NullOr","Schema.Array","Schema.TaggedErrorClass","Schema.String","Schema.optional","Schema.Defect","Schema.Number","Schema.Union","Schema.Literals","Schema.Struct","Schema.String","Schema.Option","Schema.DateTimeUtc","Schema.optional","Schema.Boolean","Schema.NullOr","Schema.Array","Schema.TaggedErrorClass","Schema.Defect","Schema.Literals","Schema.Struct","Schema.Union","Schema.Literal","Schema.String","Schema.optional","Schema.Boolean","Schema.NullOr","Schema.isMaxLength","Schema.Array","Schema.isMinLength","Schema.isLessThanOrEqualTo","Schema.TaggedStruct","Schema.TaggedErrorClass","Schema.Number","Schema.Defect","Schema.Int","Schema.isNonEmpty","Schema.isMaxLength","Schema.decodeTo","SchemaTransformation.trim","Schema.Struct","Schema.optionalKey","Schema.Array","Schema.Literals","Schema.Struct","Schema.isMaxLength","Schema.isLessThanOrEqualTo","Schema.optional","Schema.Array","Schema.Boolean","Schema.isNonEmpty","Schema.String","Schema.TaggedErrorClass","Schema.Defect","Schema.Struct","Schema.isMaxLength","Schema.optional","Schema.Array","Schema.Literals","Schema.TaggedErrorClass","Schema.Defect","Schema.Union","Schema.TaggedStruct","Schema.isMaxLength","Schema.Struct","Schema.Number","Schema.TaggedErrorClass","Schema.Defect","Schema.Struct","Schema.optional","Schema.optionalKey","Schema.Boolean","Schema.Literals","Schema.NullOr","Schema.String","Schema.DateTimeUtc","Schema.Array","Schema.Union","Schema.brand","Schema.Struct","Schema.Array","Schema.Literals","Schema.Struct","Schema.optionalKey","Schema.Boolean","Schema.String","Schema.Number","Schema.Literal","Schema.Array","Schema.Union","Schema.DateTimeUtcFromString","Schema.OptionFromNullOr","Schema.DateTimeUtc","Schema.Option","Predicate.hasProperty","Option.some","Option.none","Stream_.isStream","Schema.make","Context.Service","Cause.StackTrace","TypeId","Context.empty","Context.add","makeProto","Schema.isSchema","Schema.Struct","Context.merge","make","Schema.Void","Schema.Never","Schema.Defect","Schema.Class","PrimaryKey.symbol","RpcSchema.Stream","RpcSchema.getStreamSchemas","Option.isSome","Schema.Exit","Schema.Union","Context.makeUnsafe","Effect.gen","Effect.context","Effect.isEffect","Layer.effectContext","Effect.contextWith","Effect.succeed","Rpc.isWrapper","Effect.provide","Stream.provideContext","Context.add","Context.make","Context.merge","make","Context.empty","Schema.Struct","Schema.isMinLength","Schema.isMaxLength","Schema.Literal","Schema.optional","Schema.String","Schema.Boolean","Schema.TaggedErrorClass","Rpc.make","Schema.Union","ServerConfig","RpcGroup.make","Schema.TaggedErrorClass","Schema.Array","Schema.String","Schema.Literals","Context.Service","layerTest","make","layer","Layer.succeed","Effect.fn","Path.Path","FileSystem.FileSystem","Effect.all","makeTest","Layer.effect","Effect.orElseSucceed","Encoding.encodeBase64Url","Result.getOrThrow","Encoding.decodeBase64UrlString","Context.Service","make","Effect.gen","ServerConfig.ServerConfig","Effect.succeed","Effect.withSpan","layer","Layer.effect","Schema.encodeEffect","Schema.decodeUnknownEffect","Schema.mutable","Schema.Array","Effect.flatMap","Effect.asVoid","Arr.isReadonlyArrayNonEmpty","Effect.fail","Cause.NoSuchElementError","Effect.asSome","Effect.succeedNone","Schema.Union","Schema.Struct","Schema.String","Schema.TaggedErrorClass","Schema.optional","Schema.Defect","Schema.is","Schema.Struct","Schema.String","Schema.Literals","Schema.fromJsonString","Schema.NullOr","Schema.DateTimeUtcFromString","Schema.Unknown","Schema.decodeUnknownEffect","Context.Service","toPersistenceSqlOrDecodeError","Schema.isSchemaError","make","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Effect.mapError","Effect.flatMap","Option.match","Effect.succeed","Option.none","Effect.map","Option.some","Effect.forEach","layer","Layer.effect","Schema.TaggedErrorClass","Schema.Union","Schema.is","Schema.Defect","Schema.String","Schema.optional","Schema.Literals","Context.Service","Duration.minutes","Duration.hours","make","Effect.gen","Crypto.Crypto","ServerConfig.ServerConfig","AuthPairingLinks.AuthPairingLinkRepository","Ref.make","PubSub.unbounded","Effect.mapError","Ref.update","PubSub.publish","Effect.asVoid","DateTime.now","DateTime.add","Duration.toMillis","Effect.fn","Ref.modify","DateTime.isGreaterThanOrEqualTo","Option.isSome","Option.isNone","Stream.fromPubSub","layer","Layer.effect","Layer.provideMerge","AuthPairingLinks.layer","Schema.String","Schema.Defect","Schema.TaggedErrorClass","Schema.Union","Schema.is","Predicate.isTagged","Context.Service","make","Effect.gen","Crypto.Crypto","FileSystem.FileSystem","Path.Path","ServerConfig.ServerConfig","Effect.mapError","Effect.map","Option.some","Effect.catch","Effect.succeed","Option.none","Effect.fail","Effect.withSpan","Effect.flatMap","Effect.ignore","Effect.scoped","Option.match","Effect.as","Effect.catchIf","Effect.void","layer","Layer.effect","Schema.Struct","Schema.NullOr","Schema.String","Schema.DateTimeUtcFromString","Context.Service","Schema.fromJsonString","Schema.Literals","Schema.Unknown","Schema.decodeUnknownEffect","toPersistenceSqlOrDecodeError","Schema.isSchemaError","make","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Effect.mapError","Effect.flatMap","Option.match","Effect.succeed","Option.none","Effect.map","Option.some","Effect.forEach","layer","Layer.effect","Schema.TaggedErrorClass","Schema.Defect","Schema.DateTimeUtc","Schema.Number","Schema.Union","Schema.is","Schema.Literals","Schema.optional","Context.Service","SIGNING_SECRET_NAME","Duration.days","Duration.minutes","Schema.Struct","Schema.Literal","Schema.String","Schema.optionalKey","Schema.decodeUnknownEffect","Schema.fromJsonString","make","Effect.gen","Crypto.Crypto","ServerConfig.ServerConfig","ServerSecretStore.ServerSecretStore","AuthSessions.AuthSessionRepository","Ref.make","PubSub.unbounded","PubSub.publish","Effect.asVoid","Option.isNone","Option.none","Ref.get","Option.some","Ref.modify","Effect.flatMap","Effect.void","Option.isSome","Effect.catchCause","Effect.logError","Effect.annotateLogs","Effect.withSpan","Ref.update","Schema.encodeEffect","Effect.fn","Effect.mapError","DateTime.now","DateTime.add","Duration.toMillis","Effect.map","DateTime.make","Effect.forEach","Stream.fromPubSub","layer","Layer.effect","Layer.provideMerge","AuthSessions.layer","nc","isBytes","abytes","concatBytes","randomBytes","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","_0n","_1n","_0n","_1n","_2n","_3n","_4n","gcd","_0n","_1n","concatBytes","Schema.Struct","Schema.Literal","Schema.isNonEmpty","isRecord","Schema.Struct","DpopPublicJwkSchema","Schema.optionalKey","Schema.Never","Schema.fromJsonString","Schema.Literal","Schema.decodeUnknownOption","Schema.isNonEmpty","Schema.Int","Schema.String","Result.getOrThrow","Encoding.decodeBase64Url","Encoding.decodeBase64UrlString","Encoding.encodeBase64Url","Option.isNone","ServerSecretStore.isSecretAlreadyExistsError","Effect.gen","HttpServerRequest.toURL","Option.isNone","DateTime.now","ServerSecretStore.ServerSecretStore","Effect.flatMap","Effect.map","Encoding.encodeBase64Url","Effect.mapError","DateTime.formatIso","Effect.catchIf","ServerSecretStore.isSecretStoreError","Effect.fail","Data.TaggedError","make","Effect.void","Effect.gen","Client.SqlClient","Effect.catch","Effect.map","Option.map","Option.fromNullishOr","Effect.catchDefect","Effect.fail","Effect.flatMap","Effect.isEffect","Effect.succeed","Effect.filterOrFail","Effect.die","Effect.all","Option.match","Effect.mapError","Effect.forEach","Effect.logDebug","Effect.annotateLogs","Effect.withSpan","Effect.catchTag","Effect.as","Effect.catchCause","Effect.logInfo","Order.Number","Arr.flatMapNullishOr","Arr.map","Arr.sort","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","DEFAULT_RUNTIME_MODE","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.asVoid","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.catch","Effect.void","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Effect.gen","SqlClient.SqlClient","Migration0001","Migration0002","Migration0003","Migration0004","Migration0005","Migration0006","Migration0007","Migration0008","Migration0009","Migration0010","Migration0011","Migration0012","Migration0013","Migration0014","Migration0015","Migration0016","Migration0017","Migration0018","Migration0019","Migration0020","Migration0021","Migration0022","Migration0023","Migration0024","Migration0025","Migration0026","Migration0027","Migration0028","Migration0029","Migration0030","Migration0031","Migration0032","Migration0033","Migration0034","Migration0035","Migration0036","Migrator.fromRecord","Migrator.make","Effect.fn","Effect.logDebug","Effect.log","Effect.annotateLogs","Layer.effectDiscard","Effect.fn","Effect.promise","Layer.unwrap","Layer.effectDiscard","Effect.gen","SqlClient.SqlClient","FileSystem.FileSystem","Path.Path","Layer.provideMerge","Schema.Defect","Schema.TaggedErrorClass","Schema.Union","Schema.is","Schema.optional","Schema.String","Context.Service","PairingGrantStore.isBootstrapCredentialInternalError","Effect.mapError","SessionStore.isSessionCredentialInvalidError","make","Effect.gen","EnvironmentAuthPolicy.EnvironmentAuthPolicy","PairingGrantStore.PairingGrantStore","SessionStore.SessionStore","ServerSecretStore.ServerSecretStore","Crypto.Crypto","Effect.tapError","Effect.logWarning","Effect.annotateLogs","Effect.void","Effect.map","Effect.fail","Effect.flatMap","Effect.provideService","Effect.as","Effect.succeed","DateTime.toUtc","Effect.catchIf","Effect.withSpan","Duration.hours","Effect.fn","DateTime.now","HttpServerRequest.toURL","Option.isSome","layer","Layer.effect","Layer.provideMerge","PairingGrantStore.layer","SessionStore.layer","EnvironmentAuthPolicy.layer","Layer.mergeAll","ServerSecretStore.layer","SqlitePersistenceLayer","DateTime.formatIso","DateTime.toUtc","P.isObject","Schema.decodeExit","Schema.fromJsonString","Exit.isFailure","Result.fail","Result.succeed","decodeJsonString","Schema.decodeEffect","Schema.Unknown","SchemaGetter.onSome","Effect.map","Option.some","Effect.mapError","SchemaTransformation.Transformation","SchemaGetter.stringifyJson","SchemaGetter.parseJson","Schema.decodeTo","Schema.encode","Duration.seconds","Duration.minutes","Duration.toMillis","ServerSettingsJson","Schema.decodeUnknownOption","isProviderDriverKind","Option.isSome","Context.Reference","Effect.map","Schema.TaggedErrorClass","Schema.Number","Schema.Defect","Schema.String","Schema.optional","Schema.Union","Effect.fn","Option.none","Effect.callback","Effect.succeedNone","Effect.fail","Result.isSuccess","Effect.succeedSome","Effect.sync","Effect.timeoutOption","Effect.map","Option.flatten","Predicate.compose","Predicate.hasProperty","Effect.try","Effect.as","Effect.catchTags","Effect.succeed","Effect.gen","Data.TaggedError","Context.Reference","Effect.fn","FileSystem.FileSystem","Path.Path","Effect.orElseSucceed","Effect.as","Effect.catchTag","Effect.succeed","Effect.fn","Effect.catchDefect","Effect.sync","expandHomePath","Path.Path","Flag.choice","Flag.withDescription","Flag.optional","Flag.integer","Flag.withSchema","Flag.string","Schema.URLFromString","Flag.boolean","Schema.Int","Flag.withAlias","tailscaleServePortFlag","Config.all","Config.logLevel","Config.withDefault","Config.boolean","Config.string","Config.option","Config.map","Option.getOrUndefined","Config.int","Config.schema","ServerConfig.RuntimeMode","Config.port","Config.url","Argument.string","Argument.withDescription","Argument.optional","Option.firstSomeOf","Effect.fn","FileSystem.FileSystem","Effect.orElseSucceed","Effect.gen","NetService.NetService","Path.Path","Option.none","Option.getOrElse","Option.fromUndefinedOr","Option.match","Effect.succeed","ServerConfig.DEFAULT_PORT","Option.filter","expandHomePath","ServerConfig.deriveServerPaths","Option.isSome","ServerConfig.ensureServerDirectories","Option.some","Effect.fail","ServerConfig.resolveStaticDir","Duration.fromInput","Schema.decodeTo","Schema.Duration","SchemaTransformation.transformOrFail","SchemaIssue.InvalidValue","Duration.format","Effect.gen","GlobalFlag.LogLevel","EnvironmentAuth.EnvironmentAuth","Effect.provide","Layer.mergeAll","EnvironmentAuth.runtimeLayer","Layer.provide","ServerConfig.layer","Layer.succeed","References.MinimumLogLevel","ttlFlag","Flag.string","Flag.withSchema","Flag.withDescription","Flag.optional","Flag.boolean","Flag.withDefault","labelFlag","Command.make","Command.withDescription","Command.withHandler","Option.isSome","Console.log","EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT","Argument.string","Argument.withDescription","Command.withSubcommands","Argument.withSchema","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.option","Option.isSome","Effect.orElseSucceed","Duration.millis","Duration.seconds","Schema.Literals","Schema.Number","Schema.TaggedErrorClass","Schema.Defect","Schema.optional","Schema.Union","Schema.Struct","Schema.Unknown","Stream.decodeText","Stream.runFold","Schema.decodeEffect","Schema.fromJsonString","Effect.mapError","Effect.map","Effect.gen","ChildProcessSpawner.ChildProcessSpawner","ChildProcess.make","Effect.all","Effect.scoped","Effect.timeout","Effect.catchTags","Effect.fail","Duration.toMillis","timeout","Duration.fromInputUnsafe","Effect.scoped","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.fn","HttpServer.HttpServer","EnvironmentAuth.EnvironmentAuth","Schema.Struct","Schema.Literal","Schema.Int","Schema.optional","Schema.String","Schema.TaggedErrorClass","Schema.Literals","Schema.Defect","Schema.decodeUnknownEffect","Schema.fromJsonString","Effect.map","DateTime.now","DateTime.formatIso","Effect.mapError","Effect.gen","FileSystem.FileSystem","Effect.catchTags","Effect.logWarning","Effect.annotateLogs","Effect.matchEffect","Effect.succeed","Option.none","Effect.fail","Option.some","Option.isNone","Effect.as","Duration.millis","Duration.seconds","Schema.TaggedErrorClass","Schema.Array","Schema.String","Schema.Defect","Schema.Number","Schema.is","DateTime.formatIso","Effect.gen","HttpClient.HttpClient","HttpClientRequest.get","Effect.timeout","Effect.mapError","HttpClientResponse.filterStatusOk","Effect.flatMap","HttpClientResponse.schemaBodyJson","Effect.catch","Effect.succeed","isProcessAlive","Effect.fn","Config.string","Config.option","Option.getOrUndefined","ServerConfig.deriveServerPaths","Option.isNone","ServerConfig.make","Effect.sleep","EnvironmentAuth.EnvironmentAuth","Option.getOrElse","Option.isSome","Effect.provide","Layer.provide","ServerConfig.layer","Layer.succeed","References.MinimumLogLevel","Flag.string","Flag.withSchema","Flag.withDescription","Flag.optional","Flag.boolean","Flag.withDefault","Flag.integer","Command.make","Command.withDescription","Command.withHandler","GlobalFlag.LogLevel","Console.log","FetchHttpClient.layer","Data.TaggedError","decode","Channel.fromTransform","Effect.sync","Effect.flatMap","Effect.fail","Effect.void","Effect.suspend","Arr.isArrayNonEmpty","Effect.succeed","Channel.pipeTo","ChannelSchema.decode","Schema.decodeTo","Duration.millis","Schema.String","Data.TaggedClass","Result.succeed","Result.fail","encoder","Duration.toMillis","Effect.gen","Effect.context","HttpClient.mapRequest","HttpClientRequest.prependUrl","HttpClientResponse.matchStatus","Effect.flatMap","Effect.catchCause","Effect.failCause","Cause.combine","Cause.fail","HttpClientError.HttpClientError","HttpClientError.StatusCodeError","Effect.fail","HttpApiSchema.getStatusStream","UndefinedOr.map","Schema.encodeUnknownEffect","HttpApiEndpoint.getPayloadSchemas","Arr.isArrayNonEmpty","HttpMethod.hasBody","Schema.Union","Effect.fnUntraced","HttpClientRequest.make","HttpClientRequest.setUrl","HttpClientRequest.bodyFormData","HttpClientRequest.setBody","HttpClientRequest.appendUrlParams","HttpClientRequest.setHeaders","make","HttpClient.HttpClient","Effect.as","Schema.decodeEffect","MediaType.normalize","HttpApiSchema.isNoContent","HttpApiSchema.getResponseEncoding","HttpClientError.DecodeError","reservedStreamFailureEvent","HttpApiSchema.isStreamSchema","HttpApiSchema.isStreamUint8Array","Effect.map","Stream.provideContext","Schema.Struct","Schema.Literal","Schema.fromJsonString","Schema.toCodecJson","Schema.Cause","Schema.Defect","Sse.decodeSchema","Stream.transformPull","Stream.decodeText","Stream.pipeThroughChannel","Effect.sync","Effect.suspend","Cause.isCause","Effect.succeed","Stream.map","ArrayBuffer","Schema.Uint8Array","Schema.String","Schema.Undefined","Schema.UnknownFromJsonString","SchemaAST.isNull","SchemaAST.toEncoded","Schema.decodeTo","SchemaTransformation.transform","UrlParams.schemaRecord","HttpBody.isHttpBody","HttpApiSchema.getPayloadEncoding","SchemaTransformation.transformOrFail","SchemaIssue.Forbidden","HttpBody.text","SchemaIssue.InvalidValue","Predicate.isObject","HttpBody.urlParams","UrlParams.fromInput","HttpBody.uint8Array","Context.Service","Context.Service","Schema.Struct","Schema.Union","Schema.NullOr","Schema.String","Context.Service","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","Effect.mapError","Layer.effect","Context.Service","Schema.decodeUnknownEffect","Schema.fromJsonString","Schema.Unknown","Schema.Struct","Schema.Union","Schema.NullOr","Schema.Number","toPersistenceSqlOrDecodeError","Schema.isSchemaError","Effect.gen","SqlClient.SqlClient","SqlSchema.findOne","SqlSchema.findAll","Effect.mapError","Effect.flatMap","Stream.empty","Stream.fromEffect","Effect.forEach","Stream.flatMap","Stream.fromIterable","Stream.concat","Layer.effect","Exit.isSuccess","Cause.hasInterruptsOnly","Metric.counter","Metric.timer","Metric.update","Metric.withAttributes","Effect.gen","Clock.currentTimeNanos","exit","Effect.exit","Duration.nanos","Exit.isSuccess","Effect.failCause","Schema.TaggedErrorClass","Schema.String","Schema.optional","Schema.Defect","Schema.Literals","SchemaIssue.makeFormatterDefault","Effect.succeed","Effect.fail","Effect.void","Effect.flatMap","ContractsProjectCreatedPayloadSchema","ContractsProjectMetaUpdatedPayloadSchema","ContractsProjectDeletedPayloadSchema","ContractsThreadCreatedPayloadSchema","ContractsThreadArchivedPayloadSchema","ContractsThreadSettledPayloadSchema","ContractsThreadMetaUpdatedPayloadSchema","ContractsThreadRuntimeModeSetPayloadSchema","ContractsThreadInteractionModeSetPayloadSchema","ContractsThreadDeletedPayloadSchema","ContractsThreadUnarchivedPayloadSchema","ContractsThreadUnsettledPayloadSchema","ContractsThreadSnoozedPayloadSchema","ContractsThreadUnsnoozedPayloadSchema","ContractsThreadPinnedPayloadSchema","ContractsThreadUnpinnedPayloadSchema","ContractsThreadMessageSentPayloadSchema","ContractsThreadProposedPlanUpsertedPayloadSchema","ContractsThreadSessionSetPayloadSchema","ContractsThreadTurnDiffCompletedPayloadSchema","ContractsThreadRevertedPayloadSchema","ContractsThreadActivityAppendedPayloadSchema","settledTurnStateForSessionStatus","Schema.decodeUnknownEffect","Effect.mapError","Effect.map","Effect.gen","Effect.succeed","nowIso","Effect.map","DateTime.now","DateTime.formatIso","Effect.flatMap","Effect.fn","Effect.orDie","Effect.fail","Context.Service","Schema.is","Effect.gen","SqlClient.SqlClient","Crypto.Crypto","Effect.map","DateTime.now","DateTime.formatIso","Queue.unbounded","PubSub.unbounded","Stream.runCollect","PubSub.publish","Effect.exit","Clock.currentTimeMillis","Effect.annotateCurrentSpan","Option.isSome","Effect.provideService","Effect.mapError","Effect.catchTag","Effect.fail","Metric.update","Metric.withAttributes","Duration.millis","Effect.withSpan","Effect.flatMap","Exit.isSuccess","Cause.hasInterruptsOnly","Deferred.succeed","Cause.squash","Effect.catch","Effect.logWarning","Effect.annotateLogs","Effect.void","Deferred.fail","Effect.forever","Queue.take","Effect.forkScoped","Effect.logDebug","Deferred.make","Queue.offer","Deferred.await","Stream.fromPubSub","Effect.sync","Layer.effect","Schema.Struct","Schema.NullOr","Context.Service","Schema.Struct","Schema.String","Schema.NullOr","Schema.Array","Context.Service","Schema.Struct","Schema.String","Context.Service","Schema.Struct","Schema.NullOr","Schema.String","Schema.Unknown","Schema.optional","Context.Service","Schema.Struct","Schema.NullOr","Schema.String","Schema.optional","Schema.Array","Schema.Boolean","Context.Service","Schema.Struct","Schema.NullOr","Context.Service","Schema.Struct","Schema.NullOr","Schema.String","RuntimeMode","Context.Service","Schema.Literals","Schema.Struct","Schema.NullOr","Schema.Array","Context.Service","Schema.Struct","Schema.String","RuntimeMode","Schema.NullOr","Schema.Literals","Schema.optional","Context.Service","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findAll","SqlSchema.findOneOption","Effect.mapError","Layer.effect","Struct.assign","Schema.NullOr","Schema.fromJsonString","Schema.Array","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Schema.Void","Effect.mapError","Layer.effect","Schema.Struct","Schema.NullOr","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Schema.Void","SqlSchema.findOne","Effect.mapError","Effect.map","Layer.effect","ProjectionThreadActivityDbRowSchema","Struct.assign","Schema.fromJsonString","Schema.Unknown","Schema.NullOr","toPersistenceSqlOrDecodeError","Schema.isSchemaError","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findAll","Effect.mapError","Effect.map","Layer.effect","ProjectionThreadMessageDbRowSchema","Struct.assign","Schema.Number","Schema.NullOr","Schema.fromJsonString","Schema.Array","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Effect.mapError","Effect.map","Option.map","Layer.effect","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findAll","Effect.mapError","Layer.effect","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","Effect.mapError","Layer.effect","Struct.assign","Schema.fromJsonString","Schema.Array","toPersistenceSqlOrDecodeError","Schema.isSchemaError","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Effect.mapError","Effect.flatMap","Effect.map","Option.match","Effect.succeed","Option.none","Option.some","Layer.effect","Struct.assign","Schema.fromJsonString","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Effect.mapError","Layer.effect","Mime","Effect.fn","Effect.succeed","Effect.service","FileSystem.FileSystem","Path.Path","Effect.orElseSucceed","Effect.logWarning","Effect.forEach","SqlClient.SqlClient","Option.isNone","Effect.all","Option.getOrUndefined","Option.match","Effect.asVoid","Effect.void","Option.isSome","Effect.flatMap","Effect.catch","Stream.runForEach","Effect.provideService","Effect.catchTag","Effect.fail","Effect.tap","Effect.logDebug","Effect.annotateLogs","Layer.effect","Layer.provideMerge","Schema.Struct","Schema.Array","Schema.NullOr","Context.Service","Context.Service","make","layer","Layer.effect","Effect.sync","Stream.runFold","Effect.map","Schema.String","Schema.Number","Schema.optional","Schema.TaggedErrorClass","Schema.Boolean","Schema.Defect","Schema.Literals","Schema.Union","Context.Service","Effect.fn","Stream.mapError","Stream.runFoldEffect","Effect.fail","Effect.succeed","Effect.map","Duration.fromInputUnsafe","Effect.scoped","Effect.timeoutOption","Effect.flatMap","Option.isSome","Duration.toMillis","ChildProcess.make","Effect.mapError","Effect.void","Stream.run","Stream.encodeText","Stream.make","Effect.all","make","ChildProcessSpawner.ChildProcessSpawner","layer","Layer.effect","Duration.minutes","Context.Service","Effect.fn","ProcessRunner.ProcessRunner","Effect.option","make","Cache.makeWith","Effect.provideService","Exit.match","Duration.zero","Cache.get","layer","Layer.effect","Layer.provide","ProcessRunner.layer","Schema.decodeUnknownEffect","Struct.assign","Schema.NullOr","Schema.fromJsonString","Schema.Array","Schema.Number","Schema.Unknown","Schema.Struct","Schema.String","Schema.Int","toPersistenceSqlOrDecodeError","Schema.isSchemaError","Effect.gen","SqlClient.SqlClient","RepositoryIdentityResolver.RepositoryIdentityResolver","Effect.fn","Effect.forEach","Effect.map","SqlSchema.findAll","Schema.Void","SqlSchema.findOne","SqlSchema.findOneOption","Effect.all","Effect.mapError","Effect.flatMap","Effect.sync","Arr.filterMap","Result.succeed","Result.failVoid","Option.isNone","Effect.succeed","Option.none","Option.some","Option.map","Option.isSome","Layer.effect","Layer.mergeAll","Layer.provide","Layer.provideMerge","ThreadBackgroundLiveness.layer","Schema.decodeTo","Schema.toType","SchemaTransformation.transformOrFail","Effect.succeed","Effect.filterOrFail","Predicate.isNotNull","SchemaIssue.InvalidValue","Effect.map","Effect.gen","Effect.fail","Schema.Array","Schema.isMaxLength","Schema.Unknown","Schema.decodeUnknownExit","Schema.decodeExit","Schema.encodeEffect","Context.Service","make","ServerConfig.ServerConfig","FileSystem.FileSystem","Path.Path","Semaphore.make","PubSub.unbounded","Ref.make","Deferred.make","Scope.make","Effect.addFinalizer","Scope.close","Exit.void","PubSub.publish","Effect.asVoid","Effect.mapError","Effect.fn","Effect.flatMap","Schema.decodeEffect","Effect.forEach","Effect.logWarning","Cause.pretty","Array.filter","Effect.provideService","Cache.make","Cache.get","Cache.invalidate","Array.filterMap","Result.succeed","Result.failVoid","Effect.ignoreCause","Stream.filter","Stream.debounce","Duration.millis","Stream.runForEach","Effect.forkIn","Ref.get","Deferred.await","Ref.set","Effect.exit","Deferred.failCause","Effect.orDie","Effect.failCause","Deferred.succeed","Stream.fromPubSub","Cache.set","layer","Layer.effect","compactEnv","Option.match","Config.all","Config.string","Config.option","Config.map","Effect.orElseSucceed","readCommandLookupEnv","Option.none","Option.some","Option.fromUndefinedOr","Option.isSome","Effect.fn","Encoding.encodeBase64","Context.Service","Effect.annotateCurrentSpan","Option.getOrElse","ChildProcessSpawner.ChildProcessSpawner","ChildProcess.make","Effect.flatMap","Effect.asVoid","Effect.scoped","Effect.mapError","make","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.provideService","layer","Layer.effect","Context.Service","Context.Service","make","Effect.gen","PubSub.unbounded","Ref.make","Ref.modify","Effect.tap","PubSub.publish","Ref.get","Stream.fromPubSub","layer","Layer.effect","Schema.encodeEffect","Schema.encodeUnknownEffect","Schema.decodeUnknownEffect","textEncoder","textDecoder","Effect.flatMap","Effect.mapError","Context.Service","layerTest","Effect.gen","Ref.make","Effect.void","Ref.get","Effect.map","Effect.tap","Ref.set","Stream.empty","Effect.succeed","Layer.effect","Schema.decodeUnknownExit","Equal.equals","make","ServerConfig.ServerConfig","FileSystem.FileSystem","Path.Path","ServerSecretStore.ServerSecretStore","Semaphore.make","PubSub.unbounded","Deferred.make","Scope.make","Effect.addFinalizer","Scope.close","Exit.void","PubSub.publish","Effect.asVoid","Effect.logWarning","Cause.pretty","Cache.make","Cache.get","Option.isSome","Stream.mapEffect","Effect.catch","Effect.as","Stream.map","Effect.fnUntraced","Effect.provideService","Cache.invalidate","Effect.ignoreCause","Stream.filter","Stream.debounce","Duration.millis","Stream.runForEach","Effect.forkIn","Ref.modify","Deferred.await","Effect.exit","Deferred.failCause","Effect.orDie","Effect.failCause","Deferred.succeed","Cache.set","Stream.fromPubSub","PubSub.subscribe","Stream.fromSubscription","layer","Schema.Struct","Schema.String","Schema.Literals","Schema.TaggedErrorClass","Schema.Defect","Schema.Literal","Schema.decodeEffect","Schema.fromJsonString","PlatformError.PlatformError","Schema.SchemaError","Effect.logWarning","Effect.annotateLogs","Effect.map","Option.some","Effect.catchTags","Effect.succeed","Option.none","Effect.fail","Effect.flatMap","Encoding.encodeHex","Effect.mapError","Effect.fn","FileSystem.FileSystem","Path.Path","Option.isNone","Effect.gen","ServerConfig.ServerConfig","Option.isSome","Effect.as","Effect.tapError","Effect.orElseSucceed","Effect.suspend","Config.all","Config.string","Config.withDefault","Config.boolean","Config.number","Config.option","Context.Service","Layer.succeed","Effect.void","make","Effect.gen","HttpClient.HttpClient","ServerConfig.ServerConfig","Ref.make","Effect.flatMap","DateTime.now","Ref.modify","DateTime.formatIso","Effect.fn","Option.getOrUndefined","packageJson.version","HttpClientRequest.post","HttpClientRequest.bodyJson","HttpClientResponse.filterStatusOk","Effect.catch","Ref.update","Effect.fail","Effect.logError","Effect.logDebug","Effect.forever","Effect.sleep","Effect.forkScoped","Effect.addFinalizer","layer","Layer.effect","Schema.Literals","Schema.TaggedErrorClass","Schema.String","Schema.Defect","Schema.Number","Effect.fn","FileSystem.FileSystem","Effect.mapError","Effect.flatMap","Effect.succeed","Effect.catchTags","Effect.logDebug","Effect.annotateLogs","Effect.as","ProcessRunner.ProcessRunner","Effect.map","Option.some","Option.none","Option.isNone","Schema.TaggedErrorClass","Schema.Literals","Schema.String","Schema.Defect","Context.Service","make","Effect.gen","FileSystem.FileSystem","Path.Path","ServerConfig.ServerConfig","Crypto.Crypto","Effect.mapError","Effect.map","packageJson.version","Effect.succeed","layer","Layer.effect","Layer.provide","ProcessRunner.layer","Context.Service","Context.Reference","Effect.gen","Effect.forkScoped","Deferred.make","Deferred.succeed","Effect.andThen","Deferred.await","Schema.TaggedErrorClass","ServerConfig.RuntimeMode","Schema.NullOr","Schema.String","Schema.Number","Schema.Defect","Context.Service","Exit.isSuccess","Deferred.succeed","Deferred.failCause","Effect.gen","Deferred.make","Queue.unbounded","Ref.make","Effect.forever","Queue.take","Effect.flatMap","Effect.forkScoped","Deferred.await","Ref.set","Effect.orDie","Deferred.fail","Ref.get","Queue.offer","Effect.exit","AnalyticsService.AnalyticsService","ProjectionSnapshotQuery.ProjectionSnapshotQuery","Effect.catch","Effect.logWarning","Effect.as","Effect.annotateSpans","Effect.withSpan","Effect.ignoreCause","Effect.asVoid","ServerConfig.ServerConfig","Crypto.Crypto","OrchestrationEngine.OrchestrationEngineService","Path.Path","Option.isNone","DateTime.formatIso","DateTime.now","EnvironmentAuth.EnvironmentAuth","Effect.succeed","ExternalLauncher.ExternalLauncher","Effect.logInfo","make","Keybindings.Keybindings","OrchestrationReactor.OrchestrationReactor","ProviderSessionReaper.ProviderSessionReaper","ServerLifecycleEvents.ServerLifecycleEvents","ServerSettings.ServerSettingsService","ServerEnvironment.ServerEnvironment","Scope.make","Effect.addFinalizer","Scope.close","Exit.void","Effect.logDebug","Scope.provide","Effect.provideService","Console.log","Effect.annotateLogs","Effect.void","Effect.logError","Effect.andThen","Layer.effect","layer","Schema.TaggedErrorClass","Schema.String","Schema.Defect","Schema.Literals","Schema.Union","Context.Service","expandHomePath","make","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.fn","Effect.matchEffect","Effect.succeed","Effect.fail","Effect.mapError","layer","Layer.effect","Schema.is","Schema.TaggedErrorClass","Schema.Literal","Schema.Defect","Schema.String","Schema.Int","Schema.optional","Schema.Number","Schema.Union","HttpClientError.isHttpClientError","Effect.flatMap","Effect.mapError","Layer.mergeAll","WorkspacePaths.layer","Layer.provideMerge","RepositoryIdentityResolver.layer","SqlitePersistenceLayerLive","Duration.seconds","Effect.acquireUseRelease","Effect.ignore","Effect.timeout","HttpApiClient.make","Effect.fn","WorkspacePaths.WorkspacePaths","Path.Path","Effect.result","Effect.gen","ProjectionSnapshotQuery.ProjectionSnapshotQuery","Option.isNone","Option.none","Effect.as","Option.some","Effect.logDebug","GlobalFlag.LogLevel","EnvironmentAuth.EnvironmentAuth","Option.isSome","Console.log","Layer.provide","ServerConfig.layer","Layer.succeed","References.MinimumLogLevel","OrchestrationEngine.OrchestrationEngineService","Effect.provide","EnvironmentAuth.runtimeLayer","FetchHttpClient.layer","Command.make","Argument.string","Argument.withDescription","Flag.string","Flag.withDescription","Flag.optional","Command.withDescription","Command.withHandler","Option.getOrUndefined","ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection","DateTime.formatIso","DateTime.now","Flag.boolean","Flag.withDefault","Command.withSubcommands","layer","HttpRouter.use","Effect.fnUntraced","Effect.context","Effect.die","OpenApi.fromApi","Effect.succeed","Response.jsonUnsafe","Layer.effectContext","Effect.gen","Context.omit","Scope.Scope","Effect.isEffect","Context.makeUnsafe","Effect.map","Redacted.make","Schema.Struct","Schema.String","Request.schemaSearchParams","Request.schemaCookies","Request.schemaHeaders","Effect.match","Result.getOrUndefined","Encoding.decodeBase64String","Schema.decodeUnknownEffect","Schema.Union","SchemaAST.isNull","SchemaAST.toEncoded","hasBody","HttpMethod.hasBody","MediaType.normalize","Response.text","Effect.orDie","Effect.provideContext","Multipart.limitsServices","Effect.flatMap","Stream.provideContext","Effect.fail","Schema.SchemaError","SchemaIssue.InvalidValue","UrlParams.toRecord","Schema.encodeUnknownEffect","UndefinedOr.map","applyMiddleware","Fiber.getCurrent","Context.getUnsafe","HttpRouter.RouteContext","Request.ParsedSearchParams","Response.isHttpServerResponse","Effect.withErrorReporting","Effect.catch","HttpRouter.route","HttpApiMiddleware.isSecurity","Effect.mapError","result","Effect.result","Result.isFailure","Effect.fromResult","HttpApiSchema.getStatusStream","HttpApiSchema.isStreamUint8Array","Stream.isStream","Response.stream","HttpApiSchema.isStreamSchema","Schema.isSchema","Schema.toCodecJson","Schema.Cause","Schema.Defect","Schema.Array","Schema.fromJsonString","Stream.map","Stream.mapArrayEffect","Stream.catchCause","Stream.fromEffect","Stream.encodeText","HttpApiSchema.getStatusSuccess","HttpApiSchema.getStatusError","HttpApiEndpoint.getSuccessSchemas","HttpApiEndpoint.getErrorSchemas","Schema.Never","Schema.decodeTo","HttpApiSchema.getResponseEncoding","HttpApiSchema.isNoContent","SchemaTransformation.transformOrFail","SchemaIssue.Forbidden","Response.empty","Response.uint8Array","Response.urlParams","Response.setHeader","Effect.fn","Effect.gen","PubSub.subscribe","Stream.fromSubscription","Data.TaggedError","Channel.splitLines","Channel.filterArray","Channel.mapEffect","Effect.succeed","Arr.map","Effect.fail","decode","Channel.pipeTo","Channel.decodeText","Duration.seconds","Schema.TaggedErrorClass","Schema.String","Schema.Number","Schema.Defect","Context.Service","Schema.decodeUnknownEffect","Schema.encodeEffect","Schema.fromJsonString","Schema.is","Option.exists","Option.none","Option.some","Effect.fn","Ref.set","PubSub.publish","Effect.callback","Effect.fail","Effect.succeed","Effect.void","make","Ref.make","DateTime.now","DateTime.toEpochMillis","PubSub.sliding","Semaphore.make","Ref.modify","Effect.flatMap","Effect.asVoid","Effect.gen","Effect.mapError","Effect.tapError","Duration.toMillis","Effect.andThen","Effect.catchCause","Effect.logWarning","Stream.runForEach","Effect.forkScoped","Effect.acquireRelease","Effect.try","Effect.sync","NodeStream.fromReadable","Stream.pipeThroughChannel","Ndjson.decode","Stream.mapEffect","Stream.mapError","DateTime.makeUnsafe","Effect.catch","Effect.forever","Effect.sleep","Ref.get","Option.isNone","Option.isSome","Option.contains","Stream.fromPubSub","PubSub.subscribe","Stream.fromSubscription","layer","Layer.effect","Context.Service","make","Effect.fn","DateTime.now","Ref.make","PubSub.sliding","Ref.modify","DateTime.isLessThan","Option.none","Option.some","Effect.flatMap","Option.match","Effect.void","PubSub.publish","Effect.asVoid","Ref.get","Stream.fromPubSub","layer","Layer.effect","Effect.gen","DesktopTelemetryReceiver.DesktopTelemetryReceiver","Stream.map","Stream.runForEach","Effect.forkScoped","Context.Service","DateTime.isGreaterThan","DateTime.toEpochMillis","make","Effect.fn","HostPowerMonitor.HostPowerMonitor","Ref.make","PubSub.sliding","Semaphore.make","Effect.map","Effect.orElseSucceed","Effect.gen","Effect.all","Ref.get","DateTime.now","Effect.flatMap","PubSub.publish","DateTime.add","Ref.update","Effect.andThen","Effect.asVoid","Stream.runForEach","Effect.forkScoped","Effect.forever","Effect.sleep","Stream.fromPubSub","layer","Layer.effect","Context.Service","make","Effect.fn","Ref.make","Ref.update","Effect.gen","DateTime.now","Ref.get","layer","Layer.effect","seconds","Option.fromUndefinedOr","Option.flatMap","Num.parse","Option.isSome","Effect.succeed","Duration.seconds","Effect.map","Duration.millis","Schedule.passthrough","HttpClientError.isHttpClientError","Context.Service","Effect.suspend","Effect.void","Effect.forEach","Effect.flatMap","Scope.Scope","Scope.addFinalizer","Effect.sync","make","Effect.context","Context.get","Duration.max","Duration.fromInputUnsafe","Duration.zero","HttpClient.filterStatusOk","HttpClient.HttpClient","HttpClient.transformResponse","Effect.provideService","HttpClient.TracerPropagationEnabled","HttpClient.retryTransient","Headers.fromRecordUnsafe","Headers.merge","Headers.fromInput","HttpClientRequest.post","HttpClientRequest.setBody","Effect.asVoid","Effect.withTracerEnabled","Effect.catchCause","Effect.logDebug","Effect.annotateLogs","FiberSet.make","FiberSet.runtime","FiberSet.awaitEmpty","Effect.ignore","Effect.interruptible","Effect.timeoutOption","Effect.sleep","Effect.andThen","FiberSet.run","Fiber.await","Effect.forever","Effect.forkIn","make","Config.schema","Schema.UndefinedOr","Config.Record","Schema.StringFromUriComponent","Schema.String","Config.string","Effect.orDie","Context.Service","layerJson","HttpBody.jsonUnsafe","make","OtlpResource.fromConfig","OtlpResource.serviceNameUnsafe","Effect.context","Metric.snapshotUnsafe","OtlpResource.entriesToAttributes","Arr.allocate","Exporter.make","Duration.seconds","layer","Layer.effectDiscard","Layer.provideMerge","Exporter.layerFlusher","make","OtlpResource.fromConfig","OtlpResource.serviceNameUnsafe","Exporter.make","Duration.seconds","Tracer.make","Option.isSome","Cause.hasInterruptsOnly","Cause.prettyErrors","Option.match","Schema.TaggedErrorClass","Schema.Literals","Schema.Number","Schema.String","Schema.Defect","Schema.is","textEncoder","Cause.findErrorOption","Option.isSome","ExitRuntime.isSuccess","Cause.hasInterruptsOnly","Cause.pretty","Option.getOrUndefined","Effect.fn","Effect.sync","Effect.flatMap","Effect.ignore","Effect.void","Effect.withTracerEnabled","Effect.addFinalizer","Effect.forkScoped","Effect.sleep","Effect.andThen","Effect.forever","Tracer.make","Tracer.NativeSpan","Schema.decodeEffect","Schema.TaggedErrorClass","Schema.Literals","Schema.String","Schema.Defect","Context.Service","Effect.logWarning","Effect.annotateLogs","make","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.fn","Effect.map","Option.some","Effect.catchTags","Effect.succeed","Option.none","Effect.as","Option.isNone","layer","Layer.effect","Schema.TaggedErrorClass","Schema.Literals","Schema.String","Schema.optional","Schema.Defect","Context.Service","optionOnNotFound","Effect.map","Option.some","Effect.catchTags","Effect.succeed","Option.none","Effect.fail","make","Effect.gen","FileSystem.FileSystem","Path.Path","WorkspacePaths.WorkspacePaths","T3ProjectFileLoader.T3ProjectFileLoader","Effect.fn","Option.isNone","Effect.mapError","Option.isSome","layer","Layer.effect","Schema.Union","Schema.Struct","Schema.Literal","Schema.String","Schema.Number","Schema.NullOr","Schema.fromJsonString","Schema.decodeUnknownOption","Schema.encodeSync","Option.getOrNull","Effect.map","Option.some","Effect.catchTags","Effect.succeed","Option.none","Effect.fail","Effect.fn","FileSystem.FileSystem","WorkspacePaths.WorkspacePaths","Option.isNone","Effect.all","Path.Path","Option.isSome","Effect.tapError","Effect.logError","Effect.orElseSucceed","Clock.currentTimeMillis","Effect.mapError","ServerConfig.ServerConfig","ProjectFaviconResolver.ProjectFaviconResolver","Crypto.Crypto","Encoding.encodeHex","ServerSecretStore.ServerSecretStore","Context.Service","make","Effect.sync","layer","Layer.succeed","HttpEffect.appendPreResponseHandler","Effect.succeed","HttpServerResponse.setHeaders","HttpServerResponse.setHeader","Effect.gen","HttpServerRequest.HttpServerRequest","Effect.map","Effect.orElseSucceed","HttpServerRequest.toURL","Effect.addFinalizer","Effect.logWarning","Effect.void","Effect.annotateLogsScoped","Effect.annotateCurrentSpan","Effect.flatMap","Effect.fail","Effect.logError","Effect.fn","Layer.effect","EnvironmentAuth.EnvironmentAuth","Effect.catchIf","EnvironmentAuth.isServerAuthCredentialError","EnvironmentAuth.serverAuthCredentialReason","EnvironmentAuth.isServerAuthInternalError","Effect.provideService","Effect.catchTag","HttpApiBuilder.group","Effect.fnUntraced","SessionStore.SessionStore","Effect.fromResult","Cookies.set","Cookies.empty","DateTime.toDate","Effect.catch","HttpServerResponse.mergeCookies","Effect.andThen","EnvironmentAuth.isServerAuthInvalidRequestError","EnvironmentAuth.serverAuthInvalidRequestReason","HttpRouter.middleware","HttpMiddleware.compression","Layer.unwrap","Effect.gen","ServerConfig.ServerConfig","HttpRouter.cors","HttpServerRequest.HttpServerRequest","EnvironmentAuth.EnvironmentAuth","Effect.catchIf","EnvironmentAuth.isServerAuthCredentialError","EnvironmentAuth.serverAuthCredentialReason","EnvironmentAuth.isServerAuthInternalError","HttpApiBuilder.group","Effect.fnUntraced","ServerEnvironment.ServerEnvironment","Effect.fn","Data.TaggedError","HttpRouter.add","BrowserTraceCollector.BrowserTraceCollector","HttpClient.HttpClient","Effect.try","Effect.flatMap","Effect.catch","Effect.logWarning","HttpServerResponse.empty","HttpBody.jsonUnsafe","HttpClientResponse.filterStatusOk","Effect.as","Effect.tapError","Effect.orElseSucceed","HttpServerResponse.text","Effect.catchTags","HttpServerRespondable.toResponse","HttpServerRequest.toURL","Option.isNone","HttpServerResponse.file","HttpServerResponse.redirect","ServerConfig.resolveStaticDir","FileSystem.FileSystem","Path.Path","HttpServerResponse.uint8Array","Mime","Context.Service","Effect.sync","TypeId","Schema.ErrorClass","Schema.String","Schema.ErrorClass","Schema.String","RequestId","ResponseDefectEncoded","position","bundledStrings","textEncoder","fs","createRequire","Context.Service","Data.TaggedError","Predicate.isNullish","Predicate.hasProperty","Effect.suspend","Semaphore.makeUnsafe","Effect.contextWith","Effect.void","Effect.map","Effect.gen","Effect.provideContext","Effect.onExit","Effect.never","makeNoSerialization","Effect.context","Context.get","Scope.Scope","Effect.serviceOption","Scope.addFinalizer","Effect.withFiber","Exit.interrupt","Effect.fnUntraced","Queue.end","Queue.failCause","RpcSchema.isStreamSchema","Headers.fromInput","Headers.empty","Context.empty","Effect.useSpan","Stream.unwrap","Effect.map","Stream.fromQueue","Effect.interrupt","Option.isSome","Effect.void","Headers.merge","Effect.andThen","Effect.onInterrupt","Effect.callback","Effect.withParentSpan","Effect.runForkWith","Fiber.interrupt","Effect.makeSpanScoped","Fiber.getCurrent","Context.getUnsafe","Scope.addFinalizerExit","Exit.isFailure","Cause.interruptors","Queue.bounded","Effect.catchCause","Effect.interruptible","Effect.forkIn","Effect.timeout","Queue.offerAll","Effect.flatMap","Effect.sync","Exit.die","make","Protocol","Transferable.makeCollectorUnsafe","Context.add","Transferable.Collector","Effect.provideContext","Effect.orDie","RequestId","Option.isNone","Effect.onError","Exit.failCause","Effect.matchCauseEffect","Exit.fail","Effect.forEach","Effect.logError","Effect.forkScoped","RpcSchema.getStreamSchemas","Option.map","Schema.decodeUnknownEffect","Schema.toCodecJson","Schema.NonEmptyArray","Schema.encodeEffect","Rpc.exitSchema","Context.Service","Effect.context","Context.get","Scope.Scope","Fiber.runIn","Scope.forkUnsafe","Semaphore.make","Latch.makeUnsafe","Scope.addFinalizer","Effect.withFiber","Effect.runForkWith","Effect.void","Effect.catchDefect","Effect.interrupt","Rpc.ServerClient","Exit.interrupt","Effect.andThen","Exit.die","Effect.ensuring","RpcSchema.isStreamSchema","isWrapper","Rpc.isWrapper","Scope.makeUnsafe","Effect.onExit","Deferred.isDeferred","Cause.hasDies","Cause.hasInterrupts","Cause.squash","Scope.closeUnsafe","Fiber.getCurrent","Effect.withSpan","Tracer.externalSpan","Context.makeUnsafe","onExit","Deferred.await","Effect.isEffect","Effect.flatMap","Effect.whileLoop","Queue.takeAll","Pull.catchDone","Effect.scoped","Stream.runForEachArray","Effect.suspend","Context.getUnsafe","make","Scope.make","Effect.provideContext","Scope.provide","Effect.forkChild","Queue.take","RpcSchema.getStreamSchemas","Schema.decodeUnknownEffect","Schema.toCodecJson","Schema.encodeUnknownEffect","Schema.Array","Option.isSome","Schema.Any","Rpc.exitSchema","Effect.provideService","Transferable.Collector","Effect.catchCause","Cause.map","ResponseDefectEncoded","Effect.annotateLogs","Effect.logDebug","RequestId","Effect.succeed","Effect.matchEffect","Transferable.makeCollectorUnsafe","Headers.fromInput","Effect.tapCause","Effect.logFatal","Scope.close","Context.Service","Effect.gen","HttpServerRequest.HttpServerRequest","Effect.orDie","HttpServerResponse.empty","Effect.forkScoped","RpcSerialization.RpcSerialization","Queue.make","scope","Effect.scope","Scope.addFinalizerExit","Queue.offer","Predicate.isTagged","Socket.CloseEvent","Effect.catchReason","Effect.sync","Effect.succeedNone","Context.Service","Effect.fn","Ref.make","Ref.modify","Ref.update","Ref.get","Semaphore.make","Effect.gen","Effect.fail","Effect.ensuring","Option.match","Config.all","Config.string","Config.option","Config.map","Effect.orElseSucceed","Context.Reference","Schema.Struct","Schema.optional","Schema.String","makeManualProviderMaintenanceCapabilities","Effect.fn","Effect.catchTag","Effect.succeed","FileSystem.FileSystem","HttpClient.HttpClient","HttpClientRequest.get","HttpClientRequest.setHeader","Effect.timeoutOption","Option.none","Option.isNone","Effect.flatMap","Schema.decodeUnknownEffect","DateTime.toEpochMillis","DateTime.now","DateTime.formatIso","Schema.is","Context.Service","Data.TaggedError","nowIso","Effect.map","DateTime.now","DateTime.formatIso","Effect.fn","ChildProcess.make","Effect.mapError","Effect.addFinalizer","Effect.ignore","Effect.all","Effect.scoped","Effect.timeoutOption","Duration.millis","Option.match","make","ChildProcessSpawner.ChildProcessSpawner","HttpClient.HttpClient","Effect.flatMap","Effect.forEach","Effect.andThen","Effect.succeed","Effect.provideService","Effect.catchCause","Effect.logWarning","Cause.pretty","Effect.as","Effect.asVoid","Ref.make","Ref.set","Cause.squash","Ref.get","layer","Layer.effect","asRecord","asTrimmedString","Effect.gen","DateTime.formatIso","DateTime.now","FileSystem.FileSystem","Path.Path","WorkspacePaths.WorkspacePaths","Effect.mapError","Effect.forEach","Schema.TaggedErrorClass","Schema.String","Schema.optional","Schema.Defect","Context.Service","Effect.withSpan","Effect.provideService","References.TracerEnabled","Stream.withSpan","Stream.provideService","Effect.gen","Clock.currentTimeNanos","Metric.update","Metric.withAttributes","Duration.nanos","Stream.unwrap","Stream.onExit","exit","Effect.exit","Exit.isFailure","Effect.failCause","Context.Service","Context.Service","Context.Service","Schema.TaggedErrorClass","Schema.String","Schema.optional","Schema.Defect","Schema.Number","Context.Service","Effect.fn","Effect.try","Effect.tryPromise","Effect.fail","make","Effect.acquireRelease","Effect.orDie","layer","Layer.effect","LayerMap.Service","Schema.TaggedErrorClass","Schema.optional","Schema.String","Schema.Defect","Schema.Union","WorkspacePaths.WorkspaceRootNotExistsError","WorkspacePaths.WorkspaceRootCreateFailedError","WorkspacePaths.WorkspaceRootStatFailedError","WorkspacePaths.WorkspaceRootNotDirectoryError","WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed","WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut","WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed","Context.Service","expandHomePath","Effect.fn","make","Effect.gen","Path.Path","WorkspacePaths.WorkspacePaths","WorkspaceSearchIndex.WorkspaceSearchIndexMap","Effect.orElseSucceed","WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS","WorkspaceSearchIndex.workspaceSearchIndexKey","RcMap.has","Effect.logWarning","WorkspaceSearchIndex.WorkspaceSearchIndex","Effect.provide","Effect.catchTags","Effect.tryPromise","Effect.catchIf","Effect.succeed","layer","Layer.effect","Layer.provide","Schema.TaggedErrorClass","Schema.String","Schema.Literals","Schema.Defect","Schema.Union","Context.Service","make","Effect.gen","FileSystem.FileSystem","Path.Path","WorkspacePaths.WorkspacePaths","WorkspaceEntries.WorkspaceEntries","Effect.fn","Effect.tryPromise","Effect.acquireUseRelease","Effect.mapError","layer","Layer.effect","Context.Service","make","Effect.gen","ProcessRunner.ProcessRunner","Effect.fn","Effect.mapError","Effect.all","Stream.fromEffectSchedule","Schedule.spaced","Stream.map","layer","Layer.effect","Layer.provide","ProcessRunner.layer","Schema.TaggedErrorClass","Schema.String","Schema.optional","Schema.Array","Schema.Defect","Context.Service","Context.Service","Effect.tryPromise","NodeFs","Effect.flatMap","Effect.void","make","Effect.gen","PtyAdapter.PtyAdapter","context","Effect.context","Effect.runForkWith","Effect.forEach","Effect.fn","result","Effect.result","Effect.try","Effect.sync","layer","Layer.effect","Schema.is","nowIso","Effect.map","DateTime.now","DateTime.formatIso","Duration.seconds","Effect.timeoutOption","Option.getOrElse","Schema.TaggedErrorClass","Schema.String","Stream.fail","Effect.gen","Crypto.Crypto","ProjectionSnapshotQuery.ProjectionSnapshotQuery","OrchestrationEngine.OrchestrationEngineService","ProviderRuntimeIngestion.ProviderRuntimeIngestionService","Keybindings.Keybindings","ExternalLauncher.ExternalLauncher","ProviderRegistry.ProviderRegistry","ProviderAdapterRegistry.ProviderAdapterRegistry","ProviderSessionDirectory.ProviderSessionDirectory","ProviderService.ProviderService","ServerConfig.ServerConfig","ServerLifecycleEvents.ServerLifecycleEvents","ServerSettings.ServerSettingsService","ServerRuntimeStartup.ServerRuntimeStartup","WorkspaceEntries.WorkspaceEntries","WorkspaceFileSystem.WorkspaceFileSystem","GitWorkspace.GitWorkspace","TerminalManager.TerminalManager","ServerEnvironment.ServerEnvironment","BackgroundPolicy.BackgroundPolicy","EnvironmentAuth.EnvironmentAuth","PairingGrantStore.PairingGrantStore","SessionStore.SessionStore","ProviderMaintenanceRunner.ProviderMaintenanceRunner","Ref.make","Effect.addFinalizer","Ref.get","Effect.flatMap","Effect.forEach","Effect.ignore","Effect.mapError","Option.match","Effect.fail","Effect.succeed","observeRpcEffect","instrumentRpcEffect","observeRpcStream","instrumentRpcStream","observeRpcStreamEffect","instrumentRpcStreamEffect","Effect.all","Cause.squash","Option.some","Option.none","Effect.retry","Effect.tapError","Effect.logWarning","Effect.orElseSucceed","Option.flatMap","Option.isSome","Duration.millis","Stream.groupedWithin","Stream.mapEffect","Stream.flatMap","Stream.fromIterable","Effect.catchCause","Cause.hasInterruptsOnly","Effect.ignoreCause","Effect.void","Effect.andThen","ServerSettings.redactServerSettingsForClient","Effect.as","Stream.filter","Stream.map","Queue.unbounded","Effect.forkScoped","Stream.runForEach","Queue.offer","Stream.fromQueue","Effect.logError","Stream.concat","Stream.fromEffect","Queue.takeAll","Stream.make","Stream.mapError","Stream.drain","Option.isNone","Effect.sync","PortProxy.listAuthorizedPorts","PortProxy.authorizePort","PortProxy.revokePort","Ref.update","Stream.debounce","Stream.merge","Ref.updateAndGet","Stream.callback","Effect.acquireRelease","Stream.unwrap","Layer.unwrap","HttpRouter.add","HttpServerRequest.HttpServerRequest","Effect.catchIf","EnvironmentAuth.isServerAuthCredentialError","EnvironmentAuth.serverAuthCredentialReason","EnvironmentAuth.isServerAuthInternalError","RpcServer.toHttpEffectWebsocket","Effect.provide","Layer.provideMerge","RpcSerialization.layerJson","Layer.provide","ProviderMaintenanceRunner.layer","Effect.acquireUseRelease","Effect.catchTags","HttpServerRespondable.toResponse","Effect.gen","Effect.fail","HttpClient.HttpClient","HttpClientRequest.post","HttpClientRequest.setHeaders","HttpClientRequest.bodyJson","HttpClientResponse.filterStatusOk","RpcSerialization.RpcSerialization","Queue.make","Effect.fnUntraced","scope","Effect.scope","Scope.addFinalizerExit","Queue.offer","Effect.asVoid","Effect.void","Effect.orDie","Effect.whileLoop","Predicate.isTagged","Socket.CloseEvent","Effect.catchReason","Effect.succeed","Effect.sync","Effect.succeedNone","Effect.scopedWith","FiberSet.make","Scope.provide","FiberSet.runtime","Effect.isEffect","Deferred.await","Effect.raceFirst","FiberSet.join","Socket.make","EnvironmentAuth.EnvironmentAuth","SessionStore.SessionStore","ServerConfig.ServerConfig","ChildProcessSpawner.ChildProcessSpawner","Effect.logInfo","Socket.makeWebSocket","Effect.provide","NodeSocket.layerWebSocketConstructor","Effect.logWarning","Effect.provideService","Effect.catch","Effect.logError","Effect.addFinalizer","Effect.runFork","Deferred.succeed","Queue.bounded","Queue.offerUnsafe","Effect.forkScoped","Effect.forever","Queue.take","Effect.flatMap","Effect.andThen","Effect.ignore","RpcSerialization.layerJson","Effect.context","Layer.build","Layer.provideMerge","Layer.provide","ProviderMaintenanceRunner.layer","Effect.provideContext","RpcServer.make","RpcServer.Protocol","Effect.tapCause","HttpClientRequest.make","HttpClientRequest.setBody","HttpBody.uint8Array","Effect.match","Effect.tap","Deferred.make","Effect.scoped","Effect.ensuring","Effect.tapDefect","Effect.tapError","Effect.retry","Schedule.spaced","Effect.catchCause","layer","Layer.effectDiscard","Effect.gen","Effect.acquireRelease","TxQueue.unbounded","TxQueue.shutdown","TxRef.make","TxQueue.take","Effect.tap","Effect.ensuring","TxRef.update","Effect.forever","Effect.forkScoped","TxRef.get","Effect.txRetry","Effect.void","Effect.tx","TxQueue.offer","Context.Service","make","Effect.gen","ServerEnvironment.ServerEnvironment","ProjectionSnapshotQuery.ProjectionSnapshotQuery","OrchestrationEngine.OrchestrationEngineService","Ref.make","Effect.fn","Option.isNone","Ref.update","Ref.get","Effect.tryPromise","Effect.fail","Effect.catchCause","Effect.logWarning","Stream.runForEach","Effect.void","layer","Layer.effectDiscard","Effect.forkScoped","Schema.Struct","Schema.String","Schema.NullOr","RuntimeMode","Schema.Unknown","Context.Service","Struct.assign","Schema.fromJsonString","Schema.decodeUnknownEffect","Schema.isSchemaError","make","Effect.gen","SqlClient.SqlClient","SqlSchema.void","SqlSchema.findOneOption","SqlSchema.findAll","Schema.Void","Effect.mapError","Effect.flatMap","Option.match","Effect.succeed","Option.none","Effect.map","Option.some","Effect.forEach","Effect.catch","Effect.logWarning","Effect.as","Arr.filterMap","Option.isSome","Result.succeed","Result.failVoid","layer","Layer.effect","Schema.TaggedErrorClass","Schema.String","Schema.optional","Schema.Defect","Schema.decodeUnknownEffect","Effect.mapError","isRecord","Effect.map","Effect.gen","ProviderSessionRuntime.ProviderSessionRuntimeRepository","Effect.flatMap","Option.match","Effect.succeed","Option.none","Option.some","Effect.fn","Option.getOrUndefined","DateTime.formatIso","DateTime.now","Effect.fail","Effect.forEach","Layer.effect","Context.Service","Effect.fn","Effect.flatMap","Effect.fail","Effect.succeed","Effect.map","Layer.effect","Schema.encodeUnknownEffect","Schema.fromJsonString","Schema.Unknown","Schema.TaggedErrorClass","Schema.String","Schema.Number","Schema.Defect","Effect.logWarning","Effect.annotateLogs","Effect.fail","Effect.succeed","Effect.fnUntraced","Effect.catch","Effect.as","Effect.try","Clock.currentTimeMillis","Effect.sync","SynchronizedRef.make","Scope.make","SynchronizedRef.modifyEffect","Effect.forEach","Effect.void","Effect.forkIn","Effect.sleep","Effect.andThen","close","Scope.close","Exit.void","Effect.map","DateTime.formatIso","Effect.uninterruptible","Context.Service","make","Effect.gen","ResourceAttribution.ResourceAttribution","EventNdjsonLogger.makeEventNdjsonLogStore","Effect.catch","Effect.logWarning","Effect.annotateLogs","Effect.as","Effect.addFinalizer","layer","Layer.effect","Schema.is","Schema.Struct","Schema.decodeUnknownEffect","Effect.mapError","SchemaIssue.makeFormatterDefault","Effect.fn","Effect.service","AnalyticsService.AnalyticsService","ProviderEventLoggers.ProviderEventLoggers","ProviderAdapterRegistry.ProviderAdapterRegistry","ProviderSessionDirectory.ProviderSessionDirectory","PubSub.unbounded","Effect.map","DateTime.now","DateTime.formatIso","Effect.succeed","Effect.tap","Effect.void","Effect.flatMap","PubSub.publish","Effect.asVoid","Effect.fail","Effect.gen","Effect.sync","Effect.andThen","Ref.make","Ref.get","Effect.tapError","Effect.logWarning","Effect.option","Option.isNone","Stream.runForEach","Effect.forkScoped","Ref.set","Stream.fromSubscription","Effect.annotateCurrentSpan","Option.getOrUndefined","Effect.forEach","Effect.catchCause","Effect.orElseSucceed","Option.none","Effect.die","Effect.addFinalizer","Stream.fromPubSub","Layer.effect","ProviderService.ProviderService","Effect.gen","Clock.currentTimeMillis","Effect.logWarning","Effect.map","Option.getOrUndefined","Effect.logDebug","Effect.tap","Effect.logInfo","Effect.as","Effect.catchCause","Effect.catch","Effect.catchDefect","Effect.repeat","Schedule.spaced","Duration.millis","Layer.effect","Context.Service","Effect.flatMap","Effect.succeed","Effect.fail","make","Effect.gen","ProviderInstanceRegistry.ProviderInstanceRegistry","layer","Layer.effect","isTextGenerationError","Schema.is","Schema.toJsonSchemaDocument","Schema.Struct","Schema.String","Schema.TaggedErrorClass","Schema.String","Schema.Number","Schema.is","PlatformError.PlatformError","Effect.gen","ChildProcessSpawner.ChildProcessSpawner","Effect.all","Effect.map","Effect.scoped","Context.Reference","Effect.fn","Effect.logWarning","Effect.fn","Path.Path","parseYamlDocument","Effect.fn","Path.Path","FileSystem.FileSystem","Effect.orElseSucceed","DateTime.make","Option.isSome","DateTime.formatIso","Effect.gen","Effect.tryPromise","claudeQuery","Effect.ensuring","Effect.sync","Effect.timeoutOption","Effect.result","Effect.map","Result.isFailure","Option.isSome","Effect.fn","ChildProcess.make","DateTime.formatIso","DateTime.now","Effect.logWarning","Option.isNone","Effect.orElseSucceed","nowIso","Schema.Struct","Schema.Unknown","encodeJsonString","Schema.encodeEffect","Schema.fromJsonString","Schema.decodeEffect","Effect.fn","ChildProcessSpawner.ChildProcessSpawner","Stream.decodeText","Stream.runFold","Effect.mapError","ChildProcess.make","Stream.encodeText","Stream.make","Effect.all","Effect.scoped","Effect.timeoutOption","Effect.flatMap","Option.match","Effect.fail","Effect.succeed","Effect.catchTags","encodeUnknownJsonStringExit","Schema.encodeUnknownExit","Schema.fromJsonString","Schema.Unknown","Schema.decodeUnknownExit","PROVIDER","encodeJsonStringForDiagnostics","Exit.isSuccess","Cause.prettyErrors","Cause.squash","Cause.hasInterruptsOnly","Cause.isFailReason","asRuntimeItemId","asRuntimeRequestId","Effect.fn","Effect.mapError","FileSystem.FileSystem","Path.Path","Crypto.Crypto","Effect.provideService","Queue.unbounded","Effect.map","DateTime.now","DateTime.formatIso","Effect.all","Queue.offer","Effect.asVoid","Effect.fnUntraced","Effect.promise","DateTime.makeUnsafe","unknownMessage","Stream.fromAsyncIterable","Stream.takeWhile","Stream.runForEach","Exit.isFailure","Deferred.succeed","Queue.shutdown","Fiber.interrupt","Effect.try","Effect.catch","Effect.fail","Effect.succeed","Effect.logWarning","Effect.catchCause","Effect.context","Effect.runForkWith","Effect.runPromiseWith","Stream.fromQueue","Stream.filter","Stream.map","Stream.catchCause","Stream.empty","Stream.failCause","Stream.toAsyncIterable","Ref.make","Deferred.make","Deferred.await","Ref.get","Effect.annotateCurrentSpan","context","Ref.set","Effect.exit","Effect.flatMap","Effect.void","Effect.logError","Effect.tryPromise","Effect.forEach","Effect.timeoutOption","Effect.ignore","Effect.sync","Effect.addFinalizer","Effect.tap","Effect.fn","BackgroundPolicy.BackgroundPolicy","Semaphore.make","Effect.acquireRelease","PubSub.unbounded","PubSub.shutdown","Ref.make","scope","Effect.scope","Ref.modify","Equal.equals","PubSub.publish","Ref.getAndSet","Fiber.interrupt","Effect.ignore","Ref.get","Effect.map","Effect.ignoreCause","Effect.forkIn","Ref.set","Effect.gen","Effect.all","Effect.succeed","Effect.orElseSucceed","Queue.sliding","Stream.map","Duration.toMillis","Stream.changes","Stream.runForEach","Queue.offer","Effect.asVoid","Effect.forkScoped","Effect.forever","Effect.flatMap","Effect.raceFirst","Effect.sleep","Duration.fromInputUnsafe","Effect.as","Queue.take","Effect.void","Effect.tapError","Effect.logError","Effect.orDie","Stream.fromPubSub","Equal.equals","Effect.map","Stream.map","Schema.decodeSync","DRIVER_KIND","Duration.minutes","UPDATE","withInstanceIdentity","Effect.gen","ChildProcessSpawner.ChildProcessSpawner","FileSystem.FileSystem","Path.Path","HttpClient.HttpClient","Cache.make","Effect.provideService","Cache.get","Effect.map","Effect.flatMap","Effect.mapError","encodeJsonString","Schema.encodeEffect","Schema.fromJsonString","Schema.Unknown","Effect.fn","FileSystem.FileSystem","Path.Path","ChildProcessSpawner.ChildProcessSpawner","Effect.service","ServerConfig.ServerConfig","Stream.decodeText","Stream.runFold","Effect.mapError","Effect.tap","Effect.catch","Effect.void","Effect.orElseSucceed","ChildProcess.make","Stream.encodeText","Stream.make","Effect.all","Effect.asVoid","Effect.gen","Effect.scoped","Effect.timeoutOption","Effect.flatMap","Option.match","Effect.fail","Schema.decodeEffect","Effect.catchTags","Effect.ensuring","Schema.Literals","schemaIssueDiagnostics","Schema.TaggedErrorClass","Schema.optional","Schema.String","Schema.Defect","Schema.Number","Schema.optionalKey","Schema.Int","Schema.Array","Schema.Unknown","Schema.Union","Schema.Union","Schema.Struct","Schema.String","Schema.Literal","Schema.optionalKey","Schema.Null","Schema.Literals","Schema.isInt","Schema.isGreaterThanOrEqualTo","Schema.Array","Schema.Boolean","Schema.Unknown","Schema.Record","Schema.isMinLength","Schema.StructWithRest","Schema.isFinite","ClientNotification","ClientRequest","RequestId","CodexSchema.V1InitializeParams","CodexSchema.V2ThreadStartParams","CodexSchema.V2ThreadResumeParams","CodexSchema.V2ThreadForkParams","CodexSchema.V2ThreadArchiveParams","CodexSchema.V2ThreadDeleteParams","CodexSchema.V2ThreadUnsubscribeParams","CodexSchema.V2ThreadSetNameParams","CodexSchema.V2ThreadGoalSetParams","CodexSchema.V2ThreadGoalGetParams","CodexSchema.V2ThreadGoalClearParams","CodexSchema.V2ThreadMetadataUpdateParams","CodexSchema.V2ThreadUnarchiveParams","CodexSchema.V2ThreadCompactStartParams","CodexSchema.V2ThreadShellCommandParams","CodexSchema.V2ThreadApproveGuardianDeniedActionParams","CodexSchema.V2ThreadRollbackParams","CodexSchema.V2ThreadListParams","CodexSchema.V2ThreadLoadedListParams","CodexSchema.V2ThreadReadParams","CodexSchema.V2ThreadInjectItemsParams","CodexSchema.V2SkillsListParams","CodexSchema.V2SkillsExtraRootsSetParams","CodexSchema.V2HooksListParams","CodexSchema.V2MarketplaceAddParams","CodexSchema.V2MarketplaceRemoveParams","CodexSchema.V2MarketplaceUpgradeParams","CodexSchema.V2PluginListParams","CodexSchema.V2PluginInstalledParams","CodexSchema.V2PluginReadParams","CodexSchema.V2PluginSkillReadParams","CodexSchema.V2PluginShareSaveParams","CodexSchema.V2PluginShareUpdateTargetsParams","CodexSchema.V2PluginShareListParams","CodexSchema.V2PluginShareCheckoutParams","CodexSchema.V2PluginShareDeleteParams","CodexSchema.V2AppsReadParams","CodexSchema.V2AppsListParams","CodexSchema.V2AppsInstalledParams","CodexSchema.V2FsReadFileParams","CodexSchema.V2FsWriteFileParams","CodexSchema.V2FsCreateDirectoryParams","CodexSchema.V2FsGetMetadataParams","CodexSchema.V2FsReadDirectoryParams","CodexSchema.V2FsRemoveParams","CodexSchema.V2FsCopyParams","CodexSchema.V2FsWatchParams","CodexSchema.V2FsUnwatchParams","CodexSchema.V2SkillsConfigWriteParams","CodexSchema.V2PluginInstallParams","CodexSchema.V2PluginUninstallParams","CodexSchema.V2TurnStartParams","CodexSchema.V2TurnSteerParams","CodexSchema.V2TurnInterruptParams","CodexSchema.V2ReviewStartParams","CodexSchema.V2ModelListParams","CodexSchema.V2ModelProviderCapabilitiesReadParams","CodexSchema.V2ExperimentalFeatureListParams","CodexSchema.V2PermissionProfileListParams","CodexSchema.V2ExperimentalFeatureEnablementSetParams","CodexSchema.V2McpServerOauthLoginParams","CodexSchema.V2ListMcpServerStatusParams","CodexSchema.V2McpResourceReadParams","CodexSchema.V2McpServerToolCallParams","CodexSchema.V2WindowsSandboxSetupStartParams","CodexSchema.V2LoginAccountParams","CodexSchema.V2CancelLoginAccountParams","CodexSchema.V2ConsumeAccountRateLimitResetCreditParams","CodexSchema.V2SendAddCreditsNudgeEmailParams","CodexSchema.V2FeedbackUploadParams","CodexSchema.V2CommandExecParams","CodexSchema.V2CommandExecWriteParams","CodexSchema.V2CommandExecTerminateParams","CodexSchema.V2CommandExecResizeParams","CodexSchema.V2ConfigReadParams","CodexSchema.V2ExternalAgentConfigDetectParams","CodexSchema.V2ExternalAgentConfigImportParams","CodexSchema.V2ConfigValueWriteParams","CodexSchema.V2ConfigBatchWriteParams","CodexSchema.V2GetAccountParams","CodexSchema.GetConversationSummaryParams","CodexSchema.GitDiffToRemoteParams","CodexSchema.GetAuthStatusParams","CodexSchema.FuzzyFileSearchParams","CodexSchema.V1InitializeResponse","CodexSchema.V2ThreadStartResponse","CodexSchema.V2ThreadResumeResponse","CodexSchema.V2ThreadForkResponse","CodexSchema.V2ThreadArchiveResponse","CodexSchema.V2ThreadDeleteResponse","CodexSchema.V2ThreadUnsubscribeResponse","CodexSchema.V2ThreadSetNameResponse","CodexSchema.V2ThreadGoalSetResponse","CodexSchema.V2ThreadGoalGetResponse","CodexSchema.V2ThreadGoalClearResponse","CodexSchema.V2ThreadMetadataUpdateResponse","CodexSchema.V2ThreadUnarchiveResponse","CodexSchema.V2ThreadCompactStartResponse","CodexSchema.V2ThreadShellCommandResponse","CodexSchema.V2ThreadApproveGuardianDeniedActionResponse","CodexSchema.V2ThreadRollbackResponse","CodexSchema.V2ThreadListResponse","CodexSchema.V2ThreadLoadedListResponse","CodexSchema.V2ThreadReadResponse","CodexSchema.V2ThreadInjectItemsResponse","CodexSchema.V2SkillsListResponse","CodexSchema.V2SkillsExtraRootsSetResponse","CodexSchema.V2HooksListResponse","CodexSchema.V2MarketplaceAddResponse","CodexSchema.V2MarketplaceRemoveResponse","CodexSchema.V2MarketplaceUpgradeResponse","CodexSchema.V2PluginListResponse","CodexSchema.V2PluginInstalledResponse","CodexSchema.V2PluginReadResponse","CodexSchema.V2PluginSkillReadResponse","CodexSchema.V2PluginShareSaveResponse","CodexSchema.V2PluginShareUpdateTargetsResponse","CodexSchema.V2PluginShareListResponse","CodexSchema.V2PluginShareCheckoutResponse","CodexSchema.V2PluginShareDeleteResponse","CodexSchema.V2AppsReadResponse","CodexSchema.V2AppsListResponse","CodexSchema.V2AppsInstalledResponse","CodexSchema.V2FsReadFileResponse","CodexSchema.V2FsWriteFileResponse","CodexSchema.V2FsCreateDirectoryResponse","CodexSchema.V2FsGetMetadataResponse","CodexSchema.V2FsReadDirectoryResponse","CodexSchema.V2FsRemoveResponse","CodexSchema.V2FsCopyResponse","CodexSchema.V2FsWatchResponse","CodexSchema.V2FsUnwatchResponse","CodexSchema.V2SkillsConfigWriteResponse","CodexSchema.V2PluginInstallResponse","CodexSchema.V2PluginUninstallResponse","CodexSchema.V2TurnStartResponse","CodexSchema.V2TurnSteerResponse","CodexSchema.V2TurnInterruptResponse","CodexSchema.V2ReviewStartResponse","CodexSchema.V2ModelListResponse","CodexSchema.V2ModelProviderCapabilitiesReadResponse","CodexSchema.V2ExperimentalFeatureListResponse","CodexSchema.V2PermissionProfileListResponse","CodexSchema.V2ExperimentalFeatureEnablementSetResponse","CodexSchema.V2McpServerOauthLoginResponse","CodexSchema.V2McpServerRefreshResponse","CodexSchema.V2ListMcpServerStatusResponse","CodexSchema.V2McpResourceReadResponse","CodexSchema.V2McpServerToolCallResponse","CodexSchema.V2WindowsSandboxSetupStartResponse","CodexSchema.V2WindowsSandboxReadinessResponse","CodexSchema.V2LoginAccountResponse","CodexSchema.V2CancelLoginAccountResponse","CodexSchema.V2LogoutAccountResponse","CodexSchema.V2GetAccountRateLimitsResponse","CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse","CodexSchema.V2GetAccountTokenUsageResponse","CodexSchema.V2GetWorkspaceMessagesResponse","CodexSchema.V2SendAddCreditsNudgeEmailResponse","CodexSchema.V2FeedbackUploadResponse","CodexSchema.V2CommandExecResponse","CodexSchema.V2CommandExecWriteResponse","CodexSchema.V2CommandExecTerminateResponse","CodexSchema.V2CommandExecResizeResponse","CodexSchema.V2ConfigReadResponse","CodexSchema.V2ExternalAgentConfigDetectResponse","CodexSchema.V2ExternalAgentConfigImportResponse","CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse","CodexSchema.V2ConfigWriteResponse","CodexSchema.V2ConfigRequirementsReadResponse","CodexSchema.V2GetAccountResponse","CodexSchema.GetConversationSummaryResponse","CodexSchema.GitDiffToRemoteResponse","CodexSchema.GetAuthStatusResponse","CodexSchema.FuzzyFileSearchResponse","CodexSchema.CommandExecutionRequestApprovalParams","CodexSchema.FileChangeRequestApprovalParams","CodexSchema.ToolRequestUserInputParams","CodexSchema.McpServerElicitationRequestParams","CodexSchema.PermissionsRequestApprovalParams","CodexSchema.DynamicToolCallParams","CodexSchema.ChatgptAuthTokensRefreshParams","CodexSchema.AttestationGenerateParams","CodexSchema.ApplyPatchApprovalParams","CodexSchema.ExecCommandApprovalParams","CodexSchema.CommandExecutionRequestApprovalResponse","CodexSchema.FileChangeRequestApprovalResponse","CodexSchema.ToolRequestUserInputResponse","CodexSchema.McpServerElicitationRequestResponse","CodexSchema.PermissionsRequestApprovalResponse","CodexSchema.DynamicToolCallResponse","CodexSchema.ChatgptAuthTokensRefreshResponse","CodexSchema.AttestationGenerateResponse","CodexSchema.ApplyPatchApprovalResponse","CodexSchema.ExecCommandApprovalResponse","CodexSchema.V2ErrorNotification","CodexSchema.V2ThreadStartedNotification","CodexSchema.V2ThreadStatusChangedNotification","CodexSchema.V2ThreadArchivedNotification","CodexSchema.V2ThreadDeletedNotification","CodexSchema.V2ThreadUnarchivedNotification","CodexSchema.V2ThreadClosedNotification","CodexSchema.V2SkillsChangedNotification","CodexSchema.V2ThreadNameUpdatedNotification","CodexSchema.V2ThreadGoalUpdatedNotification","CodexSchema.V2ThreadGoalClearedNotification","CodexSchema.V2EnvironmentConnectionNotification","CodexSchema.V2ThreadSettingsUpdatedNotification","CodexSchema.V2ThreadTokenUsageUpdatedNotification","CodexSchema.V2TurnStartedNotification","CodexSchema.V2HookStartedNotification","CodexSchema.V2TurnCompletedNotification","CodexSchema.V2HookCompletedNotification","CodexSchema.V2TurnDiffUpdatedNotification","CodexSchema.V2TurnPlanUpdatedNotification","CodexSchema.V2ItemStartedNotification","CodexSchema.V2ItemGuardianApprovalReviewStartedNotification","CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification","CodexSchema.V2ItemCompletedNotification","CodexSchema.V2RawResponseItemCompletedNotification","CodexSchema.V2RawResponseCompletedNotification","CodexSchema.V2AgentMessageDeltaNotification","CodexSchema.V2PlanDeltaNotification","CodexSchema.V2CommandExecOutputDeltaNotification","CodexSchema.V2ProcessOutputDeltaNotification","CodexSchema.V2ProcessExitedNotification","CodexSchema.V2CommandExecutionOutputDeltaNotification","CodexSchema.V2TerminalInteractionNotification","CodexSchema.V2FileChangeOutputDeltaNotification","CodexSchema.V2FileChangePatchUpdatedNotification","CodexSchema.V2ServerRequestResolvedNotification","CodexSchema.V2McpToolCallProgressNotification","CodexSchema.V2McpServerOauthLoginCompletedNotification","CodexSchema.V2McpServerStatusUpdatedNotification","CodexSchema.V2AccountUpdatedNotification","CodexSchema.V2AccountRateLimitsUpdatedNotification","CodexSchema.V2AppListUpdatedNotification","CodexSchema.V2RemoteControlStatusChangedNotification","CodexSchema.V2ExternalAgentConfigImportProgressNotification","CodexSchema.V2ExternalAgentConfigImportCompletedNotification","CodexSchema.V2FsChangedNotification","CodexSchema.V2ReasoningSummaryTextDeltaNotification","CodexSchema.V2ReasoningSummaryPartAddedNotification","CodexSchema.V2ReasoningTextDeltaNotification","CodexSchema.V2ContextCompactedNotification","CodexSchema.V2ModelReroutedNotification","CodexSchema.V2ModelVerificationNotification","CodexSchema.V2TurnModerationMetadataNotification","CodexSchema.V2ModelSafetyBufferingUpdatedNotification","CodexSchema.V2WarningNotification","CodexSchema.V2GuardianWarningNotification","CodexSchema.V2DeprecationNoticeNotification","CodexSchema.V2ConfigWarningNotification","CodexSchema.FuzzyFileSearchSessionUpdatedNotification","CodexSchema.FuzzyFileSearchSessionCompletedNotification","CodexSchema.V2ThreadRealtimeStartedNotification","CodexSchema.V2ThreadRealtimeItemAddedNotification","CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification","CodexSchema.V2ThreadRealtimeTranscriptDoneNotification","CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification","CodexSchema.V2ThreadRealtimeSdpNotification","CodexSchema.V2ThreadRealtimeErrorNotification","CodexSchema.V2ThreadRealtimeClosedNotification","CodexSchema.V2WindowsWorldWritableWarningNotification","CodexSchema.V2WindowsSandboxSetupCompletedNotification","CodexSchema.V2AccountLoginCompletedNotification","CodexSchema.V1InitializeParams","CodexSchema.V1InitializeResponse","CodexSchema.V2AccountLoginCompletedNotification","CodexSchema.V2AccountRateLimitsUpdatedNotification","CodexSchema.V2AccountUpdatedNotification","CodexSchema.V2AgentMessageDeltaNotification","CodexSchema.V2AppListUpdatedNotification","CodexSchema.V2AppsInstalledParams","CodexSchema.V2AppsInstalledResponse","CodexSchema.V2AppsListParams","CodexSchema.V2AppsListResponse","CodexSchema.V2AppsReadParams","CodexSchema.V2AppsReadResponse","CodexSchema.V2CancelLoginAccountParams","CodexSchema.V2CancelLoginAccountResponse","CodexSchema.V2CommandExecOutputDeltaNotification","CodexSchema.V2CommandExecParams","CodexSchema.V2CommandExecResizeParams","CodexSchema.V2CommandExecResizeResponse","CodexSchema.V2CommandExecResponse","CodexSchema.V2CommandExecTerminateParams","CodexSchema.V2CommandExecTerminateResponse","CodexSchema.V2CommandExecutionOutputDeltaNotification","CodexSchema.V2CommandExecWriteParams","CodexSchema.V2CommandExecWriteResponse","CodexSchema.V2ConfigBatchWriteParams","CodexSchema.V2ConfigReadParams","CodexSchema.V2ConfigReadResponse","CodexSchema.V2ConfigRequirementsReadResponse","CodexSchema.V2ConfigValueWriteParams","CodexSchema.V2ConfigWarningNotification","CodexSchema.V2ConfigWriteResponse","CodexSchema.V2ConsumeAccountRateLimitResetCreditParams","CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse","CodexSchema.V2ContextCompactedNotification","CodexSchema.V2DeprecationNoticeNotification","CodexSchema.V2EnvironmentConnectionNotification","CodexSchema.V2ErrorNotification","CodexSchema.V2ExperimentalFeatureEnablementSetParams","CodexSchema.V2ExperimentalFeatureEnablementSetResponse","CodexSchema.V2ExperimentalFeatureListParams","CodexSchema.V2ExperimentalFeatureListResponse","CodexSchema.V2ExternalAgentConfigDetectParams","CodexSchema.V2ExternalAgentConfigDetectResponse","CodexSchema.V2ExternalAgentConfigImportCompletedNotification","CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse","CodexSchema.V2ExternalAgentConfigImportParams","CodexSchema.V2ExternalAgentConfigImportProgressNotification","CodexSchema.V2ExternalAgentConfigImportResponse","CodexSchema.V2FeedbackUploadParams","CodexSchema.V2FeedbackUploadResponse","CodexSchema.V2FileChangeOutputDeltaNotification","CodexSchema.V2FileChangePatchUpdatedNotification","CodexSchema.V2FsChangedNotification","CodexSchema.V2FsCopyParams","CodexSchema.V2FsCopyResponse","CodexSchema.V2FsCreateDirectoryParams","CodexSchema.V2FsCreateDirectoryResponse","CodexSchema.V2FsGetMetadataParams","CodexSchema.V2FsGetMetadataResponse","CodexSchema.V2FsReadDirectoryParams","CodexSchema.V2FsReadDirectoryResponse","CodexSchema.V2FsReadFileParams","CodexSchema.V2FsReadFileResponse","CodexSchema.V2FsRemoveParams","CodexSchema.V2FsRemoveResponse","CodexSchema.V2FsUnwatchParams","CodexSchema.V2FsUnwatchResponse","CodexSchema.V2FsWatchParams","CodexSchema.V2FsWatchResponse","CodexSchema.V2FsWriteFileParams","CodexSchema.V2FsWriteFileResponse","CodexSchema.V2GetAccountParams","CodexSchema.V2GetAccountRateLimitsResponse","CodexSchema.V2GetAccountResponse","CodexSchema.V2GetAccountTokenUsageResponse","CodexSchema.V2GetWorkspaceMessagesResponse","CodexSchema.V2GuardianWarningNotification","CodexSchema.V2HookCompletedNotification","CodexSchema.V2HooksListParams","CodexSchema.V2HooksListResponse","CodexSchema.V2HookStartedNotification","CodexSchema.V2ItemCompletedNotification","CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification","CodexSchema.V2ItemGuardianApprovalReviewStartedNotification","CodexSchema.V2ItemStartedNotification","CodexSchema.V2ListMcpServerStatusParams","CodexSchema.V2ListMcpServerStatusResponse","CodexSchema.V2LoginAccountParams","CodexSchema.V2LoginAccountResponse","CodexSchema.V2LogoutAccountResponse","CodexSchema.V2MarketplaceAddParams","CodexSchema.V2MarketplaceAddResponse","CodexSchema.V2MarketplaceRemoveParams","CodexSchema.V2MarketplaceRemoveResponse","CodexSchema.V2MarketplaceUpgradeParams","CodexSchema.V2MarketplaceUpgradeResponse","CodexSchema.V2McpResourceReadParams","CodexSchema.V2McpResourceReadResponse","CodexSchema.V2McpServerOauthLoginCompletedNotification","CodexSchema.V2McpServerOauthLoginParams","CodexSchema.V2McpServerOauthLoginResponse","CodexSchema.V2McpServerRefreshResponse","CodexSchema.V2McpServerStatusUpdatedNotification","CodexSchema.V2McpServerToolCallParams","CodexSchema.V2McpServerToolCallResponse","CodexSchema.V2McpToolCallProgressNotification","CodexSchema.V2ModelListParams","CodexSchema.V2ModelListResponse","CodexSchema.V2ModelProviderCapabilitiesReadParams","CodexSchema.V2ModelProviderCapabilitiesReadResponse","CodexSchema.V2ModelReroutedNotification","CodexSchema.V2ModelSafetyBufferingUpdatedNotification","CodexSchema.V2ModelVerificationNotification","CodexSchema.V2PermissionProfileListParams","CodexSchema.V2PermissionProfileListResponse","CodexSchema.V2PlanDeltaNotification","CodexSchema.V2PluginInstalledParams","CodexSchema.V2PluginInstalledResponse","CodexSchema.V2PluginInstallParams","CodexSchema.V2PluginInstallResponse","CodexSchema.V2PluginListParams","CodexSchema.V2PluginListResponse","CodexSchema.V2PluginReadParams","CodexSchema.V2PluginReadResponse","CodexSchema.V2PluginShareCheckoutParams","CodexSchema.V2PluginShareCheckoutResponse","CodexSchema.V2PluginShareDeleteParams","CodexSchema.V2PluginShareDeleteResponse","CodexSchema.V2PluginShareListParams","CodexSchema.V2PluginShareListResponse","CodexSchema.V2PluginShareSaveParams","CodexSchema.V2PluginShareSaveResponse","CodexSchema.V2PluginShareUpdateTargetsParams","CodexSchema.V2PluginShareUpdateTargetsResponse","CodexSchema.V2PluginSkillReadParams","CodexSchema.V2PluginSkillReadResponse","CodexSchema.V2PluginUninstallParams","CodexSchema.V2PluginUninstallResponse","CodexSchema.V2ProcessExitedNotification","CodexSchema.V2ProcessOutputDeltaNotification","CodexSchema.V2RawResponseCompletedNotification","CodexSchema.V2RawResponseItemCompletedNotification","CodexSchema.V2ReasoningSummaryPartAddedNotification","CodexSchema.V2ReasoningSummaryTextDeltaNotification","CodexSchema.V2ReasoningTextDeltaNotification","CodexSchema.V2RemoteControlStatusChangedNotification","CodexSchema.V2ReviewStartParams","CodexSchema.V2ReviewStartResponse","CodexSchema.V2SendAddCreditsNudgeEmailParams","CodexSchema.V2SendAddCreditsNudgeEmailResponse","CodexSchema.V2ServerRequestResolvedNotification","CodexSchema.V2SkillsChangedNotification","CodexSchema.V2SkillsConfigWriteParams","CodexSchema.V2SkillsConfigWriteResponse","CodexSchema.V2SkillsExtraRootsSetParams","CodexSchema.V2SkillsExtraRootsSetResponse","CodexSchema.V2SkillsListParams","CodexSchema.V2SkillsListResponse","CodexSchema.V2TerminalInteractionNotification","CodexSchema.V2ThreadApproveGuardianDeniedActionParams","CodexSchema.V2ThreadApproveGuardianDeniedActionResponse","CodexSchema.V2ThreadArchivedNotification","CodexSchema.V2ThreadArchiveParams","CodexSchema.V2ThreadArchiveResponse","CodexSchema.V2ThreadClosedNotification","CodexSchema.V2ThreadCompactStartParams","CodexSchema.V2ThreadCompactStartResponse","CodexSchema.V2ThreadDeletedNotification","CodexSchema.V2ThreadDeleteParams","CodexSchema.V2ThreadDeleteResponse","CodexSchema.V2ThreadForkParams","CodexSchema.V2ThreadForkResponse","CodexSchema.V2ThreadGoalClearedNotification","CodexSchema.V2ThreadGoalClearParams","CodexSchema.V2ThreadGoalClearResponse","CodexSchema.V2ThreadGoalGetParams","CodexSchema.V2ThreadGoalGetResponse","CodexSchema.V2ThreadGoalSetParams","CodexSchema.V2ThreadGoalSetResponse","CodexSchema.V2ThreadGoalUpdatedNotification","CodexSchema.V2ThreadInjectItemsParams","CodexSchema.V2ThreadInjectItemsResponse","CodexSchema.V2ThreadListParams","CodexSchema.V2ThreadListResponse","CodexSchema.V2ThreadLoadedListParams","CodexSchema.V2ThreadLoadedListResponse","CodexSchema.V2ThreadMetadataUpdateParams","CodexSchema.V2ThreadMetadataUpdateResponse","CodexSchema.V2ThreadNameUpdatedNotification","CodexSchema.V2ThreadReadParams","CodexSchema.V2ThreadReadResponse","CodexSchema.V2ThreadRealtimeClosedNotification","CodexSchema.V2ThreadRealtimeErrorNotification","CodexSchema.V2ThreadRealtimeItemAddedNotification","CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification","CodexSchema.V2ThreadRealtimeSdpNotification","CodexSchema.V2ThreadRealtimeStartedNotification","CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification","CodexSchema.V2ThreadRealtimeTranscriptDoneNotification","CodexSchema.V2ThreadResumeParams","CodexSchema.V2ThreadResumeResponse","CodexSchema.V2ThreadRollbackParams","CodexSchema.V2ThreadRollbackResponse","CodexSchema.V2ThreadSetNameParams","CodexSchema.V2ThreadSetNameResponse","CodexSchema.V2ThreadSettingsUpdatedNotification","CodexSchema.V2ThreadShellCommandParams","CodexSchema.V2ThreadShellCommandResponse","CodexSchema.V2ThreadStartedNotification","CodexSchema.V2ThreadStartParams","CodexSchema.V2ThreadStartResponse","CodexSchema.V2ThreadStatusChangedNotification","CodexSchema.V2ThreadTokenUsageUpdatedNotification","CodexSchema.V2ThreadUnarchivedNotification","CodexSchema.V2ThreadUnarchiveParams","CodexSchema.V2ThreadUnarchiveResponse","CodexSchema.V2ThreadUnsubscribeParams","CodexSchema.V2ThreadUnsubscribeResponse","CodexSchema.V2TurnCompletedNotification","CodexSchema.V2TurnDiffUpdatedNotification","CodexSchema.V2TurnInterruptParams","CodexSchema.V2TurnInterruptResponse","CodexSchema.V2TurnModerationMetadataNotification","CodexSchema.V2TurnPlanUpdatedNotification","CodexSchema.V2TurnStartedNotification","CodexSchema.V2TurnStartParams","CodexSchema.V2TurnStartResponse","CodexSchema.V2TurnSteerParams","CodexSchema.V2TurnSteerResponse","CodexSchema.V2WarningNotification","CodexSchema.V2WindowsSandboxReadinessResponse","CodexSchema.V2WindowsSandboxSetupCompletedNotification","CodexSchema.V2WindowsSandboxSetupStartParams","CodexSchema.V2WindowsSandboxSetupStartResponse","CodexSchema.V2WindowsWorldWritableWarningNotification","JsonRpcId","Schema.Union","Schema.Number","Schema.String","Schema.Struct","Schema.optional","Schema.Unknown","Effect.sync","Effect.fail","Schema.decodeUnknownEffect","Effect.mapError","Schema.encodeEffect","runHandler","Effect.fnUntraced","Schema.is","JsonRpcId","CodexError.CodexAppServerError","Schema.encodeUnknownEffect","Schema.fromJsonString","Schema.Unknown","Schema.decodeUnknownEffect","Effect.map","Effect.mapError","CodexError.CodexAppServerTransportError","Effect.fn","Queue.unbounded","Ref.make","Effect.void","Effect.logDebug","Effect.annotateLogs","Ref.get","Effect.flatMap","Effect.forEach","Deferred.fail","Effect.andThen","Ref.set","Ref.modify","Effect.gen","Queue.end","Effect.flatten","Queue.offer","Effect.asVoid","Ref.update","Deferred.succeed","Effect.matchEffect","Effect.fail","Effect.tap","Effect.tapErrorTag","Stream.decodeText","Stream.runForEach","Effect.succeed","CodexError.CodexAppServerInputStreamEndedError","Effect.forkScoped","Stream.fromQueue","Stream.run","Deferred.make","Effect.tapError","Deferred.await","Effect.onInterrupt","encoder","makeChildStdio","Stdio.make","Effect.succeed","Sink.mapInput","Sink.drain","makeInMemoryStdio","Effect.fn","Queue.unbounded","Stream.fromQueue","Sink.forEach","Queue.offer","makeTerminationError","Effect.match","CodexError.CodexAppServerTransportError","CodexError.CodexAppServerProcessExitedError","Context.Service","make","Effect.fn","CodexRpc.SERVER_REQUEST_PARAMS","CodexRpc.SERVER_REQUEST_RESPONSES","CodexRpc.CLIENT_REQUEST_PARAMS","CodexRpc.CLIENT_REQUEST_RESPONSES","CodexRpc.CLIENT_NOTIFICATION_PARAMS","CodexRpc.SERVER_NOTIFICATION_PARAMS","Effect.flatMap","Effect.forEach","Effect.catch","Effect.void","runHandler","Effect.fail","CodexProtocol.makeCodexAppServerPatchedProtocol","Effect.sync","layerChildProcess","Layer.effect","Stream.runDrain","Effect.ignore","Effect.forkScoped","makeChildStdio","makeTerminationError","Schema.is","CodexErrors.CodexAppServerSpawnError","Effect.fn","packageJson.version","ChildProcessSpawner.ChildProcessSpawner","ChildProcess.make","Effect.mapError","Layer.build","CodexClient.layerChildProcess","Effect.service","CodexClient.CodexAppServerClient","Effect.provide","Effect.all","Effect.timeoutOption","Duration.millis","Effect.catchCause","Cause.hasInterrupts","Effect.failCause","Effect.succeed","Option.none","Option.getOrUndefined","Effect.gen","Effect.map","DateTime.now","DateTime.formatIso","Effect.scoped","Effect.result","Result.isFailure","Option.isNone","Schema.decodeUnknownEffect","EffectCodexSchema.V2TurnStartResponse","PROVIDER","Schema.Struct","Schema.String","Schema.Array","isCodexResumeCursorSchema","Schema.is","Schema.fieldsAssign","Schema.optionalKey","EffectCodexSchema.V2TurnStartParams__CollaborationMode","Schema.TaggedErrorClass","Effect.mapError","Effect.catchIf","Effect.logWarning","Effect.andThen","Effect.succeed","Effect.fail","Effect.forEach","Effect.map","Effect.gen","DateTime.formatIso","DateTime.now","Ref.update","ChildProcessSpawner.ChildProcessSpawner","Scope.Scope","Crypto.Crypto","Queue.unbounded","Ref.make","ChildProcess.make","Effect.provideService","CodexErrors.CodexAppServerSpawnError","CodexClient.layerChildProcess","Layer.build","Effect.service","CodexClient.CodexAppServerClient","Effect.provide","Effect.cached","CodexErrors.CodexAppServerIdentifierGenerationError","Queue.offer","Effect.asVoid","Ref.get","Effect.flatMap","Deferred.succeed","Effect.ignore","Ref.set","Effect.void","Deferred.make","Deferred.await","Effect.ensuring","CodexRpc.SERVER_NOTIFICATION_METHODS","Stream.fromQueue","Stream.runForEach","Effect.forkIn","Stream.decodeText","Ref.modify","Effect.fn","close","Ref.getAndSet","Effect.catch","Effect.logError","Scope.close","Exit.void","Queue.shutdown","Effect.timeoutOption","Schema.is","CodexErrors.CodexAppServerProcessExitedError","CodexErrors.CodexAppServerTransportError","Schema.Struct","EffectCodexSchema.V2ItemStartedNotification","EffectCodexSchema.V2ItemCompletedNotification","EffectCodexSchema.ServerRequest__ToolRequestUserInputParams","EffectCodexSchema.ToolRequestUserInputParams","EffectCodexSchema.ServerRequest__CommandExecutionRequestApprovalParams","EffectCodexSchema.ServerRequest__FileChangeRequestApprovalParams","EffectCodexSchema.ServerRequest__ApplyPatchApprovalParams","EffectCodexSchema.ServerRequest__ExecCommandApprovalParams","EffectCodexSchema.ServerRequest__DynamicToolCallParams","EffectCodexSchema.V2ThreadStartedNotification","EffectCodexSchema.V2ThreadStatusChangedNotification","EffectCodexSchema.V2ThreadNameUpdatedNotification","EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification","EffectCodexSchema.V2TurnCompletedNotification","EffectCodexSchema.V2TurnPlanUpdatedNotification","EffectCodexSchema.V2TurnDiffUpdatedNotification","EffectCodexSchema.V2PlanDeltaNotification","EffectCodexSchema.V2AgentMessageDeltaNotification","EffectCodexSchema.V2CommandExecutionOutputDeltaNotification","EffectCodexSchema.V2FileChangeOutputDeltaNotification","EffectCodexSchema.V2ReasoningSummaryTextDeltaNotification","EffectCodexSchema.V2ReasoningTextDeltaNotification","EffectCodexSchema.V2McpToolCallProgressNotification","EffectCodexSchema.V2ServerRequestResolvedNotification","EffectCodexSchema.ToolRequestUserInputResponse","EffectCodexSchema.V2ModelReroutedNotification","EffectCodexSchema.V2DeprecationNoticeNotification","EffectCodexSchema.V2ConfigWarningNotification","EffectCodexSchema.V2AccountUpdatedNotification","EffectCodexSchema.V2AccountRateLimitsUpdatedNotification","EffectCodexSchema.V2McpServerOauthLoginCompletedNotification","EffectCodexSchema.V2ThreadRealtimeStartedNotification","EffectCodexSchema.V2ThreadRealtimeItemAddedNotification","EffectCodexSchema.V2ThreadRealtimeTranscriptDeltaNotification","EffectCodexSchema.V2ThreadRealtimeTranscriptDoneNotification","EffectCodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification","EffectCodexSchema.V2ThreadRealtimeErrorNotification","EffectCodexSchema.V2ThreadRealtimeClosedNotification","EffectCodexSchema.V2ErrorNotification","EffectCodexSchema.V2WindowsWorldWritableWarningNotification","EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification","Effect.fn","FileSystem.FileSystem","ChildProcessSpawner.ChildProcessSpawner","Crypto.Crypto","Effect.service","Queue.unbounded","Effect.scoped","Effect.gen","Effect.suspend","Scope.make","Effect.addFinalizer","Effect.void","Scope.close","Exit.void","Effect.provideService","Scope.Scope","Effect.mapError","Stream.runForEach","Effect.logDebug","Queue.offerAll","Effect.forkIn","Effect.onError","Effect.andThen","Effect.ignore","Fiber.interrupt","Effect.forEach","Effect.flatMap","Effect.map","Effect.fail","Effect.fnUntraced","Effect.succeed","Effect.asVoid","Effect.acquireRelease","Queue.shutdown","Stream.fromQueue","Effect.fn","Path.Path","Schema.String","Schema.TaggedErrorClass","Schema.Literals","Schema.optional","Schema.Defect","Schema.Union","Effect.map","Effect.catchTags","Effect.succeed","FileSystem.FileSystem","Effect.all","Effect.forEach","Effect.void","Schema.decodeSync","withInstanceIdentity","Effect.gen","ChildProcessSpawner.ChildProcessSpawner","HttpClient.HttpClient","Effect.mapError","Effect.map","Effect.provideService","Effect.flatMap","Schema.Struct","Schema.optionalKey","Schema.Union","Schema.Record","Schema.String","Schema.Unknown","Schema.Null","Schema.isFinite","Schema.isInt","Schema.Array","Error","Schema.Literal","Schema.Literals","Schema.isGreaterThanOrEqualTo","Schema.isLessThanOrEqualTo","Schema.Literals","Schema.Union","Schema.String","Schema.Number","schemaIssueDiagnostics","Schema.TaggedErrorClass","Schema.optional","Schema.Defect","Schema.optionalKey","Schema.Int","Schema.Array","AcpSchema.ErrorCode","Schema.Unknown","Schema.is","AcpError.AcpError","Schema.decodeUnknownEffect","AcpSchema.SessionNotification","AcpSchema.ElicitationCompleteNotification","RpcSerialization.ndJsonRpc","canonicalStopReasons","Effect.fn","Queue.unbounded","Ref.make","Effect.void","Effect.logDebug","Effect.annotateLogs","Effect.try","Queue.offer","Effect.asVoid","Ref.modify","Effect.flatten","Ref.update","Deferred.fail","Deferred.succeed","Ref.getAndSet","Effect.flatMap","Effect.forEach","Effect.andThen","Effect.catch","RpcClientError.RpcClientError","RpcClientError.RpcClientDefect","Effect.gen","Effect.matchEffect","Effect.map","Effect.mapError","Effect.catchTags","Effect.logWarning","Ref.get","Stream.runForEach","AcpError.AcpProtocolParseError","Effect.tap","Effect.tapErrorTag","AcpError.AcpTransportError","Effect.succeed","AcpError.AcpInputStreamEndedError","Effect.forkScoped","Stream.fromQueue","Stream.run","Effect.forever","Effect.orDie","Queue.end","Effect.succeedNone","Deferred.make","Effect.tapError","Deferred.await","Effect.onInterrupt","Schema.Struct","Schema.optionalKey","Schema.NullOr","Schema.Record","Schema.String","Schema.Unknown","AcpSchema.Usage","Schema.is","AcpSchema.PromptResponse","Schema.Union","Schema.decodeTo","Schema.toType","SchemaTransformation.transform","Rpc.make","AcpSchema.InitializeRequest","AcpSchema.InitializeResponse","AcpSchema.Error","AcpSchema.AuthenticateRequest","AcpSchema.AuthenticateResponse","AcpSchema.LogoutRequest","AcpSchema.LogoutResponse","AcpSchema.NewSessionRequest","AcpSchema.NewSessionResponse","AcpSchema.LoadSessionRequest","AcpSchema.LoadSessionResponse","AcpSchema.ListSessionsRequest","AcpSchema.ListSessionsResponse","AcpSchema.ForkSessionRequest","AcpSchema.ForkSessionResponse","AcpSchema.ResumeSessionRequest","AcpSchema.ResumeSessionResponse","AcpSchema.CloseSessionRequest","AcpSchema.CloseSessionResponse","AcpSchema.PromptRequest","AcpSchema.SetSessionModelRequest","AcpSchema.SetSessionModelResponse","AcpSchema.SetSessionConfigOptionRequest","AcpSchema.SetSessionConfigOptionResponse","AcpSchema.ReadTextFileRequest","AcpSchema.ReadTextFileResponse","AcpSchema.WriteTextFileRequest","AcpSchema.WriteTextFileResponse","AcpSchema.RequestPermissionRequest","AcpSchema.RequestPermissionResponse","AcpSchema.ElicitationRequest","AcpSchema.ElicitationResponse","AcpSchema.CreateTerminalRequest","AcpSchema.CreateTerminalResponse","AcpSchema.TerminalOutputRequest","AcpSchema.TerminalOutputResponse","AcpSchema.ReleaseTerminalRequest","AcpSchema.ReleaseTerminalResponse","AcpSchema.WaitForTerminalExitRequest","AcpSchema.WaitForTerminalExitResponse","AcpSchema.KillTerminalRequest","AcpSchema.KillTerminalResponse","RpcGroup.make","Schema.is","AcpSchema.Error","Effect.catchDefect","Schema.isSchemaError","Effect.fail","Effect.die","Effect.catchIf","Effect.catchTags","AcpError.AcpTransportError","Effect.fnUntraced","Effect.mapError","Schema.decodeUnknownEffect","Effect.flatMap","encoder","Schema.Union","Schema.Number","Schema.String","Schema.Array","Schema.Unknown","Stdio.make","Effect.succeed","Sink.mapInput","Sink.drain","Effect.fn","Queue.unbounded","Stream.fromQueue","Sink.forEach","Queue.offer","Effect.match","AcpError.AcpTransportError","AcpError.AcpProcessExitedError","Context.Service","make","Effect.fn","Effect.forEach","Effect.catch","Effect.void","Effect.suspend","Effect.fail","AcpProtocol.makeAcpPatchedProtocol","Effect.map","RpcServer.make","AcpRpcs.ClientRpcs","Effect.provideService","RpcServer.Protocol","Effect.provide","Effect.forkScoped","RpcClient.make","AcpRpcs.AgentRpcs","RpcMessage.RequestId","RpcClient.Protocol","Layer.effect","Effect.gen","Crypto.Crypto","FileSystem.FileSystem","Path.Path","ChildProcessSpawner.ChildProcessSpawner","Scope.Scope","Effect.mapError","Effect.ignore","ChildProcess.make","Effect.provideService","Deferred.make","Stream.runForEach","Effect.sync","Effect.forkIn","Effect.match","Effect.flatMap","Deferred.succeed","Effect.fail","Effect.succeed","Deferred.await","asRecord","normalizeCommandValue","extractCommandFromTitle","isRecord","canonicalItemTypeFromAcpToolKind","Effect.gen","Duration.millis","Ref.get","Option.isSome","Duration.toMillis","Clock.currentTimeMillis","Effect.sleep","Duration.seconds","Context.Service","make","Effect.gen","Crypto.Crypto","ChildProcessSpawner.ChildProcessSpawner","Scope.Scope","Queue.unbounded","Ref.make","Effect.mapError","EffectAcpErrors.AcpTransportError","Semaphore.make","Option.none","Effect.void","Effect.flatMap","Effect.tap","Effect.onError","ChildProcess.make","Effect.provideService","EffectAcpErrors.AcpSpawnError","Stream.runForEach","Effect.catch","Effect.forkIn","Effect.matchEffect","Layer.build","EffectAcpClient.layerChildProcess","Effect.service","EffectAcpClient.AcpClient","Effect.provide","Ref.get","Option.isSome","Clock.currentTimeMillis","Ref.set","Option.some","EffectAcpErrors.AcpRequestError","Ref.update","Effect.succeed","Duration.fromInputUnsafe","Effect.raceFirst","Fiber.join","Effect.ensuring","Fiber.interrupt","Effect.ignore","Effect.timeoutOption","Option.match","Effect.fail","Deferred.make","Ref.modify","Deferred.await","Effect.andThen","Deferred.succeed","Deferred.failCause","Stream.fromQueue","Queue.offer","Effect.catchCause","Cause.hasInterruptsOnly","Effect.failCause","Effect.as","Effect.asVoid","layer","Layer.effect","Effect.gen","Layer.build","AcpSessionRuntime.layer","Layer.provide","Layer.succeed","ChildProcessSpawner.ChildProcessSpawner","Effect.service","AcpSessionRuntime.AcpSessionRuntime","Effect.provide","Effect.succeed","Effect.mapError","Effect.as","Schema.is","Effect.gen","Crypto.Crypto","ChildProcessSpawner.ChildProcessSpawner","FileSystem.FileSystem","Path.Path","Ref.make","Effect.provideService","Effect.void","Ref.update","Effect.timeoutOption","Effect.flatMap","Option.match","Effect.fail","Effect.succeed","Effect.mapError","Ref.get","Schema.decodeEffect","Schema.fromJsonString","Effect.catchTags","Effect.scoped","Effect.fn","Schema.is","EffectAcpErrors.AcpProcessExitedError","EffectAcpErrors.AcpRequestError","Schema.isSchemaError","Effect.fn","Crypto.Crypto","Effect.gen","DateTime.formatIso","DateTime.now","Effect.catchCause","Cause.hasInterrupts","Effect.interrupt","Effect.logWarning","Schema.encodeUnknownExit","Schema.fromJsonString","Schema.Unknown","Exit.isSuccess","Effect.forEach","Deferred.succeed","Effect.ignore","Effect.gen","FileSystem.FileSystem","Path.Path","ChildProcessSpawner.ChildProcessSpawner","Effect.service","Crypto.Crypto","SynchronizedRef.make","PubSub.unbounded","Effect.map","DateTime.now","DateTime.formatIso","Effect.mapError","Effect.all","EffectAcpErrors.AcpTransportError","PubSub.publish","Effect.asVoid","SynchronizedRef.modifyEffect","Option.fromNullishOr","Option.match","Semaphore.make","Effect.succeed","Effect.flatMap","Effect.catchCause","Effect.logWarning","Effect.fail","Fiber.interrupt","Scope.close","Exit.void","Scope.make","Effect.addFinalizer","Effect.void","Effect.provideService","Scope.Scope","Deferred.make","Deferred.await","Stream.runDrain","Stream.mapEffect","Effect.catch","Effect.logError","Effect.forkChild","Effect.scoped","Effect.yieldNow","Effect.tapCause","Ref.make","Effect.tap","Ref.set","Effect.tapError","Effect.andThen","Effect.ensuring","Ref.get","Effect.sync","PubSub.shutdown","Stream.fromPubSub","Effect.gen","Effect.map","DateTime.now","DateTime.formatIso","ChildProcessSpawner.ChildProcessSpawner","Effect.scoped","ChildProcess.make","Effect.timeoutOption","Effect.result","Result.isFailure","Effect.logWarning","Option.isNone","Effect.exit","Exit.isFailure","Effect.provideService","HttpClient.HttpClient","Effect.flatMap","Effect.catchCause","Effect.asVoid","Effect.gen","Crypto.Crypto","FileSystem.FileSystem","Path.Path","ChildProcessSpawner.ChildProcessSpawner","HttpClient.HttpClient","Effect.map","Effect.provideService","Effect.mapError","Schema.decodeSync","Schema.decodeSync","Schema.decodeSync","Schema.decodeSync","Context.Service","Effect.map","DateTime.now","DateTime.formatIso","Effect.gen","Equal.equals","Effect.gen","Schema.decodeUnknownEffect","Effect.result","Effect.logError","Scope.make","Scope.addFinalizer","Scope.close","Exit.void","Effect.ignore","Effect.provideService","Scope.Scope","Ref.get","Ref.set","PubSub.publish","Effect.context","Ref.make","PubSub.unbounded","Effect.addFinalizer","PubSub.shutdown","Effect.provideContext","Effect.map","Stream.fromPubSub","PubSub.subscribe","Layer.effectContext","Context.make","Context.add","Layer.effectDiscard","Effect.gen","Stream.runForEach","Effect.catchCause","Effect.logError","Effect.forkScoped","Layer.unwrap","Effect.orElseSucceed","Layer.provideMerge","Context.Service","Context.Service","Effect.gen","Effect.fn","Layer.effect","Schema.Struct","Schema.Literal","Schema.Literals","Schema.Union","Context.Service","Effect.succeed","Effect.void","Stream.empty","Effect.gen","PubSub.unbounded","PubSub.publish","Effect.asVoid","Stream.fromPubSub","Layer.effect","Duration.minutes","make","Effect.gen","Crypto.Crypto","Effect.succeed","Effect.map","SynchronizedRef.make","SynchronizedRef.modifyEffect","Semaphore.make","Effect.flatMap","Cache.make","Effect.die","Cache.set","Cache.getOption","Option.filter","Option.getOrUndefined","Effect.fn","Option.match","Effect.void","Cache.invalidate","Option.getOrElse","Option.flatMap","Option.some","Option.none","Option.isSome","Effect.as","Effect.forEach","Effect.tap","Effect.sync","Effect.asVoid","Option.isNone","Cache.keys","Effect.catchCause","Effect.logWarning","Cause.pretty","Effect.tapError","DateTime.formatIso","DateTime.now","Effect.mapError","Cause.hasInterruptsOnly","Effect.failCause","Stream.runForEach","Layer.effect","Layer.provide","Schema.is","Duration.minutes","Cause.isFailReason","Cause.pretty","make","Effect.gen","Crypto.Crypto","Effect.map","Cache.make","Effect.succeed","Cache.getOption","Effect.flatMap","Cache.set","Effect.as","Option.isSome","Effect.all","Effect.fnUntraced","Option.getOrUndefined","Effect.fn","Effect.die","Effect.mapError","Equal.equals","Effect.logInfo","Effect.catchCause","Effect.logWarning","Effect.forEach","Cause.hasInterruptsOnly","Effect.interrupt","Effect.failCause","Effect.andThen","Effect.forkScoped","Effect.void","Effect.asVoid","Option.some","Option.none","Option.isNone","Effect.annotateCurrentSpan","Stream.runForEach","Layer.effect","Effect.catchCause","Cause.hasInterruptsOnly","Effect.failCause","Effect.logDebug","Cause.pretty","make","Effect.gen","Effect.fn","Effect.logWarning","Stream.runForEach","Effect.void","Layer.effect","Schema.decodeUnknownEffect","Schema.fromJsonString","ServerProviderSchema","mergeProviderModels","Effect.fn","Path.Path","Effect.gen","FileSystem.FileSystem","Effect.orElseSucceed","Effect.matchCauseEffect","Effect.logWarning","Effect.as","Effect.succeed","Effect.forEach","Effect.flatMap","Equal.equals","Effect.die","Effect.succeed","Layer.effect","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.acquireRelease","PubSub.unbounded","PubSub.shutdown","Effect.provideService","Effect.as","Effect.logWarning","Effect.map","Ref.make","Semaphore.make","Ref.get","Effect.tapError","Effect.logError","Effect.ignore","Effect.fn","Ref.modify","PubSub.publish","Ref.update","Effect.andThen","Stream.runForEach","Effect.forkScoped","Effect.yieldNow","Effect.ignoreCause","Ref.set","Effect.catchCause","Cause.hasInterruptsOnly","Effect.interrupt","Cause.pretty","Stream.fromSubscription","Stream.fromPubSub","Schema.TaggedErrorClass","Schema.String","Schema.Defect","Effect.gen","Path.Path","FileSystem.FileSystem","Effect.orElseSucceed","Effect.fn","Effect.tryPromise","Effect.orDie","Effect.cached","Effect.provideService","Effect.try","PtyAdapter.PtySpawnError","Layer.effect","PtyAdapter.PtyAdapter","Layer.effect","Headers.CurrentRedactedNames","Effect.map","Effect.gen","Layer.succeed","References.MinimumLogLevel","Logger.layer","Logger.consolePretty","Logger.tracerLogger","Layer.mergeAll","Layer.unwrap","OtlpSerialization.layerJson","Layer.unwrap","Effect.gen","ServerConfig.ServerConfig","ResourceAttribution.ResourceAttribution","Layer.mergeAll","Layer.succeed","Tracer.MinimumTraceLevel","References.TracerTimingEnabled","OtlpTracer.make","Tracer.Tracer","BrowserTraceCollector.layer","Layer.provide","OtlpExporter.layerFlusher","Layer.provideMerge","Layer.empty","OtlpMetrics.layer","HttpApiBuilder.group","Effect.fail","HttpApiBuilder.group","Effect.fnUntraced","Effect.fn","Effect.catch","Option.isNone","Layer.provideMerge","ResourceAttribution.layer","Layer.provide","ServerSecretStore.layer","Layer.unwrap","Effect.gen","ServerConfig.ServerConfig","Effect.promise","Effect.all","ProviderSessionRuntime.layer","SqlitePersistenceLayerLive","WorkspacePaths.layer","Layer.mergeAll","NodePtyAdapter.layer","T3ProjectFileLoader.layer","Keybindings.layer","TextGeneration.layer","ProviderEventLoggers.layer","GitWorkspace.layer","RepositoryIdentityResolver.layer","ServerEnvironment.layer","AnalyticsService.layer","ExternalLauncher.layer","ServerLifecycleEvents.layer","NetService.layer","HttpRouter.middleware","Effect.flatMap","ServerRuntimeStartup.ServerRuntimeStartup","Effect.orDie","Effect.andThen","HttpApiBuilder.layer","Deferred.make","Deferred.await","Layer.succeed","Layer.effectDiscard","HttpServer.HttpServer","Effect.acquireRelease","Deferred.succeed","Effect.catchCause","Effect.logWarning","Effect.as","Effect.tap","Effect.logInfo","Effect.catch","Effect.void","Layer.empty","ServerRuntimeStartup.layerWithOptions","Effect.asVoid","Deferred.die","HttpRouter.serve","Layer.tap","HubTunnel.layer","AgentAwarenessHub.layer","FetchHttpClient.layer","Layer.launch","Effect.gen","GlobalFlag.LogLevel","Effect.try","Effect.provideService","Effect.ensuring","Effect.sync","Command.make","Command.withDescription","Command.withHandler","Layer.mergeAll","NodeServices.layer","NetService.layer","Command.make","Command.withDescription","Command.withHandler","Command.withSubcommands","Command.run","packageJson.version","Effect.scoped","Effect.provide"],"sources":["../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Runtime.js","../../../node_modules/.pnpm/@effect+platform-node-shared@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patc_c414c3b6e1e822e230993f828f7aeb31/node_modules/@effect/platform-node-shared/dist/NodeRuntime.js","../../../node_modules/.pnpm/@effect+platform-node@4.0.0-beta.103_bufferutil@4.1.0_effect@4.0.0-beta.103_patch_hash=_7eec308fcf6351488fccaf9a0edac255/node_modules/@effect/platform-node/dist/NodeRuntime.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/CliError.js","../../../node_modules/.pnpm/ini@7.0.0/node_modules/ini/lib/ini.js","../../../node_modules/.pnpm/toml@4.3.0/node_modules/toml/lib/parser.js","../../../node_modules/.pnpm/toml@4.3.0/node_modules/toml/lib/compiler.js","../../../node_modules/.pnpm/toml@4.3.0/node_modules/toml/index.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Primitive.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/ansi.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Prompt.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Param.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Argument.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Console.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/CliOutput.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/completions/bash.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/completions/fish.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/completions/zsh.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Completions.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Flag.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/config.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/command.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/completions/descriptor.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/help.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/GlobalFlag.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/CliConfig.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/lexer.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/auto-suggest.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/parser.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/internal/wizard.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/cli/Command.js","../../t3-shared/src/Net.ts","../package.json","../../t3-contracts/src/baseSchemas.ts","../../t3-contracts/src/providerInstance.ts","../../t3-contracts/src/background.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiSchema.js","../../t3-contracts/src/auth.ts","../../t3-contracts/src/environment.ts","../../../node_modules/.pnpm/find-my-way-ts@0.1.6/node_modules/find-my-way-ts/dist/esm/QueryString.js","../../../node_modules/.pnpm/find-my-way-ts@0.1.6/node_modules/find-my-way-ts/dist/esm/internal/router.js","../../../node_modules/.pnpm/find-my-way-ts@0.1.6/node_modules/find-my-way-ts/dist/esm/index.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/http/HttpRouter.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/internal/mediaType.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiEndpoint.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApi.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiGroup.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiError.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiMiddleware.js","../../t3-contracts/src/model.ts","../../t3-contracts/src/orchestration.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiSecurity.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/OpenApi.js","../../t3-contracts/src/relay.ts","../../t3-contracts/src/environmentHttp.ts","../../t3-contracts/src/relayClient.ts","../../t3-contracts/src/desktopBootstrap.ts","../../t3-contracts/src/remoteAccess.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/ChannelSchema.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/PrimaryKey.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/LayerMap.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/Logger.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/SynchronizedRef.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/TxRef.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/TxChunk.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/TxQueue.js","../../t3-contracts/src/preview.ts","../../t3-contracts/src/previewAutomation.ts","../../t3-contracts/src/ipc.ts","../../t3-contracts/src/terminal.ts","../../t3-contracts/src/provider.ts","../../t3-contracts/src/providerRuntime.ts","../../t3-contracts/src/keybindings.ts","../../t3-contracts/src/editor.ts","../../t3-contracts/src/settings.ts","../../t3-contracts/src/server.ts","../../t3-contracts/src/vcs.ts","../../t3-contracts/src/sourceControl.ts","../../t3-contracts/src/git.ts","../../t3-contracts/src/t3ProjectFile.ts","../../t3-contracts/src/project.ts","../../t3-contracts/src/filesystem.ts","../../t3-contracts/src/assets.ts","../../t3-contracts/src/review.ts","../../t3-contracts/src/portProxy.ts","../../t3-contracts/src/resourceTelemetry.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcSchema.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/Rpc.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcGroup.js","../../t3-contracts/src/rpc.ts","../../t3-shared/src/oauthScope.ts","../src/config.ts","../src/auth/utils.ts","../src/auth/EnvironmentAuthPolicy.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/sql/SqlSchema.js","../src/persistence/Errors.ts","../src/persistence/AuthPairingLinks.ts","../src/auth/PairingGrantStore.ts","../src/auth/ServerSecretStore.ts","../src/persistence/AuthSessions.ts","../src/auth/SessionStore.ts","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/modular.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/curve.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/_shortw_utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/nist.js","../../t3-shared/src/dpopCommon.ts","../../t3-shared/src/relaySigning.ts","../../t3-shared/src/dpop.ts","../src/auth/dpop.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/sql/Migrator.js","../src/persistence/Migrations/001_OrchestrationEvents.ts","../src/persistence/Migrations/002_OrchestrationCommandReceipts.ts","../src/persistence/Migrations/003_CheckpointDiffBlobs.ts","../src/persistence/Migrations/004_ProviderSessionRuntime.ts","../src/persistence/Migrations/005_Projections.ts","../src/persistence/Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts","../src/persistence/Migrations/007_ProjectionThreadMessageAttachments.ts","../src/persistence/Migrations/008_ProjectionThreadActivitySequence.ts","../src/persistence/Migrations/009_ProviderSessionRuntimeMode.ts","../src/persistence/Migrations/010_ProjectionThreadsRuntimeMode.ts","../src/persistence/Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts","../src/persistence/Migrations/012_ProjectionThreadsInteractionMode.ts","../src/persistence/Migrations/013_ProjectionThreadProposedPlans.ts","../src/persistence/Migrations/014_ProjectionThreadProposedPlanImplementation.ts","../src/persistence/Migrations/015_ProjectionTurnsSourceProposedPlan.ts","../src/persistence/Migrations/016_CanonicalizeModelSelections.ts","../src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts","../src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts","../src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts","../src/persistence/Migrations/020_AuthAccessManagement.ts","../src/persistence/Migrations/021_AuthSessionClientMetadata.ts","../src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts","../src/persistence/Migrations/023_ProjectionThreadShellSummary.ts","../src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.ts","../src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.ts","../src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.ts","../src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts","../src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts","../src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.ts","../src/persistence/Migrations/030_ProjectionThreadShellArchiveIndexes.ts","../src/persistence/Migrations/031_AuthAuthorizationScopes.ts","../src/persistence/Migrations/032_AuthPairingProofKeyThumbprint.ts","../src/persistence/Migrations/033_ProjectionThreadsSettled.ts","../src/persistence/Migrations/034_ProjectionThreadsSnoozed.ts","../src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.ts","../src/persistence/Migrations/036_ProjectionThreadsPinned.ts","../src/persistence/Migrations.ts","../src/persistence/Layers/Sqlite.ts","../src/auth/EnvironmentAuth.ts","../src/cliAuthFormat.ts","../../t3-shared/src/Struct.ts","../../t3-shared/src/schemaJson.ts","../../t3-shared/src/model.ts","../../t3-shared/src/backgroundActivitySettings.ts","../../t3-shared/src/serverSettings.ts","../../t3-shared/src/hostProcess.ts","../src/bootstrap.ts","../../t3-shared/src/shell.ts","../src/os-jank.ts","../src/cli/config.ts","../src/cli/auth.ts","../../t3-shared/src/devHome.ts","../../t3-tailscale/src/tailscale.ts","../src/atomicWrite.ts","../../t3-shared/src/qrCode.ts","../src/startupAccess.ts","../src/serverRuntimeState.ts","../src/cli/pair.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/encoding/Sse.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiClient.js","../src/orchestration/Services/OrchestrationEngine.ts","../src/orchestration/Services/ProjectionSnapshotQuery.ts","../src/persistence/Services/OrchestrationCommandReceipts.ts","../src/persistence/Layers/OrchestrationCommandReceipts.ts","../src/persistence/Services/OrchestrationEventStore.ts","../src/persistence/Layers/OrchestrationEventStore.ts","../src/observability/Attributes.ts","../src/observability/Metrics.ts","../src/orchestration/Errors.ts","../../t3-shared/src/path.ts","../src/orchestration/commandInvariants.ts","../src/orchestration/Schemas.ts","../src/orchestration/projector.ts","../src/orchestration/decider.ts","../src/orchestration/Services/ProjectionPipeline.ts","../src/orchestration/Layers/OrchestrationEngine.ts","../src/persistence/Services/ProjectionPendingApprovals.ts","../src/persistence/Services/ProjectionProjects.ts","../src/persistence/Services/ProjectionState.ts","../src/persistence/Services/ProjectionThreadActivities.ts","../src/persistence/Services/ProjectionThreadMessages.ts","../src/persistence/Services/ProjectionThreadProposedPlans.ts","../src/persistence/Services/ProjectionThreadSessions.ts","../src/persistence/Services/ProjectionTurns.ts","../src/persistence/Services/ProjectionThreads.ts","../src/persistence/Layers/ProjectionPendingApprovals.ts","../src/persistence/Layers/ProjectionProjects.ts","../src/persistence/Layers/ProjectionState.ts","../src/persistence/Layers/ProjectionThreadActivities.ts","../src/persistence/Layers/ProjectionThreadMessages.ts","../src/persistence/Layers/ProjectionThreadProposedPlans.ts","../src/persistence/Layers/ProjectionThreadSessions.ts","../src/persistence/Layers/ProjectionTurns.ts","../src/persistence/Layers/ProjectionThreads.ts","../src/attachmentPaths.ts","../src/imageMime.ts","../src/attachmentStore.ts","../src/orchestration/Layers/ProjectionPipeline.ts","../src/persistence/Services/ProjectionCheckpoints.ts","../src/orchestration/ThreadBackgroundLiveness.ts","../../t3-shared/src/sourceControl.ts","../../t3-shared/src/git.ts","../src/stream/collectUint8StreamText.ts","../src/processRunner.ts","../src/project/RepositoryIdentityResolver.ts","../src/orchestration/Layers/ProjectionSnapshotQuery.ts","../src/orchestration/runtimeLayer.ts","../../t3-shared/src/keybindings.ts","../src/keybindings.ts","../src/process/externalLauncher.ts","../src/orchestration/Services/OrchestrationReactor.ts","../src/serverLifecycleEvents.ts","../src/serverSettings.ts","../src/telemetry/Identify.ts","../src/telemetry/AnalyticsService.ts","../src/environment/ServerEnvironmentLabel.ts","../src/environment/ServerEnvironment.ts","../src/provider/Services/ProviderSessionReaper.ts","../src/serverActivation.ts","../src/serverRuntimeStartup.ts","../src/workspace/WorkspacePaths.ts","../src/cli/project.ts","../src/daemonLock.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/httpapi/HttpApiBuilder.js","../src/utils/subscribeBeforeSnapshot.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/encoding/Ndjson.js","../src/resourceTelemetry/DesktopTelemetryReceiver.ts","../src/background/HostPowerMonitor.ts","../src/background/BackgroundPolicy.ts","../src/resourceTelemetry/ResourceAttribution.ts","../../t3-shared/src/devProxy.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/observability/OtlpExporter.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/observability/OtlpResource.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/observability/OtlpSerialization.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/observability/OtlpMetrics.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/observability/OtlpTracer.js","../../t3-shared/src/logging.ts","../../t3-shared/src/observability.ts","../../t3-shared/src/filePreview.ts","../../t3-shared/src/projectFavicon.ts","../../t3-shared/src/t3ProjectFile.ts","../src/project/T3ProjectFileLoader.ts","../src/project/ProjectFaviconResolver.ts","../src/assets/AssetAccess.ts","../src/observability/BrowserTraceCollector.ts","../src/auth/http.ts","../src/httpCors.ts","../src/http.ts","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/workers/Transferable.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/workers/WorkerError.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcClientError.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcMessage.js","../../../node_modules/.pnpm/msgpackr@2.0.5/node_modules/msgpackr/unpack.js","../../../node_modules/.pnpm/msgpackr@2.0.5/node_modules/msgpackr/pack.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/filesystem.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/elf.js","../../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/detect-libc.js","../../../node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/node-gyp-build.js","../../../node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js","../../../node_modules/.pnpm/msgpackr-extract@3.0.4/node_modules/msgpackr-extract/index.js","../../../node_modules/.pnpm/msgpackr@2.0.5/node_modules/msgpackr/node-index.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcSerialization.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/Utils.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcClient.js","../../../node_modules/.pnpm/effect@4.0.0-beta.103_patch_hash=a18f963109656ddbeb2a99ca45f942ecf54830986259eb01ce6a970421c9c6a9/node_modules/effect/dist/unstable/rpc/RpcServer.js","../src/provider/Services/ProviderRegistry.ts","../src/provider/providerMaintenanceCommandCoordinator.ts","../../t3-shared/src/semver.ts","../src/provider/providerMaintenance.ts","../src/provider/providerMaintenanceRunner.ts","../src/orchestration/ActivityPayloadProjection.ts","../src/orchestration/Normalizer.ts","../src/orchestration/Services/ProviderRuntimeIngestion.ts","../src/observability/RpcInstrumentation.ts","../src/provider/Services/ProviderAdapterRegistry.ts","../src/provider/Services/ProviderSessionDirectory.ts","../src/provider/Services/ProviderService.ts","../src/portProxy.ts","../../t3-shared/src/searchRanking.ts","../src/workspace/WorkspaceSearchIndex.ts","../src/workspace/WorkspaceEntries.ts","../src/workspace/WorkspaceFileSystem.ts","../src/workspace/GitWorkspace.ts","../src/terminal/PtyAdapter.ts","../src/terminal/Manager.ts","../src/auth/RpcAuthorization.ts","../src/ws.ts","../src/tunnel/e2e.ts","../src/tunnel/bridge.ts","../../t3-shared/src/agentAwareness.ts","../../t3-shared/src/DrainableWorker.ts","../src/tunnel/AgentAwarenessHub.ts","../src/persistence/ProviderSessionRuntime.ts","../src/provider/Errors.ts","../src/provider/Layers/ProviderSessionDirectory.ts","../src/provider/Services/ProviderInstanceRegistry.ts","../src/provider/Layers/ProviderAdapterRegistry.ts","../src/provider/Layers/EventNdjsonLogger.ts","../src/provider/Layers/ProviderEventLoggers.ts","../src/provider/Layers/ProviderService.ts","../src/provider/Layers/ProviderSessionReaper.ts","../src/textGeneration/TextGeneration.ts","../src/textGeneration/TextGenerationUtils.ts","../src/textGeneration/TextGenerationPrompts.ts","../src/provider/providerSnapshot.ts","../src/provider/Drivers/ClaudeExecutable.ts","../src/pathExpansion.ts","../src/provider/Drivers/ClaudeHome.ts","../src/provider/Drivers/ClaudeSkills.ts","../src/provider/providerUsageLimits.ts","../src/provider/Layers/ClaudeProvider.ts","../src/textGeneration/ClaudeTextGeneration.ts","../../t3-shared/src/cliArgs.ts","../src/provider/Layers/ClaudeAdapter.ts","../src/provider/makeManagedServerProvider.ts","../src/provider/ProviderDriver.ts","../src/provider/ProviderInstanceEnvironment.ts","../src/provider/providerUpdateSettings.ts","../src/provider/Drivers/ClaudeDriver.ts","../src/provider/Layers/codexLaunchArgs.ts","../src/codexModelOptions.ts","../src/textGeneration/CodexTextGeneration.ts","../../effect-codex-app-server/src/errors.ts","../../effect-codex-app-server/src/_generated/schema.gen.ts","../../effect-codex-app-server/src/_generated/meta.gen.ts","../../effect-codex-app-server/src/_generated/namespaces.gen.ts","../../effect-codex-app-server/src/_internal/shared.ts","../../effect-codex-app-server/src/protocol.ts","../../effect-codex-app-server/src/_internal/stdio.ts","../../effect-codex-app-server/src/client.ts","../src/provider/Layers/CodexProvider.ts","../src/provider/CodexDeveloperInstructions.ts","../src/provider/Layers/CodexSessionRuntime.ts","../src/provider/Layers/CodexAdapter.ts","../src/provider/Drivers/CodexHomeLayout.ts","../src/provider/Drivers/CodexDriver.ts","../src/provider/acp/GeminiAcpAgent.ts","../../effect-acp/src/_generated/schema.gen.ts","../../effect-acp/src/errors.ts","../../effect-acp/src/_generated/meta.gen.ts","../../effect-acp/src/protocol.ts","../../effect-acp/src/rpc.ts","../../effect-acp/src/_internal/shared.ts","../../effect-acp/src/_internal/stdio.ts","../../effect-acp/src/client.ts","../src/provider/acp/AcpLocalToolHost.ts","../../t3-shared/src/toolActivity.ts","../src/provider/acp/AcpRuntimeModel.ts","../src/provider/acp/AcpSessionRuntime.ts","../src/provider/acp/AcpAgentSupport.ts","../src/textGeneration/AcpAgentTextGeneration.ts","../src/provider/acp/AcpAdapterSupport.ts","../src/provider/acp/AcpCoreRuntimeEvents.ts","../src/provider/acp/AcpNativeLogging.ts","../src/provider/Layers/AcpAgentAdapter.ts","../src/provider/Layers/AcpAgentProvider.ts","../src/provider/Drivers/makeAcpAgentDriver.ts","../src/provider/Drivers/GeminiDriver.ts","../src/provider/acp/JoyCodeAcpAgent.ts","../src/provider/Drivers/JoyCodeDriver.ts","../src/provider/acp/KimiAcpAgent.ts","../src/provider/Drivers/KimiDriver.ts","../src/provider/acp/QwenAcpAgent.ts","../src/provider/Drivers/QwenDriver.ts","../src/provider/builtInDrivers.ts","../src/provider/Services/ProviderInstanceRegistryMutator.ts","../src/provider/unavailableProviderSnapshot.ts","../src/provider/Layers/ProviderInstanceRegistryLive.ts","../src/provider/Layers/ProviderInstanceRegistryHydration.ts","../src/orchestration/Services/ProviderCommandReactor.ts","../src/orchestration/Services/ThreadDeletionReactor.ts","../src/orchestration/Layers/OrchestrationReactor.ts","../src/orchestration/Services/RuntimeReceiptBus.ts","../src/orchestration/Layers/RuntimeReceiptBus.ts","../src/orchestration/Layers/ProviderRuntimeIngestion.ts","../src/threadWorkspaceCwd.ts","../src/orchestration/Layers/ProviderCommandReactor.ts","../src/orchestration/Layers/ThreadDeletionReactor.ts","../src/provider/providerStatusCache.ts","../src/provider/Layers/ProviderRegistry.ts","../src/terminal/NodePtyAdapter.ts","../../t3-shared/src/httpObservability.ts","../src/serverLogger.ts","../src/observability/Layers/Observability.ts","../src/connectHttpStub.ts","../src/orchestration/http.ts","../src/server.ts","../src/cli/server.ts","../src/bin.ts"],"sourcesContent":["/**\n * Helpers for turning an `Effect` program into a host application's main entry\n * point. This module is the low-level layer used by platform adapters to run a\n * main effect, observe its fiber, report unhandled failures, and translate the\n * resulting `Exit` into an application or process exit code. It provides\n * `makeRunMain`, the default teardown behavior, and error markers for custom\n * exit codes and already-reported failures. Application code usually calls the\n * platform-provided runner instead of using this module directly.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport { constVoid, dual } from \"effect/Function\";\n/**\n * The default teardown function that determines exit codes from an Effect exit.\n *\n * **When to use**\n *\n * Use as the standard teardown for main programs with conventional process\n * exit codes and support for {@link errorExitCode}.\n *\n * **Details**\n *\n * This teardown follows these exit-code rules:\n *\n * - `0` for successful completion.\n * - `130` for interruption-only failures.\n * - The squashed error's {@link errorExitCode} value for other failures when\n *   present.\n * - `1` for other failures.\n *\n * **Gotchas**\n *\n * The `130` code is used only when the Cause contains interruptions and no\n * other failure reasons. Mixed causes use the squashed error path instead.\n *\n * **Example** (Referencing default teardown)\n *\n * ```ts import.meta.vitest\n * import { Exit, Runtime } from \"effect\"\n *\n * const exitCodes: Array<number> = []\n * const collectExitCode = (exit: Exit.Exit<any, any>) =>\n *   Runtime.defaultTeardown(exit, (code) => exitCodes.push(code))\n *\n * collectExitCode(Exit.succeed(42))\n * collectExitCode(Exit.fail(\"error\"))\n * collectExitCode(Exit.interrupt(123))\n *\n * exitCodes // => [0, 1, 130]\n * ```\n *\n * @see {@link errorExitCode} for customizing failure exit codes\n *\n * @category running\n * @since 4.0.0\n */\nexport const defaultTeardown = (exit, onExit) => {\n  if (Exit.isSuccess(exit)) return onExit(0);\n  if (Cause.hasInterruptsOnly(exit.cause)) return onExit(130);\n  return onExit(getErrorExitCode(Cause.squash(exit.cause)));\n};\n/**\n * Creates a platform-specific main program runner that handles Effect execution lifecycle.\n *\n * **When to use**\n *\n * Use when building a runtime adapter for a host platform.\n *\n * **Details**\n *\n * The runner executes Effect programs as main entry points. The provided\n * function receives a forked fiber and a teardown callback so it can install\n * platform-specific signal handling, fiber observers, and final exit behavior.\n *\n * Most applications should use a platform-provided runner, such as\n * `NodeRuntime.runMain`, rather than constructing one directly.\n *\n * `disableErrorReporting` disables the automatic log emitted for unreported\n * non-interruption failures. It does not change exit-code calculation or the\n * custom teardown callback.\n *\n * **Gotchas**\n *\n * The setup function is responsible for observing the fiber and eventually\n * invoking teardown. `makeRunMain` also tries to keep the host process alive\n * with a long interval while the main fiber is running; if the host blocks\n * timers, the runner still starts but cannot use that keep-alive fallback.\n *\n * **Example** (Creating platform runners)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Runtime } from \"effect\"\n *\n * const events: Array<string> = []\n * const completed = new Promise<readonly [Exit.Exit<unknown, unknown>, number]>((resolve) => {\n * // Create a simple runner for a hypothetical platform\n *   const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {\n *     // Handle fiber completion\n *     fiber.addObserver((exit) => {\n *       teardown(exit, (code) => resolve([exit, code]))\n *     })\n *   })\n *\n *   // Use the runner\n *   const program = Effect.sync(() => {\n *     events.push(\"Starting program\", \"Program completed\")\n *     return \"success\"\n *   })\n *\n *   runMain(program, {\n *     teardown: (exit, onExit) => {\n *       events.push(\"Custom teardown logic\")\n *       Runtime.defaultTeardown(exit, onExit)\n *     }\n *   })\n * })\n *\n * const result = await completed\n * result // => [Exit.succeed(\"success\"), 0]\n * events // => [\"Starting program\", \"Program completed\", \"Custom teardown logic\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const makeRunMain = f => dual(args => Effect.isEffect(args[0]), (effect, options) => {\n  const fiber = options?.disableErrorReporting === true ? Effect.runFork(effect) : Effect.runFork(Effect.tapCause(effect, cause => {\n    if (Cause.hasInterruptsOnly(cause)) return Effect.void;\n    const isReported = getErrorReported(Cause.squash(cause));\n    return isReported ? Effect.logError(cause) : Effect.void;\n  }));\n  try {\n    const keepAlive = globalThis.setInterval(constVoid, 2_147_483_647);\n    fiber.addObserver(() => {\n      clearInterval(keepAlive);\n    });\n  } catch {}\n  const teardown = options?.teardown ?? defaultTeardown;\n  return f({\n    fiber,\n    teardown\n  });\n});\n/**\n * Allows associating an exit code with an error for determining the process\n * exit code on failure.\n *\n * **When to use**\n *\n * Use when error classes should map failures to a specific process exit code\n * when handled by {@link defaultTeardown}.\n *\n * **Details**\n *\n * Attach this marker as a readonly property on an error object. When the main\n * program fails, {@link defaultTeardown} squashes the Cause and reads the marker\n * from the resulting error value.\n *\n * **Gotchas**\n *\n * The marker is read from the squashed failure value. If a Cause contains\n * multiple failures, the selected squashed error determines the exit code.\n *\n * **Example** (Setting a process exit code)\n *\n * ```ts import.meta.vitest\n * import { Data, Runtime } from \"effect\"\n *\n * class MyError extends Data.TaggedError(\"MyError\") {\n *   readonly [Runtime.errorExitCode] = 42\n * }\n *\n * Runtime.getErrorExitCode(new MyError()) // => 42\n * ```\n *\n * @see {@link errorReported} for controlling automatic error logging\n * @see {@link defaultTeardown} for the default failure exit-code rules that read this marker\n * @see {@link getErrorExitCode} for reading the marker from unknown error values\n *\n * @category symbols\n * @since 4.0.0\n */\nexport const errorExitCode = \"~effect/Runtime/errorExitCode\";\n/**\n * Reads the runtime exit-code marker from an unknown error value.\n *\n * **When to use**\n *\n * Use to read a custom failure exit code from an unknown error value, falling\n * back to the default failure code.\n *\n * **Details**\n *\n * Returns the numeric `[Runtime.errorExitCode]` property when it is present on\n * an object. Otherwise returns `1`, the default failure exit code used by\n * `defaultTeardown`.\n *\n * **Gotchas**\n *\n * Non-object values, missing markers, and non-number marker values all return\n * `1`.\n *\n * @see {@link errorExitCode} for the marker read by this function\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getErrorExitCode = u => {\n  if (typeof u === \"object\" && u !== null && errorExitCode in u) {\n    const code = u[errorExitCode];\n    if (typeof code === \"number\") {\n      return code;\n    }\n  }\n  return 1;\n};\n/**\n * Defines the runtime marker that controls default `runMain` error logging for an error.\n *\n * **When to use**\n *\n * Use when you need error classes reported by application code to avoid being\n * logged again by the default main runner.\n *\n * **Details**\n *\n * Set `[Runtime.errorReported]` to `false` on an error object to suppress the\n * runtime log because the error has already been reported. Omitted or\n * non-boolean values are treated as `true`, so failures are logged by default.\n *\n * **Gotchas**\n *\n * This marker controls only automatic error logging. It does not change the\n * failure Cause or the process exit code.\n * `makeRunMain` reads the marker from `Cause.squash(cause)`, so for causes\n * with multiple failures, the squashed error determines whether default logging\n * is suppressed.\n *\n * **Example** (Suppressing error reporting)\n *\n * ```ts import.meta.vitest\n * import { Data, Runtime } from \"effect\"\n *\n * class MyError extends Data.TaggedError(\"MyError\") {\n *   readonly [Runtime.errorReported] = false\n * }\n *\n * Runtime.getErrorReported(new MyError()) // => false\n * ```\n *\n * @see {@link errorExitCode} for controlling failure exit codes\n * @see {@link getErrorReported} for reading the marker from unknown error values\n *\n * @category symbols\n * @since 4.0.0\n */\nexport const errorReported = \"~effect/Runtime/errorReported\";\n/**\n * Reads the runtime error-reporting marker from an unknown error value.\n *\n * **When to use**\n *\n * Use to read whether an unknown error value should be treated as already\n * reported by the default main runner.\n *\n * **Details**\n *\n * Returns a boolean `[Runtime.errorReported]` property when it is present on an\n * object. Otherwise returns `true`, so failures are logged by default.\n *\n * **Gotchas**\n *\n * Non-object values, missing markers, and non-boolean marker values all return\n * `true`.\n *\n * @see {@link errorReported} for the marker read by this function\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getErrorReported = u => {\n  if (typeof u === \"object\" && u !== null && errorReported in u) {\n    const isReported = u[errorReported];\n    if (typeof isReported === \"boolean\") {\n      return isReported;\n    }\n  }\n  return true;\n};\n//# sourceMappingURL=Runtime.js.map","import * as Runtime from \"effect/Runtime\";\n/**\n * Runs an Effect as the Node process main program, interrupting the fiber on\n * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the\n * process exit code.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runMain = /*#__PURE__*/Runtime.makeRunMain(({\n  fiber,\n  teardown\n}) => {\n  let receivedSignal = false;\n  fiber.addObserver(exit => {\n    process.removeListener(\"SIGINT\", onSigint);\n    process.removeListener(\"SIGTERM\", onSigint);\n    teardown(exit, code => {\n      if (receivedSignal || code !== 0) {\n        process.exit(code);\n      }\n    });\n  });\n  function onSigint() {\n    receivedSignal = true;\n    fiber.interruptUnsafe(fiber.id);\n  }\n  process.on(\"SIGINT\", onSigint);\n  process.on(\"SIGTERM\", onSigint);\n});\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Node.js process runner for Effect programs.\n *\n * This module exports `runMain`, which runs one Effect as the main process\n * fiber in Node.js. It reuses the shared Node runtime runner, including its\n * error reporting, `SIGINT` / `SIGTERM` interruption, and optional teardown\n * behavior.\n *\n * @since 4.0.0\n */\nimport * as NodeRuntime from \"@effect/platform-node-shared/NodeRuntime\";\n/**\n * Helps you run a main effect with built-in error handling, logging, and signal management.\n *\n * **When to use**\n *\n * Use to run a Node.js application's main Effect with structured error\n * handling, log management, interrupt support, or advanced teardown\n * capabilities.\n *\n * **Details**\n *\n * This function launches an Effect as the main entry point, setting exit codes\n * based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally\n * logging errors. By default, it logs errors and uses a \"pretty\" format, but both\n * behaviors can be turned off. You can also provide custom teardown logic to\n * finalize resources or produce different exit codes.\n *\n * The optional configuration object can include:\n * - `disableErrorReporting`: Turn off automatic error logging.\n * - `teardown`: Provide custom finalization logic.\n *\n * @category running\n * @since 4.0.0\n */\nexport const runMain = NodeRuntime.runMain;\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Defines structured errors for the unstable CLI parser and runner.\n *\n * CLI errors describe problems such as unknown or duplicate flags, missing\n * flags or arguments, unexpected positional arguments, invalid values, unknown\n * subcommands, user handler failures, and requests to show command help. This\n * module includes the `CliError` union, the `isCliError` guard, schema-backed\n * error classes with display messages, and the `NonShowHelpErrors` union used\n * when parse or validation errors should be shown with help output.\n *\n * @since 4.0.0\n */\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Runtime from \"../../Runtime.js\";\nimport * as Schema from \"../../Schema.js\";\n/**\n * @category type IDs\n * @since 4.0.0\n */\nconst TypeId = \"~effect/cli/CliError\";\n/**\n * Type guard to check if a value is a CLI error.\n *\n * **Example** (Checking CLI errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const error = new CliError.MissingOption({ option: \"api-key\" })\n * const program = CliError.isCliError(error)\n *   ? Effect.succeed(error.message)\n *   : Effect.fail(\"Unknown error\")\n *\n * await Effect.runPromise(program) // => \"Missing required flag: --api-key\"\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isCliError = u => Predicate.hasProperty(u, TypeId);\n/**\n * Error thrown when an unrecognized option is encountered.\n *\n * **Example** (Creating unrecognized option errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/unstable/cli\"\n *\n * // Creating an unrecognized option error\n * const unrecognizedError = new CliError.UnrecognizedOption({\n *   option: \"--unknown-flag\",\n *   command: [\"deploy\", \"production\"],\n *   suggestions: [\"--verbose\", \"--force\"]\n * })\n *\n * unrecognizedError._tag // => \"UnrecognizedOption\"\n * unrecognizedError.option // => \"--unknown-flag\"\n * unrecognizedError.command // => [\"deploy\", \"production\"]\n *\n * // In CLI parsing context\n * const parseCommand = Effect.gen(function*() {\n *   // If parsing encounters unknown flag\n *   return yield* unrecognizedError\n * })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseCommand))\n * parseError._tag // => \"UnrecognizedOption\"\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class UnrecognizedOption extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/UnrecognizedOption`)(\"UnrecognizedOption\", {\n  option: Schema.String,\n  command: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Schema.String)),\n  suggestions: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n  /**\n   * Marks this value as a CLI parsing error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Formats the unrecognized option with command context and suggestions.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    const suggestionText = this.suggestions.length > 0 ? `\\n\\n  Did you mean this?\\n    ${this.suggestions.join(\"\\n    \")}` : \"\";\n    const baseMessage = this.command ? `Unrecognized flag: ${this.option} in command ${this.command.join(\" \")}` : `Unrecognized flag: ${this.option}`;\n    return baseMessage + suggestionText;\n  }\n}\n/**\n * Error thrown when duplicate option names are detected between parent and child commands.\n *\n * **Example** (Creating duplicate option errors)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const duplicateError = new CliError.DuplicateOption({\n *   option: \"--verbose\",\n *   parentCommand: \"myapp\",\n *   childCommand: \"deploy\"\n * })\n *\n * duplicateError._tag // => \"DuplicateOption\"\n * duplicateError.option // => \"--verbose\"\n * duplicateError.parentCommand // => \"myapp\"\n * duplicateError.childCommand // => \"deploy\"\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class DuplicateOption extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/DuplicateOption`)(\"DuplicateOption\", {\n  option: Schema.String,\n  parentCommand: Schema.String,\n  childCommand: Schema.String\n}) {\n  /**\n   * Marks this value as a CLI configuration error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Explains which parent and child commands define the duplicate option.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return `Duplicate flag name \"${this.option}\" in parent command \"${this.parentCommand}\" and subcommand \"${this.childCommand}\". ` + `Parent will always claim this flag (Mode A semantics). Consider renaming one of them to avoid confusion.`;\n  }\n}\n/**\n * Error thrown when a required option is missing.\n *\n * **Example** (Creating missing option errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const missingOptionError = new CliError.MissingOption({\n *   option: \"api-key\"\n * })\n *\n * const details = [missingOptionError._tag, missingOptionError.option] // => [\"MissingOption\", \"api-key\"]\n *\n * // In validation context\n * const validateRequiredOptions = (options: Record<string, string | undefined>) =>\n *   Effect.gen(function*() {\n *     const apiKey = options[\"api-key\"]\n *     if (!apiKey) {\n *       return yield* missingOptionError\n *     }\n *     return apiKey\n *   })\n *\n * const validationError = await Effect.runPromise(Effect.flip(validateRequiredOptions({})))\n * validationError._tag // => \"MissingOption\"\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MissingOption extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/MissingOption`)(\"MissingOption\", {\n  option: Schema.String\n}) {\n  /**\n   * Marks this value as a missing CLI option error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Formats the missing required flag for display.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return `Missing required flag: --${this.option}`;\n  }\n}\n/**\n * Error thrown when a required positional argument is missing.\n *\n * **Example** (Creating missing argument errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const missingArgError = new CliError.MissingArgument({\n *   argument: \"target\"\n * })\n *\n * const details = [missingArgError._tag, missingArgError.argument] // => [\"MissingArgument\", \"target\"]\n *\n * // In argument parsing\n * const parseArguments = (args: Array<string>) =>\n *   Effect.gen(function*() {\n *     if (args.length === 0) {\n *       return yield* missingArgError\n *     }\n *     return args[0]\n *   })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseArguments([])))\n * parseError._tag // => \"MissingArgument\"\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MissingArgument extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/MissingArgument`)(\"MissingArgument\", {\n  argument: Schema.String\n}) {\n  /**\n   * Marks this value as a missing CLI argument error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Formats the missing required positional argument for display.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return `Missing required argument: ${this.argument}`;\n  }\n}\n/**\n * Error thrown when positional arguments remain after a command has parsed all\n * of its parameters.\n *\n * **Example** (Reporting unexpected arguments)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const error = new CliError.UnexpectedArgument({\n *   arguments: [\"extra.txt\"]\n * })\n *\n * const details = [error._tag, error.arguments] // => [\"UnexpectedArgument\", [\"extra.txt\"]]\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class UnexpectedArgument extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/UnexpectedArgument`)(\"UnexpectedArgument\", {\n  arguments: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n  /**\n   * Marks this value as an unexpected CLI argument error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Formats the unexpected positional arguments for display.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    const label = this.arguments.length === 1 ? \"argument\" : \"arguments\";\n    return `Unexpected positional ${label}: ${this.arguments.map(value => JSON.stringify(value)).join(\", \")}`;\n  }\n}\n/**\n * Error thrown when an option or argument value is invalid.\n *\n * **Example** (Creating invalid value errors)\n *\n * ```ts import.meta.vitest\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const invalidValueError = new CliError.InvalidValue({\n *   option: \"port\",\n *   value: \"abc123\",\n *   expected: \"integer between 1 and 65535\",\n *   kind: \"flag\"\n * })\n *\n * invalidValueError._tag // => \"InvalidValue\"\n * invalidValueError.kind // => \"flag\"\n * invalidValueError.option // => \"port\"\n * invalidValueError.value // => \"abc123\"\n *\n * // For positional arguments\n * const invalidArgError = new CliError.InvalidValue({\n *   option: \"count\",\n *   value: \"abc\",\n *   expected: \"integer\",\n *   kind: \"argument\"\n * })\n *\n * const details = [invalidArgError.kind, invalidArgError.option, invalidArgError.value] // => [\"argument\", \"count\", \"abc\"]\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InvalidValue extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/InvalidValue`)(\"InvalidValue\", {\n  option: Schema.String,\n  value: Schema.String,\n  expected: Schema.String,\n  kind: /*#__PURE__*/Schema.Union([/*#__PURE__*/Schema.Literal(\"flag\"), /*#__PURE__*/Schema.Literal(\"argument\")])\n}) {\n  /**\n   * Marks this value as an invalid CLI value error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Formats the invalid flag or argument value with the expected input.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    const expectation = this.expected.startsWith(\"Expected \") || this.expected.startsWith(\"Expected:\") ? this.expected : `Expected: ${this.expected}`;\n    if (this.kind === \"argument\") {\n      return `Invalid value for argument <${this.option}>: \"${this.value}\". ${expectation}`;\n    }\n    if (this.value.length === 0) {\n      return `Missing value for flag --${this.option}. ${expectation}`;\n    }\n    return `Invalid value for flag --${this.option}: \"${this.value}\". ${expectation}`;\n  }\n}\n/**\n * Error thrown when an unknown subcommand is encountered.\n *\n * **Example** (Creating unknown subcommand errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/unstable/cli\"\n *\n * const unknownSubcommandError = new CliError.UnknownSubcommand({\n *   subcommand: \"deplyo\", // typo\n *   parent: [\"myapp\"],\n *   suggestions: [\"deploy\", \"destroy\"]\n * })\n *\n * unknownSubcommandError._tag // => \"UnknownSubcomand\"\n * unknownSubcommandError.subcommand // => \"deplyo\"\n * unknownSubcommandError.parent // => [\"myapp\"]\n *\n * // In subcommand parsing\n * const parseSubcommand = (subcommand: string) =>\n *   Effect.gen(function*() {\n *     const validCommands = [\"deploy\", \"destroy\", \"status\"]\n *     if (!validCommands.includes(subcommand)) {\n *       return yield* unknownSubcommandError\n *     }\n *     return subcommand\n *   })\n *\n * const parseError = await Effect.runPromise(Effect.flip(parseSubcommand(\"deplyo\")))\n * parseError._tag // => \"UnknownSubcomand\"\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class UnknownSubcommand extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/UnknownSubcommand`)(\"UnknownSubcomand\", {\n  subcommand: Schema.String,\n  parent: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Array(Schema.String)),\n  suggestions: /*#__PURE__*/Schema.Array(Schema.String)\n}) {\n  /**\n   * Marks this value as an unknown CLI subcommand error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  /**\n   * Formats the unknown subcommand with parent command context and suggestions.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    const suggestionText = this.suggestions.length > 0 ? `\\n\\n  Did you mean this?\\n    ${this.suggestions.join(\"\\n    \")}` : \"\";\n    return this.parent ? `Unknown subcommand \"${this.subcommand}\" for \"${this.parent.join(\" \")}\"${suggestionText}` : `Unknown subcommand \"${this.subcommand}\"${suggestionText}`;\n  }\n}\n/**\n * Error wrapper for user handler failures in the CLI error channel.\n *\n * **Example** (Wrapping user errors)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliError } from \"effect/unstable/cli\"\n *\n * // Wrapping user errors\n * const userError = new CliError.UserError({\n *   cause: new Error(\"Database connection failed\")\n * })\n *\n * // In command handler\n * const deployCommand = Effect.gen(function*() {\n *   const result = yield* Effect.try({\n *     try: () => ({ deployed: true }),\n *     catch: (error) => new CliError.UserError({ cause: error })\n *   })\n *   return result\n * })\n *\n * // In error handling\n * const handleError = (error: CliError.CliError): Effect.Effect<number> => {\n *   if (error._tag === \"UserError\") {\n *     return Effect.succeed(1) // Exit code 1\n *   }\n *   return Effect.succeed(0)\n * }\n *\n * await Effect.runPromise(deployCommand) // => { deployed: true }\n * await Effect.runPromise(handleError(userError)) // => 1\n * ```\n *\n * @category errors\n * @since 4.0.0\n */\nexport class UserError extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/UserError`)(\"UserError\", {\n  cause: /*#__PURE__*/Schema.Defect()\n}) {\n  /**\n   * Marks this value as a user handler error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n}\n/**\n * Schema for concrete CLI errors that can be reported together with help output.\n *\n * **Details**\n *\n * This excludes `ShowHelp` itself, allowing parse and validation errors to be\n * stored in `ShowHelp.errors` without nesting another help-control value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const NonShowHelpErrors = /*#__PURE__*/Schema.Union([UnrecognizedOption, DuplicateOption, MissingOption, MissingArgument, UnexpectedArgument, InvalidValue, UnknownSubcommand, UserError]);\n/**\n * Error data requesting CLI help rendering for a command path.\n *\n * **Details**\n *\n * It is used for explicit help requests and for parse or validation failures\n * that should be shown with help text. When `errors` is non-empty, the runtime\n * exit code is `1`; otherwise it is `0`.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class ShowHelp extends /*#__PURE__*/Schema.TaggedErrorClass(`${TypeId}/ShowHelp`)(\"ShowHelp\", {\n  commandPath: /*#__PURE__*/Schema.Array(Schema.String),\n  errors: /*#__PURE__*/Schema.Array(NonShowHelpErrors)\n}) {\n  [TypeId] = TypeId;\n  [Runtime.errorExitCode] = this.errors.length ? 1 : 0;\n  [Runtime.errorReported] = false;\n  get message() {\n    return \"Help requested\";\n  }\n}\n//# sourceMappingURL=CliError.js.map","const { hasOwnProperty } = Object.prototype\n\nconst encode = (obj, opt = {}) => {\n  if (typeof opt === 'string') {\n    opt = { section: opt }\n  }\n  opt.align = opt.align === true\n  opt.newline = opt.newline === true\n  opt.sort = opt.sort === true\n  opt.whitespace = opt.whitespace === true || opt.align === true\n  // The `typeof` check is required because accessing the `process` directly fails on browsers.\n  /* istanbul ignore next */\n  opt.platform = opt.platform || (typeof process !== 'undefined' && process.platform)\n  opt.bracketedArray = opt.bracketedArray !== false\n\n  /* istanbul ignore next */\n  const eol = opt.platform === 'win32' ? '\\r\\n' : '\\n'\n  const separator = opt.whitespace ? ' = ' : '='\n  const children = []\n\n  const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj)\n\n  let padToChars = 0\n  // If aligning on the separator, then padToChars is determined as follows:\n  // 1. Get the keys\n  // 2. Exclude keys pointing to objects unless the value is null or an array\n  // 3. Add `[]` to array keys\n  // 4. Ensure non empty set of keys\n  // 5. Reduce the set to the longest `safe` key\n  // 6. Get the `safe` length\n  if (opt.align) {\n    padToChars = safe(\n      (\n        keys\n          .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object')\n          .map(k => Array.isArray(obj[k]) ? `${k}[]` : k)\n      )\n        .concat([''])\n        .reduce((a, b) => safe(a).length >= safe(b).length ? a : b)\n    ).length\n  }\n\n  let out = ''\n  const arraySuffix = opt.bracketedArray ? '[]' : ''\n\n  for (const k of keys) {\n    const val = obj[k]\n    if (val && Array.isArray(val)) {\n      for (const item of val) {\n        out += safe(`${k}${arraySuffix}`).padEnd(padToChars, ' ') + separator + safe(item) + eol\n      }\n    } else if (val && typeof val === 'object') {\n      children.push(k)\n    } else {\n      out += safe(k).padEnd(padToChars, ' ') + separator + safe(val) + eol\n    }\n  }\n\n  if (opt.section && out.length) {\n    out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out\n  }\n\n  for (const k of children) {\n    const nk = splitSections(k, '.').join('\\\\.')\n    const section = (opt.section ? opt.section + '.' : '') + nk\n    const child = encode(obj[k], {\n      ...opt,\n      section,\n    })\n    if (out.length && child.length) {\n      out += eol\n    }\n\n    out += child\n  }\n\n  return out\n}\n\nfunction splitSections (str, separator) {\n  var lastMatchIndex = 0\n  var lastSeparatorIndex = 0\n  var nextIndex = 0\n  var sections = []\n\n  do {\n    nextIndex = str.indexOf(separator, lastMatchIndex)\n\n    if (nextIndex !== -1) {\n      lastMatchIndex = nextIndex + separator.length\n\n      if (nextIndex > 0 && str[nextIndex - 1] === '\\\\') {\n        continue\n      }\n\n      sections.push(str.slice(lastSeparatorIndex, nextIndex))\n      lastSeparatorIndex = nextIndex + separator.length\n    }\n  } while (nextIndex !== -1)\n\n  sections.push(str.slice(lastSeparatorIndex))\n\n  return sections\n}\n\nconst decode = (str, opt = {}) => {\n  opt.bracketedArray = opt.bracketedArray !== false\n  const out = Object.create(null)\n  let p = out\n  let section = null\n  //          section          |key      = value\n  const re = /^\\[([^\\]]*)\\]\\s*$|^([^=]+)(=(.*))?$/i\n  const lines = str.split(/[\\r\\n]+/g)\n  const duplicates = {}\n\n  for (const line of lines) {\n    if (!line || line.match(/^\\s*[;#]/) || line.match(/^\\s*$/)) {\n      continue\n    }\n    const match = line.match(re)\n    if (!match) {\n      continue\n    }\n    if (match[1] !== undefined) {\n      section = unsafe(match[1])\n      if (section === '__proto__') {\n        // not allowed\n        // keep parsing the section, but don't attach it.\n        p = Object.create(null)\n        continue\n      }\n      p = out[section] = out[section] || Object.create(null)\n      continue\n    }\n    const keyRaw = unsafe(match[2])\n    let isArray\n    if (opt.bracketedArray) {\n      isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'\n    } else {\n      duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1\n      isArray = duplicates[keyRaw] > 1\n    }\n    const key = isArray && keyRaw.endsWith('[]')\n      ? keyRaw.slice(0, -2) : keyRaw\n\n    if (key === '__proto__') {\n      continue\n    }\n    const valueRaw = match[3] ? unsafe(match[4]) : true\n    const value = valueRaw === 'true' ||\n      valueRaw === 'false' ||\n      valueRaw === 'null' ? JSON.parse(valueRaw)\n      : valueRaw\n\n    // Convert keys with '[]' suffix to an array\n    if (isArray) {\n      if (!hasOwnProperty.call(p, key)) {\n        p[key] = []\n      } else if (!Array.isArray(p[key])) {\n        p[key] = [p[key]]\n      }\n    }\n\n    // safeguard against resetting a previously defined\n    // array by accidentally forgetting the brackets\n    if (Array.isArray(p[key])) {\n      p[key].push(value)\n    } else {\n      p[key] = value\n    }\n  }\n\n  // {a:{y:1},\"a.b\":{x:2}} --> {a:{y:1,b:{x:2}}}\n  // use a filter to return the keys that have to be deleted.\n  const remove = []\n  for (const k of Object.keys(out)) {\n    if (!hasOwnProperty.call(out, k) ||\n      typeof out[k] !== 'object' ||\n      Array.isArray(out[k])) {\n      continue\n    }\n\n    // see if the parent section is also an object.\n    // if so, add it to that, and mark this one for deletion\n    const parts = splitSections(k, '.')\n    p = out\n    const l = parts.pop()\n    const nl = l.replace(/\\\\\\./g, '.')\n    for (const part of parts) {\n      if (part === '__proto__') {\n        continue\n      }\n      if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') {\n        p[part] = Object.create(null)\n      }\n      p = p[part]\n    }\n    if (p === out && nl === l) {\n      continue\n    }\n\n    p[nl] = out[k]\n    remove.push(k)\n  }\n  for (const del of remove) {\n    delete out[del]\n  }\n\n  return out\n}\n\nconst isQuoted = val => {\n  return (val.startsWith('\"') && val.endsWith('\"')) ||\n    (val.startsWith(\"'\") && val.endsWith(\"'\"))\n}\n\nconst safe = val => {\n  if (\n    typeof val !== 'string' ||\n    val.match(/[=\\r\\n]/) ||\n    val.match(/^\\[/) ||\n    (val.length > 1 && isQuoted(val)) ||\n    val !== val.trim()\n  ) {\n    return JSON.stringify(val)\n  }\n  return val.split(';').join('\\\\;').split('#').join('\\\\#')\n}\n\nconst unsafe = val => {\n  val = (val || '').trim()\n  if (isQuoted(val)) {\n    // remove the single quotes before calling JSON.parse\n    if (val.charAt(0) === \"'\") {\n      val = val.slice(1, -1)\n    }\n    try {\n      val = JSON.parse(val)\n    } catch {\n      // ignore errors\n    }\n  } else {\n    // walk the val to find the first not-escaped ; character\n    let esc = false\n    let unesc = ''\n    for (let i = 0, l = val.length; i < l; i++) {\n      const c = val.charAt(i)\n      if (esc) {\n        if ('\\\\;#'.indexOf(c) !== -1) {\n          unesc += c\n        } else {\n          unesc += '\\\\' + c\n        }\n\n        esc = false\n      } else if (';#'.indexOf(c) !== -1) {\n        break\n      } else if (c === '\\\\') {\n        esc = true\n      } else {\n        unesc += c\n      }\n    }\n    if (esc) {\n      unesc += '\\\\'\n    }\n\n    return unesc.trim()\n  }\n  return val\n}\n\nmodule.exports = {\n  parse: decode,\n  decode,\n  stringify: encode,\n  encode,\n  safe,\n  unsafe,\n}\n","// @generated by Peggy 5.1.0.\n//\n// https://peggyjs.org/\n\n\"use strict\";\n\nclass peg$SyntaxError extends SyntaxError {\n  constructor(message, expected, found, location) {\n    super(message);\n    this.expected = expected;\n    this.found = found;\n    this.location = location;\n    this.name = \"SyntaxError\";\n  }\n\n  format(sources) {\n    let str = \"Error: \" + this.message;\n    if (this.location) {\n      let src = null;\n      const st = sources.find(s => s.source === this.location.source);\n      if (st) {\n        src = st.text.split(/\\r\\n|\\n|\\r/g);\n      }\n      const s = this.location.start;\n      const offset_s = (this.location.source && (typeof this.location.source.offset === \"function\"))\n        ? this.location.source.offset(s)\n        : s;\n      const loc = this.location.source + \":\" + offset_s.line + \":\" + offset_s.column;\n      if (src) {\n        const e = this.location.end;\n        const filler = \"\".padEnd(offset_s.line.toString().length, \" \");\n        const line = src[s.line - 1];\n        const last = s.line === e.line ? e.column : line.length + 1;\n        const hatLen = (last - s.column) || 1;\n        str += \"\\n --> \" + loc + \"\\n\"\n            + filler + \" |\\n\"\n            + offset_s.line + \" | \" + line + \"\\n\"\n            + filler + \" | \" + \"\".padEnd(s.column - 1, \" \")\n            + \"\".padEnd(hatLen, \"^\");\n      } else {\n        str += \"\\n at \" + loc;\n      }\n    }\n    return str;\n  }\n\n  static buildMessage(expected, found) {\n    function hex(ch) {\n      return ch.codePointAt(0).toString(16).toUpperCase();\n    }\n\n    const nonPrintable = Object.prototype.hasOwnProperty.call(RegExp.prototype, \"unicode\")\n      ? new RegExp(\"[\\\\p{C}\\\\p{Mn}\\\\p{Mc}]\", \"gu\")\n      : null;\n    function unicodeEscape(s) {\n      if (nonPrintable) {\n        return s.replace(nonPrintable,  ch => \"\\\\u{\" + hex(ch) + \"}\");\n      }\n      return s;\n    }\n\n    function literalEscape(s) {\n      return unicodeEscape(s\n        .replace(/\\\\/g, \"\\\\\\\\\")\n        .replace(/\"/g,  \"\\\\\\\"\")\n        .replace(/\\0/g, \"\\\\0\")\n        .replace(/\\t/g, \"\\\\t\")\n        .replace(/\\n/g, \"\\\\n\")\n        .replace(/\\r/g, \"\\\\r\")\n        .replace(/[\\x00-\\x0F]/g,          ch => \"\\\\x0\" + hex(ch))\n        .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, ch => \"\\\\x\"  + hex(ch)));\n    }\n\n    function classEscape(s) {\n      return unicodeEscape(s\n        .replace(/\\\\/g, \"\\\\\\\\\")\n        .replace(/\\]/g, \"\\\\]\")\n        .replace(/\\^/g, \"\\\\^\")\n        .replace(/-/g,  \"\\\\-\")\n        .replace(/\\0/g, \"\\\\0\")\n        .replace(/\\t/g, \"\\\\t\")\n        .replace(/\\n/g, \"\\\\n\")\n        .replace(/\\r/g, \"\\\\r\")\n        .replace(/[\\x00-\\x0F]/g,          ch => \"\\\\x0\" + hex(ch))\n        .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, ch => \"\\\\x\"  + hex(ch)));\n    }\n\n    const DESCRIBE_EXPECTATION_FNS = {\n      literal(expectation) {\n        return \"\\\"\" + literalEscape(expectation.text) + \"\\\"\";\n      },\n\n      class(expectation) {\n        const escapedParts = expectation.parts.map(\n          part => (Array.isArray(part)\n            ? classEscape(part[0]) + \"-\" + classEscape(part[1])\n            : classEscape(part))\n        );\n\n        return \"[\" + (expectation.inverted ? \"^\" : \"\") + escapedParts.join(\"\") + \"]\" + (expectation.unicode ? \"u\" : \"\");\n      },\n\n      any() {\n        return \"any character\";\n      },\n\n      end() {\n        return \"end of input\";\n      },\n\n      other(expectation) {\n        return expectation.description;\n      },\n    };\n\n    function describeExpectation(expectation) {\n      return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);\n    }\n\n    function describeExpected(expected) {\n      const descriptions = expected.map(describeExpectation);\n      descriptions.sort();\n\n      if (descriptions.length > 0) {\n        let j = 1;\n        for (let i = 1; i < descriptions.length; i++) {\n          if (descriptions[i - 1] !== descriptions[i]) {\n            descriptions[j] = descriptions[i];\n            j++;\n          }\n        }\n        descriptions.length = j;\n      }\n\n      switch (descriptions.length) {\n        case 1:\n          return descriptions[0];\n\n        case 2:\n          return descriptions[0] + \" or \" + descriptions[1];\n\n        default:\n          return descriptions.slice(0, -1).join(\", \")\n            + \", or \"\n            + descriptions[descriptions.length - 1];\n      }\n    }\n\n    function describeFound(found) {\n      return found ? \"\\\"\" + literalEscape(found) + \"\\\"\" : \"end of input\";\n    }\n\n    return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";\n  }\n}\n\nfunction peg$parse(input, options) {\n  options = options !== undefined ? options : {};\n\n  const peg$FAILED = {};\n  const peg$source = options.grammarSource;\n\n  const peg$startRuleFunctions = {\n    start: peg$parsestart,\n  };\n  let peg$startRuleFunction = peg$parsestart;\n\n  const peg$c0 = \"#\";\n  const peg$c1 = \"[\";\n  const peg$c2 = \"]\";\n  const peg$c3 = \".\";\n  const peg$c4 = \"=\";\n  const peg$c5 = \"inf\";\n  const peg$c6 = \"nan\";\n  const peg$c7 = \"\\\"\\\"\\\"\";\n  const peg$c8 = \"\\\"\";\n  const peg$c9 = \"'''\";\n  const peg$c10 = \"'\";\n  const peg$c11 = \"\\\\\";\n  const peg$c12 = \"\\r\\n\";\n  const peg$c13 = \"\\\"\\\"\";\n  const peg$c14 = \"''\";\n  const peg$c15 = \"0\";\n  const peg$c16 = \"0x\";\n  const peg$c17 = \"0o\";\n  const peg$c18 = \"0b\";\n  const peg$c19 = \"true\";\n  const peg$c20 = \"false\";\n  const peg$c21 = \",\";\n  const peg$c22 = \"{\";\n  const peg$c23 = \"}\";\n  const peg$c24 = \"-\";\n  const peg$c25 = \":\";\n  const peg$c26 = \"z\";\n  const peg$c27 = \"t\";\n  const peg$c28 = \" \";\n  const peg$c29 = \"\\n\";\n  const peg$c30 = \"\\r\";\n  const peg$c31 = \"\\uFEFF\";\n  const peg$c32 = \"\\\\U\";\n  const peg$c33 = \"\\\\u\";\n  const peg$c34 = \"\\\\x\";\n\n  const peg$r0 = /^[\\t -~\\x80-\\uFFFF]/;\n  const peg$r1 = /^[+\\-]/;\n  const peg$r2 = /^[^\"\\\\\\0-\\b\\v-\\x1F\\x7F\\r]/;\n  const peg$r3 = /^[^'\\0-\\b\\v-\\x1F\\x7F\\r]/;\n  const peg$r4 = /^[^\"\\\\\\0-\\b\\n-\\x1F\\x7F]/;\n  const peg$r5 = /^[^'\\0-\\b\\n-\\x1F\\x7F]/;\n  const peg$r6 = /^[eE]/;\n  const peg$r7 = /^[0-9_]/;\n  const peg$r8 = /^[1-9]/;\n  const peg$r9 = /^[_]/;\n  const peg$r10 = /^[0-9]/;\n  const peg$r11 = /^[0-9a-fA-F]/;\n  const peg$r12 = /^[0-7]/;\n  const peg$r13 = /^[01]/;\n  const peg$r14 = /^[ \\t]/;\n  const peg$r15 = /^[A-Za-z0-9_\\-]/;\n  const peg$r16 = /^[\"\\\\btnfre]/;\n\n  const peg$e0 = peg$literalExpectation(\"#\", false);\n  const peg$e1 = peg$classExpectation([\"\\t\", [\" \", \"~\"], [\"\\x80\", \"\\uFFFF\"]], false, false, false);\n  const peg$e2 = peg$literalExpectation(\"[\", false);\n  const peg$e3 = peg$literalExpectation(\"]\", false);\n  const peg$e4 = peg$literalExpectation(\".\", false);\n  const peg$e5 = peg$literalExpectation(\"=\", false);\n  const peg$e6 = peg$classExpectation([\"+\", \"-\"], false, false, false);\n  const peg$e7 = peg$literalExpectation(\"inf\", false);\n  const peg$e8 = peg$literalExpectation(\"nan\", false);\n  const peg$e9 = peg$literalExpectation(\"\\\"\\\"\\\"\", false);\n  const peg$e10 = peg$literalExpectation(\"\\\"\", false);\n  const peg$e11 = peg$literalExpectation(\"'''\", false);\n  const peg$e12 = peg$literalExpectation(\"'\", false);\n  const peg$e13 = peg$literalExpectation(\"\\\\\", false);\n  const peg$e14 = peg$anyExpectation();\n  const peg$e15 = peg$literalExpectation(\"\\r\\n\", false);\n  const peg$e16 = peg$classExpectation([\"\\\"\", \"\\\\\", [\"\\0\", \"\\b\"], [\"\\v\", \"\\x1F\"], \"\\x7F\", \"\\r\"], true, false, false);\n  const peg$e17 = peg$literalExpectation(\"\\\"\\\"\", false);\n  const peg$e18 = peg$classExpectation([\"'\", [\"\\0\", \"\\b\"], [\"\\v\", \"\\x1F\"], \"\\x7F\", \"\\r\"], true, false, false);\n  const peg$e19 = peg$literalExpectation(\"''\", false);\n  const peg$e20 = peg$classExpectation([\"\\\"\", \"\\\\\", [\"\\0\", \"\\b\"], [\"\\n\", \"\\x1F\"], \"\\x7F\"], true, false, false);\n  const peg$e21 = peg$classExpectation([\"'\", [\"\\0\", \"\\b\"], [\"\\n\", \"\\x1F\"], \"\\x7F\"], true, false, false);\n  const peg$e22 = peg$classExpectation([\"e\", \"E\"], false, false, false);\n  const peg$e23 = peg$literalExpectation(\"0\", false);\n  const peg$e24 = peg$literalExpectation(\"0x\", false);\n  const peg$e25 = peg$literalExpectation(\"0o\", false);\n  const peg$e26 = peg$literalExpectation(\"0b\", false);\n  const peg$e27 = peg$classExpectation([[\"0\", \"9\"], \"_\"], false, false, false);\n  const peg$e28 = peg$classExpectation([[\"1\", \"9\"]], false, false, false);\n  const peg$e29 = peg$classExpectation([\"_\"], false, false, false);\n  const peg$e30 = peg$classExpectation([[\"0\", \"9\"]], false, false, false);\n  const peg$e31 = peg$classExpectation([[\"0\", \"9\"], [\"a\", \"f\"], [\"A\", \"F\"]], false, false, false);\n  const peg$e32 = peg$classExpectation([[\"0\", \"7\"]], false, false, false);\n  const peg$e33 = peg$classExpectation([\"0\", \"1\"], false, false, false);\n  const peg$e34 = peg$literalExpectation(\"true\", false);\n  const peg$e35 = peg$literalExpectation(\"false\", false);\n  const peg$e36 = peg$literalExpectation(\",\", false);\n  const peg$e37 = peg$literalExpectation(\"{\", false);\n  const peg$e38 = peg$literalExpectation(\"}\", false);\n  const peg$e39 = peg$literalExpectation(\"-\", false);\n  const peg$e40 = peg$literalExpectation(\":\", false);\n  const peg$e41 = peg$literalExpectation(\"Z\", true);\n  const peg$e42 = peg$literalExpectation(\"T\", true);\n  const peg$e43 = peg$literalExpectation(\" \", false);\n  const peg$e44 = peg$classExpectation([\" \", \"\\t\"], false, false, false);\n  const peg$e45 = peg$literalExpectation(\"\\n\", false);\n  const peg$e46 = peg$literalExpectation(\"\\r\", false);\n  const peg$e47 = peg$literalExpectation(\"\\uFEFF\", false);\n  const peg$e48 = peg$classExpectation([[\"A\", \"Z\"], [\"a\", \"z\"], [\"0\", \"9\"], \"_\", \"-\"], false, false, false);\n  const peg$e49 = peg$classExpectation([\"\\\"\", \"\\\\\", \"b\", \"t\", \"n\", \"f\", \"r\", \"e\"], false, false, false);\n  const peg$e50 = peg$literalExpectation(\"\\\\U\", false);\n  const peg$e51 = peg$literalExpectation(\"\\\\u\", false);\n  const peg$e52 = peg$literalExpectation(\"\\\\x\", false);\n\n  function peg$f0() {    return nodes  }\n  function peg$f1(name) {    addNode(node('ArrayPath', name, offset()))  }\n  function peg$f2(name) {    addNode(node('ObjectPath', name, offset()))  }\n  function peg$f3(parts, name) {    return parts.concat(name)  }\n  function peg$f4(name) {    return [name]  }\n  function peg$f5(name) {    return name  }\n  function peg$f6(name) {    return name  }\n  function peg$f7(keys, value) {    addNode(node('Assign', value, offset(), keys))  }\n  function peg$f8(node) {    return node.value  }\n  function peg$f9(node) {    return node.value  }\n  function peg$f10() {    if (++depth > MAX_DEPTH) { depth--; genError(\"Maximum nesting depth of \" + MAX_DEPTH + \" exceeded.\", offset()); } return true;  }\n  function peg$f11(v) {    return v;  }\n  function peg$f12(v) {    depth--; return v;  }\n  function peg$f13() {    depth--; return false;  }\n  function peg$f14(sign) {    return node('Float', sign === '-' ? -Infinity : Infinity, offset())  }\n  function peg$f15(sign) {    return node('Float', NaN, offset())  }\n  function peg$f16(body) {    return node('String', body, offset())  }\n  function peg$f17(chars) {    return node('String', chars.join(''), offset())  }\n  function peg$f18(body) {    return node('String', body, offset())  }\n  function peg$f19(chars) {    return node('String', chars.join(''), offset())  }\n  function peg$f20(head, parts, tail) {\n    var result = head.join('');\n    for (var i = 0; i < parts.length; i++) { result += parts[i][0] + parts[i][1].join(''); }\n    return result + (tail || '');\n  }\n  function peg$f21() {    genError(\"Invalid escape sequence\", offset())  }\n  function peg$f22() {    return \"\\n\"  }\n  function peg$f23() {    return ''  }\n  function peg$f24() {    return '\"\"'  }\n  function peg$f25() {    return '\"'  }\n  function peg$f26() {    return '\"\"'  }\n  function peg$f27() {    return '\"'  }\n  function peg$f28(head, parts, tail) {\n    var result = head.join('');\n    for (var i = 0; i < parts.length; i++) { result += parts[i][0] + parts[i][1].join(''); }\n    return result + (tail || '');\n  }\n  function peg$f29() {    return \"\\n\"  }\n  function peg$f30() {    return \"''\"  }\n  function peg$f31() {    return \"'\"  }\n  function peg$f32() {    return \"''\"  }\n  function peg$f33() {    return \"'\"  }\n  function peg$f34() {    genError(\"Invalid escape sequence\", offset())  }\n  function peg$f35(left, right) {    return node('Float', parseFloat(stripUnderscores(left + 'e' + right)), offset())  }\n  function peg$f36(text) {    return node('Float', parseFloat(stripUnderscores(text)), offset())  }\n  function peg$f37(sign, digits, frac) {    return (sign === '-' ? '-' : '') + digits + '.' + frac  }\n  function peg$f38(sign, digits, frac) {    return (sign === '-' ? '-' : '') + digits + '.' + frac  }\n  function peg$f39(sign, digits) {    return (sign === '-' ? '-' : '') + digits  }\n  function peg$f40() {    return '0'  }\n  function peg$f41(sign, digits) {    return (sign || '') + digits  }\n  function peg$f42(digits) {    return node('Integer', parseInt(stripUnderscores(digits), 16), offset())  }\n  function peg$f43(digits) {    return node('Integer', parseInt(stripUnderscores(digits), 8), offset())  }\n  function peg$f44(digits) {    return node('Integer', parseInt(stripUnderscores(digits), 2), offset())  }\n  function peg$f45(text) {    return node('Integer', parseInt(stripUnderscores(text), 10), offset())  }\n  function peg$f46(sign) {    return (sign || '') + '0'  }\n  function peg$f47(sign, digits) {    return (sign || '') + digits  }\n  function peg$f48() {    return node('Boolean', true, offset())  }\n  function peg$f49() {    return node('Boolean', false, offset())  }\n  function peg$f50() {    return node('Array', [], offset())  }\n  function peg$f51(head, v) {    return v  }\n  function peg$f52(head, tail) {\n    tail.unshift(head); return node('Array', tail, offset())\n  }\n  function peg$f53() {    return node('InlineTable', [], offset())  }\n  function peg$f54(head, e) {    return e  }\n  function peg$f55(head, tail) {\n    tail.unshift(head); return node('InlineTable', tail, offset())\n  }\n  function peg$f56(keys, value) {    return node('InlineTableValue', value, offset(), keys)  }\n  function peg$f57(parts, last) {    return parts.concat(last)  }\n  function peg$f58(k) {    return [k]  }\n  function peg$f59(k) {    return k  }\n  function peg$f60(t, frac) {    return frac ? t + frac : t  }\n  function peg$f61(t) {    return t + ':00'  }\n  function peg$f62() {    return \"Z\"  }\n  function peg$f63(d, t, o) {    var off = offset(); validateDate(d, off); validateTime(t, off); validateOffset(o, off); var n = node('Date', new Date(d + \"T\" + t + o), off); n.raw = d + \"T\" + t; n.tz = o; return n  }\n  function peg$f64(d, t) {    var off = offset(); validateDate(d, off); validateTime(t, off); return node('LocalDateTime', d + \"T\" + t, off)  }\n  function peg$f65(d) {    var off = offset(); validateDate(d, off); return node('LocalDate', d, off)  }\n  function peg$f66(t) {    var off = offset(); validateTime(t, off); return node('LocalTime', t, off)  }\n  function peg$f67(ch) {    return ch === 'n' ? '\\n' : ch === 't' ? '\\t' : ch === 'r' ? '\\r' : ch === '\\\\' ? '\\\\' : ch === '\"' ? '\"' : ch === 'b' ? '\\b' : ch === 'f' ? '\\f' : '\\x1B'  }\n  function peg$f68(digits) {    return convertCodePoint(digits)  }\n  function peg$f69(digits) {    return convertCodePoint(digits)  }\n  function peg$f70(digits) {    return convertCodePoint(digits)  }\n  let peg$currPos = options.peg$currPos | 0;\n  let peg$savedPos = peg$currPos;\n  const peg$posDetailsCache = [{ line: 1, column: 1 }];\n  let peg$maxFailPos = peg$currPos;\n  let peg$maxFailExpected = options.peg$maxFailExpected || [];\n  let peg$silentFails = options.peg$silentFails | 0;\n\n  let peg$result;\n\n  if (options.startRule) {\n    if (!(options.startRule in peg$startRuleFunctions)) {\n      throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");\n    }\n\n    peg$startRuleFunction = peg$startRuleFunctions[options.startRule];\n  }\n\n  function text() {\n    return input.substring(peg$savedPos, peg$currPos);\n  }\n\n  function offset() {\n    return peg$savedPos;\n  }\n\n  function range() {\n    return {\n      source: peg$source,\n      start: peg$savedPos,\n      end: peg$currPos,\n    };\n  }\n\n  function location() {\n    return peg$computeLocation(peg$savedPos, peg$currPos);\n  }\n\n  function expected(description, location) {\n    location = location !== undefined\n      ? location\n      : peg$computeLocation(peg$savedPos, peg$currPos);\n\n    throw peg$buildStructuredError(\n      [peg$otherExpectation(description)],\n      input.substring(peg$savedPos, peg$currPos),\n      location\n    );\n  }\n\n  function error(message, location) {\n    location = location !== undefined\n      ? location\n      : peg$computeLocation(peg$savedPos, peg$currPos);\n\n    throw peg$buildSimpleError(message, location);\n  }\n\n  function peg$getUnicode(pos = peg$currPos) {\n    const cp = input.codePointAt(pos);\n    if (cp === undefined) {\n      return \"\";\n    }\n    return String.fromCodePoint(cp);\n  }\n\n  function peg$literalExpectation(text, ignoreCase) {\n    return { type: \"literal\", text, ignoreCase };\n  }\n\n  function peg$classExpectation(parts, inverted, ignoreCase, unicode) {\n    return { type: \"class\", parts, inverted, ignoreCase, unicode };\n  }\n\n  function peg$anyExpectation() {\n    return { type: \"any\" };\n  }\n\n  function peg$endExpectation() {\n    return { type: \"end\" };\n  }\n\n  function peg$otherExpectation(description) {\n    return { type: \"other\", description };\n  }\n\n  function peg$computePosDetails(pos) {\n    let details = peg$posDetailsCache[pos];\n    let p;\n\n    if (details) {\n      return details;\n    } else {\n      if (pos >= peg$posDetailsCache.length) {\n        p = peg$posDetailsCache.length - 1;\n      } else {\n        p = pos;\n        while (!peg$posDetailsCache[--p]) {}\n      }\n\n      details = peg$posDetailsCache[p];\n      details = {\n        line: details.line,\n        column: details.column,\n      };\n\n      while (p < pos) {\n        if (input.charCodeAt(p) === 10) {\n          details.line++;\n          details.column = 1;\n        } else {\n          details.column++;\n        }\n\n        p++;\n      }\n\n      peg$posDetailsCache[pos] = details;\n\n      return details;\n    }\n  }\n\n  function peg$computeLocation(startPos, endPos, offset) {\n    const startPosDetails = peg$computePosDetails(startPos);\n    const endPosDetails = peg$computePosDetails(endPos);\n\n    const res = {\n      source: peg$source,\n      start: {\n        offset: startPos,\n        line: startPosDetails.line,\n        column: startPosDetails.column,\n      },\n      end: {\n        offset: endPos,\n        line: endPosDetails.line,\n        column: endPosDetails.column,\n      },\n    };\n    if (offset && peg$source && (typeof peg$source.offset === \"function\")) {\n      res.start = peg$source.offset(res.start);\n      res.end = peg$source.offset(res.end);\n    }\n    return res;\n  }\n\n  function peg$fail(expected) {\n    if (peg$currPos < peg$maxFailPos) { return; }\n\n    if (peg$currPos > peg$maxFailPos) {\n      peg$maxFailPos = peg$currPos;\n      peg$maxFailExpected = [];\n    }\n\n    peg$maxFailExpected.push(expected);\n  }\n\n  function peg$buildSimpleError(message, location) {\n    return new peg$SyntaxError(message, null, null, location);\n  }\n\n  function peg$buildStructuredError(expected, found, location) {\n    return new peg$SyntaxError(\n      peg$SyntaxError.buildMessage(expected, found),\n      expected,\n      found,\n      location\n    );\n  }\n\n  function peg$parsestart() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    s1 = peg$parseBOM();\n    if (s1 === peg$FAILED) {\n      s1 = null;\n    }\n    s2 = [];\n    s3 = peg$parseline();\n    while (s3 !== peg$FAILED) {\n      s2.push(s3);\n      s3 = peg$parseline();\n    }\n    peg$savedPos = s0;\n    s0 = peg$f0();\n\n    return s0;\n  }\n\n  function peg$parseline() {\n    let s0, s1, s2, s3, s4, s5, s6;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parseS();\n    while (s2 !== peg$FAILED) {\n      s1.push(s2);\n      s2 = peg$parseS();\n    }\n    s2 = peg$parseexpression();\n    if (s2 !== peg$FAILED) {\n      s3 = [];\n      s4 = peg$parseS();\n      while (s4 !== peg$FAILED) {\n        s3.push(s4);\n        s4 = peg$parseS();\n      }\n      s4 = peg$parsecomment();\n      if (s4 === peg$FAILED) {\n        s4 = null;\n      }\n      s5 = [];\n      s6 = peg$parseNL();\n      if (s6 !== peg$FAILED) {\n        while (s6 !== peg$FAILED) {\n          s5.push(s6);\n          s6 = peg$parseNL();\n        }\n      } else {\n        s5 = peg$FAILED;\n      }\n      if (s5 === peg$FAILED) {\n        s5 = peg$parseEOF();\n      }\n      if (s5 !== peg$FAILED) {\n        s1 = [s1, s2, s3, s4, s5];\n        s0 = s1;\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = [];\n      s2 = peg$parseS();\n      if (s2 !== peg$FAILED) {\n        while (s2 !== peg$FAILED) {\n          s1.push(s2);\n          s2 = peg$parseS();\n        }\n      } else {\n        s1 = peg$FAILED;\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = [];\n        s3 = peg$parseNL();\n        if (s3 !== peg$FAILED) {\n          while (s3 !== peg$FAILED) {\n            s2.push(s3);\n            s3 = peg$parseNL();\n          }\n        } else {\n          s2 = peg$FAILED;\n        }\n        if (s2 === peg$FAILED) {\n          s2 = peg$parseEOF();\n        }\n        if (s2 !== peg$FAILED) {\n          s1 = [s1, s2];\n          s0 = s1;\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n      if (s0 === peg$FAILED) {\n        s0 = peg$parseNL();\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseexpression() {\n    let s0;\n\n    s0 = peg$parsecomment();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parsetable_or_array_path();\n      if (s0 === peg$FAILED) {\n        s0 = peg$parseassignment();\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsecomment() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 35) {\n      s1 = peg$c0;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e0); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = input.charAt(peg$currPos);\n      if (peg$r0.test(s3)) {\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e1); }\n      }\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = input.charAt(peg$currPos);\n        if (peg$r0.test(s3)) {\n          peg$currPos++;\n        } else {\n          s3 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e1); }\n        }\n      }\n      s1 = [s1, s2];\n      s0 = s1;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsetable_or_array_path() {\n    let s0, s1, s2, s3, s4, s5, s6, s7;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 91) {\n      s1 = peg$c1;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e2); }\n    }\n    if (s1 !== peg$FAILED) {\n      if (input.charCodeAt(peg$currPos) === 91) {\n        s2 = peg$c1;\n        peg$currPos++;\n      } else {\n        s2 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e2); }\n      }\n      if (s2 !== peg$FAILED) {\n        s3 = [];\n        s4 = peg$parseS();\n        while (s4 !== peg$FAILED) {\n          s3.push(s4);\n          s4 = peg$parseS();\n        }\n        s4 = peg$parsetable_key();\n        if (s4 !== peg$FAILED) {\n          s5 = [];\n          s6 = peg$parseS();\n          while (s6 !== peg$FAILED) {\n            s5.push(s6);\n            s6 = peg$parseS();\n          }\n          if (input.charCodeAt(peg$currPos) === 93) {\n            s6 = peg$c2;\n            peg$currPos++;\n          } else {\n            s6 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e3); }\n          }\n          if (s6 !== peg$FAILED) {\n            if (input.charCodeAt(peg$currPos) === 93) {\n              s7 = peg$c2;\n              peg$currPos++;\n            } else {\n              s7 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e3); }\n            }\n            if (s7 !== peg$FAILED) {\n              peg$savedPos = s0;\n              s0 = peg$f1(s4);\n            } else {\n              peg$currPos = s0;\n              s0 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 91) {\n        s1 = peg$c1;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e2); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = [];\n        s3 = peg$parseS();\n        while (s3 !== peg$FAILED) {\n          s2.push(s3);\n          s3 = peg$parseS();\n        }\n        s3 = peg$parsetable_key();\n        if (s3 !== peg$FAILED) {\n          s4 = [];\n          s5 = peg$parseS();\n          while (s5 !== peg$FAILED) {\n            s4.push(s5);\n            s5 = peg$parseS();\n          }\n          if (input.charCodeAt(peg$currPos) === 93) {\n            s5 = peg$c2;\n            peg$currPos++;\n          } else {\n            s5 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e3); }\n          }\n          if (s5 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f2(s3);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsetable_key() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parsedot_ended_table_key_part();\n    if (s2 !== peg$FAILED) {\n      while (s2 !== peg$FAILED) {\n        s1.push(s2);\n        s2 = peg$parsedot_ended_table_key_part();\n      }\n    } else {\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$parsetable_key_part();\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f3(s1, s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$parsetable_key_part();\n      if (s1 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s1 = peg$f4(s1);\n      }\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsetable_key_part() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parseS();\n    while (s2 !== peg$FAILED) {\n      s1.push(s2);\n      s2 = peg$parseS();\n    }\n    s2 = peg$parsesimple_key();\n    if (s2 !== peg$FAILED) {\n      s3 = [];\n      s4 = peg$parseS();\n      while (s4 !== peg$FAILED) {\n        s3.push(s4);\n        s4 = peg$parseS();\n      }\n      peg$savedPos = s0;\n      s0 = peg$f5(s2);\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsedot_ended_table_key_part() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parseS();\n    while (s2 !== peg$FAILED) {\n      s1.push(s2);\n      s2 = peg$parseS();\n    }\n    s2 = peg$parsesimple_key();\n    if (s2 !== peg$FAILED) {\n      s3 = [];\n      s4 = peg$parseS();\n      while (s4 !== peg$FAILED) {\n        s3.push(s4);\n        s4 = peg$parseS();\n      }\n      if (input.charCodeAt(peg$currPos) === 46) {\n        s4 = peg$c3;\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e4); }\n      }\n      if (s4 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f6(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseassignment() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = peg$parseinline_key();\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parseS();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parseS();\n      }\n      if (input.charCodeAt(peg$currPos) === 61) {\n        s3 = peg$c4;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e5); }\n      }\n      if (s3 !== peg$FAILED) {\n        s4 = [];\n        s5 = peg$parseS();\n        while (s5 !== peg$FAILED) {\n          s4.push(s5);\n          s5 = peg$parseS();\n        }\n        s5 = peg$parsevalue();\n        if (s5 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f7(s1, s5);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsekey() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parseASCII_BASIC();\n    if (s2 !== peg$FAILED) {\n      while (s2 !== peg$FAILED) {\n        s1.push(s2);\n        s2 = peg$parseASCII_BASIC();\n      }\n    } else {\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s0 = input.substring(s0, peg$currPos);\n    } else {\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsequoted_key() {\n    let s0, s1;\n\n    s0 = peg$currPos;\n    s1 = peg$parsedouble_quoted_single_line_string();\n    if (s1 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s1 = peg$f8(s1);\n    }\n    s0 = s1;\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$parsesingle_quoted_single_line_string();\n      if (s1 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s1 = peg$f9(s1);\n      }\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsevalue() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    peg$savedPos = peg$currPos;\n    s1 = peg$f10();\n    if (s1) {\n      s1 = undefined;\n    } else {\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$parsevalue_choice();\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f11(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsevalue_choice() {\n    let s0, s1;\n\n    s0 = peg$currPos;\n    s1 = peg$parsevalue_body();\n    if (s1 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s1 = peg$f12(s1);\n    }\n    s0 = s1;\n    if (s0 === peg$FAILED) {\n      peg$savedPos = peg$currPos;\n      s0 = peg$f13();\n      if (s0) {\n        s0 = undefined;\n      } else {\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsevalue_body() {\n    let s0;\n\n    s0 = peg$parsestring();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parsenumber_or_date();\n      if (s0 === peg$FAILED) {\n        s0 = peg$parseboolean();\n        if (s0 === peg$FAILED) {\n          s0 = peg$parsearray();\n          if (s0 === peg$FAILED) {\n            s0 = peg$parseinline_table();\n          }\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsenumber_or_date() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r1.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e6); }\n    }\n    if (s1 === peg$FAILED) {\n      s1 = null;\n    }\n    if (input.substr(peg$currPos, 3) === peg$c5) {\n      s2 = peg$c5;\n      peg$currPos += 3;\n    } else {\n      s2 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e7); }\n    }\n    if (s2 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s0 = peg$f14(s1);\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = input.charAt(peg$currPos);\n      if (peg$r1.test(s1)) {\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e6); }\n      }\n      if (s1 === peg$FAILED) {\n        s1 = null;\n      }\n      if (input.substr(peg$currPos, 3) === peg$c6) {\n        s2 = peg$c6;\n        peg$currPos += 3;\n      } else {\n        s2 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e8); }\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f15(s1);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n      if (s0 === peg$FAILED) {\n        s0 = peg$parsedatetime();\n        if (s0 === peg$FAILED) {\n          s0 = peg$parsefloat();\n          if (s0 === peg$FAILED) {\n            s0 = peg$parseinteger();\n          }\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsestring() {\n    let s0;\n\n    s0 = peg$parsedouble_quoted_multiline_string();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parsedouble_quoted_single_line_string();\n      if (s0 === peg$FAILED) {\n        s0 = peg$parsesingle_quoted_multiline_string();\n        if (s0 === peg$FAILED) {\n          s0 = peg$parsesingle_quoted_single_line_string();\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsedouble_quoted_multiline_string() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 3) === peg$c7) {\n      s1 = peg$c7;\n      peg$currPos += 3;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e9); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$parseNL();\n      if (s2 === peg$FAILED) {\n        s2 = null;\n      }\n      s3 = peg$parsemlb_body();\n      if (input.substr(peg$currPos, 3) === peg$c7) {\n        s4 = peg$c7;\n        peg$currPos += 3;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e9); }\n      }\n      if (s4 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f16(s3);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsedouble_quoted_single_line_string() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 34) {\n      s1 = peg$c8;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e10); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parsestring_char();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parsestring_char();\n      }\n      if (input.charCodeAt(peg$currPos) === 34) {\n        s3 = peg$c8;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e10); }\n      }\n      if (s3 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f17(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsesingle_quoted_multiline_string() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 3) === peg$c9) {\n      s1 = peg$c9;\n      peg$currPos += 3;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e11); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$parseNL();\n      if (s2 === peg$FAILED) {\n        s2 = null;\n      }\n      s3 = peg$parsemll_body();\n      if (input.substr(peg$currPos, 3) === peg$c9) {\n        s4 = peg$c9;\n        peg$currPos += 3;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e11); }\n      }\n      if (s4 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f18(s3);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsesingle_quoted_single_line_string() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 39) {\n      s1 = peg$c10;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e12); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parseliteral_char();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parseliteral_char();\n      }\n      if (input.charCodeAt(peg$currPos) === 39) {\n        s3 = peg$c10;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e12); }\n      }\n      if (s3 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f19(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsemlb_body() {\n    let s0, s1, s2, s3, s4, s5, s6;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parsemlb_content();\n    while (s2 !== peg$FAILED) {\n      s1.push(s2);\n      s2 = peg$parsemlb_content();\n    }\n    s2 = [];\n    s3 = peg$currPos;\n    s4 = peg$parsemlb_quotes();\n    if (s4 !== peg$FAILED) {\n      s5 = [];\n      s6 = peg$parsemlb_content();\n      if (s6 !== peg$FAILED) {\n        while (s6 !== peg$FAILED) {\n          s5.push(s6);\n          s6 = peg$parsemlb_content();\n        }\n      } else {\n        s5 = peg$FAILED;\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s3;\n      s3 = peg$FAILED;\n    }\n    while (s3 !== peg$FAILED) {\n      s2.push(s3);\n      s3 = peg$currPos;\n      s4 = peg$parsemlb_quotes();\n      if (s4 !== peg$FAILED) {\n        s5 = [];\n        s6 = peg$parsemlb_content();\n        if (s6 !== peg$FAILED) {\n          while (s6 !== peg$FAILED) {\n            s5.push(s6);\n            s6 = peg$parsemlb_content();\n          }\n        } else {\n          s5 = peg$FAILED;\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n    }\n    s3 = peg$parsemlb_trailing();\n    if (s3 === peg$FAILED) {\n      s3 = null;\n    }\n    peg$savedPos = s0;\n    s0 = peg$f20(s1, s2, s3);\n\n    return s0;\n  }\n\n  function peg$parsemlb_content() {\n    let s0, s1, s2;\n\n    s0 = peg$parseESCAPED();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parsemlb_escaped_newline();\n      if (s0 === peg$FAILED) {\n        s0 = peg$currPos;\n        if (input.charCodeAt(peg$currPos) === 92) {\n          s1 = peg$c11;\n          peg$currPos++;\n        } else {\n          s1 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e13); }\n        }\n        if (s1 !== peg$FAILED) {\n          if (input.length > peg$currPos) {\n            s2 = input.charAt(peg$currPos);\n            peg$currPos++;\n          } else {\n            s2 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e14); }\n          }\n          if (s2 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f21();\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n        if (s0 === peg$FAILED) {\n          s0 = peg$currPos;\n          if (input.substr(peg$currPos, 2) === peg$c12) {\n            s1 = peg$c12;\n            peg$currPos += 2;\n          } else {\n            s1 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e15); }\n          }\n          if (s1 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s1 = peg$f22();\n          }\n          s0 = s1;\n          if (s0 === peg$FAILED) {\n            s0 = peg$currPos;\n            s1 = [];\n            s2 = input.charAt(peg$currPos);\n            if (peg$r2.test(s2)) {\n              peg$currPos++;\n            } else {\n              s2 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e16); }\n            }\n            if (s2 !== peg$FAILED) {\n              while (s2 !== peg$FAILED) {\n                s1.push(s2);\n                s2 = input.charAt(peg$currPos);\n                if (peg$r2.test(s2)) {\n                  peg$currPos++;\n                } else {\n                  s2 = peg$FAILED;\n                  if (peg$silentFails === 0) { peg$fail(peg$e16); }\n                }\n              }\n            } else {\n              s1 = peg$FAILED;\n            }\n            if (s1 !== peg$FAILED) {\n              s0 = input.substring(s0, peg$currPos);\n            } else {\n              s0 = s1;\n            }\n          }\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsemlb_escaped_newline() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 92) {\n      s1 = peg$c11;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e13); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parseS();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parseS();\n      }\n      s3 = peg$parseNL();\n      if (s3 !== peg$FAILED) {\n        s4 = [];\n        s5 = peg$parseNLS();\n        while (s5 !== peg$FAILED) {\n          s4.push(s5);\n          s5 = peg$parseNLS();\n        }\n        peg$savedPos = s0;\n        s0 = peg$f23();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsemlb_quotes() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c13) {\n      s1 = peg$c13;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e17); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$currPos;\n      peg$silentFails++;\n      if (input.charCodeAt(peg$currPos) === 34) {\n        s3 = peg$c8;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e10); }\n      }\n      peg$silentFails--;\n      if (s3 === peg$FAILED) {\n        s2 = undefined;\n      } else {\n        peg$currPos = s2;\n        s2 = peg$FAILED;\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f24();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 34) {\n        s1 = peg$c8;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e10); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        peg$silentFails++;\n        if (input.charCodeAt(peg$currPos) === 34) {\n          s3 = peg$c8;\n          peg$currPos++;\n        } else {\n          s3 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e10); }\n        }\n        peg$silentFails--;\n        if (s3 === peg$FAILED) {\n          s2 = undefined;\n        } else {\n          peg$currPos = s2;\n          s2 = peg$FAILED;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f25();\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsemlb_trailing() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c13) {\n      s1 = peg$c13;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e17); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$currPos;\n      peg$silentFails++;\n      if (input.substr(peg$currPos, 3) === peg$c7) {\n        s3 = peg$c7;\n        peg$currPos += 3;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e9); }\n      }\n      peg$silentFails--;\n      if (s3 !== peg$FAILED) {\n        peg$currPos = s2;\n        s2 = undefined;\n      } else {\n        s2 = peg$FAILED;\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f26();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 34) {\n        s1 = peg$c8;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e10); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        peg$silentFails++;\n        if (input.substr(peg$currPos, 3) === peg$c7) {\n          s3 = peg$c7;\n          peg$currPos += 3;\n        } else {\n          s3 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e9); }\n        }\n        peg$silentFails--;\n        if (s3 !== peg$FAILED) {\n          peg$currPos = s2;\n          s2 = undefined;\n        } else {\n          s2 = peg$FAILED;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f27();\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsemll_body() {\n    let s0, s1, s2, s3, s4, s5, s6;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parsemll_content();\n    while (s2 !== peg$FAILED) {\n      s1.push(s2);\n      s2 = peg$parsemll_content();\n    }\n    s2 = [];\n    s3 = peg$currPos;\n    s4 = peg$parsemll_quotes();\n    if (s4 !== peg$FAILED) {\n      s5 = [];\n      s6 = peg$parsemll_content();\n      if (s6 !== peg$FAILED) {\n        while (s6 !== peg$FAILED) {\n          s5.push(s6);\n          s6 = peg$parsemll_content();\n        }\n      } else {\n        s5 = peg$FAILED;\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s3;\n      s3 = peg$FAILED;\n    }\n    while (s3 !== peg$FAILED) {\n      s2.push(s3);\n      s3 = peg$currPos;\n      s4 = peg$parsemll_quotes();\n      if (s4 !== peg$FAILED) {\n        s5 = [];\n        s6 = peg$parsemll_content();\n        if (s6 !== peg$FAILED) {\n          while (s6 !== peg$FAILED) {\n            s5.push(s6);\n            s6 = peg$parsemll_content();\n          }\n        } else {\n          s5 = peg$FAILED;\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n    }\n    s3 = peg$parsemll_trailing();\n    if (s3 === peg$FAILED) {\n      s3 = null;\n    }\n    peg$savedPos = s0;\n    s0 = peg$f28(s1, s2, s3);\n\n    return s0;\n  }\n\n  function peg$parsemll_content() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c12) {\n      s1 = peg$c12;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e15); }\n    }\n    if (s1 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s1 = peg$f29();\n    }\n    s0 = s1;\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = [];\n      s2 = input.charAt(peg$currPos);\n      if (peg$r3.test(s2)) {\n        peg$currPos++;\n      } else {\n        s2 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e18); }\n      }\n      if (s2 !== peg$FAILED) {\n        while (s2 !== peg$FAILED) {\n          s1.push(s2);\n          s2 = input.charAt(peg$currPos);\n          if (peg$r3.test(s2)) {\n            peg$currPos++;\n          } else {\n            s2 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e18); }\n          }\n        }\n      } else {\n        s1 = peg$FAILED;\n      }\n      if (s1 !== peg$FAILED) {\n        s0 = input.substring(s0, peg$currPos);\n      } else {\n        s0 = s1;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsemll_quotes() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c14) {\n      s1 = peg$c14;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e19); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$currPos;\n      peg$silentFails++;\n      if (input.charCodeAt(peg$currPos) === 39) {\n        s3 = peg$c10;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e12); }\n      }\n      peg$silentFails--;\n      if (s3 === peg$FAILED) {\n        s2 = undefined;\n      } else {\n        peg$currPos = s2;\n        s2 = peg$FAILED;\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f30();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 39) {\n        s1 = peg$c10;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e12); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        peg$silentFails++;\n        if (input.charCodeAt(peg$currPos) === 39) {\n          s3 = peg$c10;\n          peg$currPos++;\n        } else {\n          s3 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e12); }\n        }\n        peg$silentFails--;\n        if (s3 === peg$FAILED) {\n          s2 = undefined;\n        } else {\n          peg$currPos = s2;\n          s2 = peg$FAILED;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f31();\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsemll_trailing() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c14) {\n      s1 = peg$c14;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e19); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$currPos;\n      peg$silentFails++;\n      if (input.substr(peg$currPos, 3) === peg$c9) {\n        s3 = peg$c9;\n        peg$currPos += 3;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e11); }\n      }\n      peg$silentFails--;\n      if (s3 !== peg$FAILED) {\n        peg$currPos = s2;\n        s2 = undefined;\n      } else {\n        s2 = peg$FAILED;\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f32();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 39) {\n        s1 = peg$c10;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e12); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        peg$silentFails++;\n        if (input.substr(peg$currPos, 3) === peg$c9) {\n          s3 = peg$c9;\n          peg$currPos += 3;\n        } else {\n          s3 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e11); }\n        }\n        peg$silentFails--;\n        if (s3 !== peg$FAILED) {\n          peg$currPos = s2;\n          s2 = undefined;\n        } else {\n          s2 = peg$FAILED;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f33();\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsestring_char() {\n    let s0, s1, s2;\n\n    s0 = peg$parseESCAPED();\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 92) {\n        s1 = peg$c11;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e13); }\n      }\n      if (s1 !== peg$FAILED) {\n        if (input.length > peg$currPos) {\n          s2 = input.charAt(peg$currPos);\n          peg$currPos++;\n        } else {\n          s2 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e14); }\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f34();\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n      if (s0 === peg$FAILED) {\n        s0 = peg$currPos;\n        s1 = [];\n        s2 = input.charAt(peg$currPos);\n        if (peg$r4.test(s2)) {\n          peg$currPos++;\n        } else {\n          s2 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e20); }\n        }\n        if (s2 !== peg$FAILED) {\n          while (s2 !== peg$FAILED) {\n            s1.push(s2);\n            s2 = input.charAt(peg$currPos);\n            if (peg$r4.test(s2)) {\n              peg$currPos++;\n            } else {\n              s2 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e20); }\n            }\n          }\n        } else {\n          s1 = peg$FAILED;\n        }\n        if (s1 !== peg$FAILED) {\n          s0 = input.substring(s0, peg$currPos);\n        } else {\n          s0 = s1;\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseliteral_char() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = input.charAt(peg$currPos);\n    if (peg$r5.test(s2)) {\n      peg$currPos++;\n    } else {\n      s2 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e21); }\n    }\n    if (s2 !== peg$FAILED) {\n      while (s2 !== peg$FAILED) {\n        s1.push(s2);\n        s2 = input.charAt(peg$currPos);\n        if (peg$r5.test(s2)) {\n          peg$currPos++;\n        } else {\n          s2 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e21); }\n        }\n      }\n    } else {\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s0 = input.substring(s0, peg$currPos);\n    } else {\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsefloat() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    s1 = peg$parsefloat_or_int_text();\n    if (s1 !== peg$FAILED) {\n      s2 = input.charAt(peg$currPos);\n      if (peg$r6.test(s2)) {\n        peg$currPos++;\n      } else {\n        s2 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e22); }\n      }\n      if (s2 !== peg$FAILED) {\n        s3 = peg$parsefloat_exp_text();\n        if (s3 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f35(s1, s3);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$parsefloat_text();\n      if (s1 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s1 = peg$f36(s1);\n      }\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsefloat_text() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r1.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e6); }\n    }\n    if (s1 === peg$FAILED) {\n      s1 = null;\n    }\n    s2 = peg$parseFLOAT_DEC_INT();\n    if (s2 !== peg$FAILED) {\n      if (input.charCodeAt(peg$currPos) === 46) {\n        s3 = peg$c3;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e4); }\n      }\n      if (s3 !== peg$FAILED) {\n        s4 = peg$currPos;\n        s5 = peg$parseDEC_DIGIT_SEQ();\n        if (s5 !== peg$FAILED) {\n          s4 = input.substring(s4, peg$currPos);\n        } else {\n          s4 = s5;\n        }\n        if (s4 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f37(s1, s2, s4);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsefloat_or_int_text() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r1.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e6); }\n    }\n    if (s1 === peg$FAILED) {\n      s1 = null;\n    }\n    s2 = peg$parseFLOAT_DEC_INT();\n    if (s2 !== peg$FAILED) {\n      if (input.charCodeAt(peg$currPos) === 46) {\n        s3 = peg$c3;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e4); }\n      }\n      if (s3 !== peg$FAILED) {\n        s4 = peg$currPos;\n        s5 = peg$parseDEC_DIGIT_SEQ();\n        if (s5 !== peg$FAILED) {\n          s4 = input.substring(s4, peg$currPos);\n        } else {\n          s4 = s5;\n        }\n        if (s4 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f38(s1, s2, s4);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = input.charAt(peg$currPos);\n      if (peg$r1.test(s1)) {\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e6); }\n      }\n      if (s1 === peg$FAILED) {\n        s1 = null;\n      }\n      s2 = peg$parseFLOAT_DEC_INT();\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f39(s1, s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseFLOAT_DEC_INT() {\n    let s0, s1;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 48) {\n      s1 = peg$c15;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e23); }\n    }\n    if (s1 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s1 = peg$f40();\n    }\n    s0 = s1;\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$parseDEC_INT_NOZERO_SEQ();\n      if (s1 !== peg$FAILED) {\n        s0 = input.substring(s0, peg$currPos);\n      } else {\n        s0 = s1;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsefloat_exp_text() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r1.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e6); }\n    }\n    if (s1 === peg$FAILED) {\n      s1 = null;\n    }\n    s2 = peg$currPos;\n    s3 = peg$parseDEC_DIGIT_SEQ();\n    if (s3 !== peg$FAILED) {\n      s2 = input.substring(s2, peg$currPos);\n    } else {\n      s2 = s3;\n    }\n    if (s2 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s0 = peg$f41(s1, s2);\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseinteger() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c16) {\n      s1 = peg$c16;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e24); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$currPos;\n      s3 = peg$parseHEX_DIGIT_SEQ();\n      if (s3 !== peg$FAILED) {\n        s2 = input.substring(s2, peg$currPos);\n      } else {\n        s2 = s3;\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f42(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.substr(peg$currPos, 2) === peg$c17) {\n        s1 = peg$c17;\n        peg$currPos += 2;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e25); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        s3 = peg$parseOCT_DIGIT_SEQ();\n        if (s3 !== peg$FAILED) {\n          s2 = input.substring(s2, peg$currPos);\n        } else {\n          s2 = s3;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f43(s2);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n      if (s0 === peg$FAILED) {\n        s0 = peg$currPos;\n        if (input.substr(peg$currPos, 2) === peg$c18) {\n          s1 = peg$c18;\n          peg$currPos += 2;\n        } else {\n          s1 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e26); }\n        }\n        if (s1 !== peg$FAILED) {\n          s2 = peg$currPos;\n          s3 = peg$parseBIN_DIGIT_SEQ();\n          if (s3 !== peg$FAILED) {\n            s2 = input.substring(s2, peg$currPos);\n          } else {\n            s2 = s3;\n          }\n          if (s2 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f44(s2);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n        if (s0 === peg$FAILED) {\n          s0 = peg$currPos;\n          s1 = peg$parsedec_integer_text();\n          if (s1 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s1 = peg$f45(s1);\n          }\n          s0 = s1;\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsedec_integer_text() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r1.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e6); }\n    }\n    if (s1 === peg$FAILED) {\n      s1 = null;\n    }\n    if (input.charCodeAt(peg$currPos) === 48) {\n      s2 = peg$c15;\n      peg$currPos++;\n    } else {\n      s2 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e23); }\n    }\n    if (s2 !== peg$FAILED) {\n      s3 = peg$currPos;\n      peg$silentFails++;\n      s4 = input.charAt(peg$currPos);\n      if (peg$r7.test(s4)) {\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e27); }\n      }\n      peg$silentFails--;\n      if (s4 === peg$FAILED) {\n        s3 = undefined;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      if (s3 !== peg$FAILED) {\n        s4 = peg$currPos;\n        peg$silentFails++;\n        if (input.charCodeAt(peg$currPos) === 46) {\n          s5 = peg$c3;\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e4); }\n        }\n        peg$silentFails--;\n        if (s5 === peg$FAILED) {\n          s4 = undefined;\n        } else {\n          peg$currPos = s4;\n          s4 = peg$FAILED;\n        }\n        if (s4 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f46(s1);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = input.charAt(peg$currPos);\n      if (peg$r1.test(s1)) {\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e6); }\n      }\n      if (s1 === peg$FAILED) {\n        s1 = null;\n      }\n      s2 = peg$currPos;\n      s3 = peg$parseDEC_INT_NOZERO_SEQ();\n      if (s3 !== peg$FAILED) {\n        s2 = input.substring(s2, peg$currPos);\n      } else {\n        s2 = s3;\n      }\n      if (s2 !== peg$FAILED) {\n        s3 = peg$currPos;\n        peg$silentFails++;\n        if (input.charCodeAt(peg$currPos) === 46) {\n          s4 = peg$c3;\n          peg$currPos++;\n        } else {\n          s4 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e4); }\n        }\n        peg$silentFails--;\n        if (s4 === peg$FAILED) {\n          s3 = undefined;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n        if (s3 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f47(s1, s2);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseDEC_INT_NOZERO_SEQ() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r8.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e28); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$currPos;\n      s4 = input.charAt(peg$currPos);\n      if (peg$r9.test(s4)) {\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e29); }\n      }\n      if (s4 === peg$FAILED) {\n        s4 = null;\n      }\n      s5 = input.charAt(peg$currPos);\n      if (peg$r10.test(s5)) {\n        peg$currPos++;\n      } else {\n        s5 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e30); }\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$currPos;\n        s4 = input.charAt(peg$currPos);\n        if (peg$r9.test(s4)) {\n          peg$currPos++;\n        } else {\n          s4 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e29); }\n        }\n        if (s4 === peg$FAILED) {\n          s4 = null;\n        }\n        s5 = input.charAt(peg$currPos);\n        if (peg$r10.test(s5)) {\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e30); }\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      }\n      s1 = [s1, s2];\n      s0 = s1;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseDEC_DIGIT_SEQ() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r10.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e30); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$currPos;\n      s4 = input.charAt(peg$currPos);\n      if (peg$r9.test(s4)) {\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e29); }\n      }\n      if (s4 === peg$FAILED) {\n        s4 = null;\n      }\n      s5 = input.charAt(peg$currPos);\n      if (peg$r10.test(s5)) {\n        peg$currPos++;\n      } else {\n        s5 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e30); }\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$currPos;\n        s4 = input.charAt(peg$currPos);\n        if (peg$r9.test(s4)) {\n          peg$currPos++;\n        } else {\n          s4 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e29); }\n        }\n        if (s4 === peg$FAILED) {\n          s4 = null;\n        }\n        s5 = input.charAt(peg$currPos);\n        if (peg$r10.test(s5)) {\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e30); }\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      }\n      s1 = [s1, s2];\n      s0 = s1;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseHEX_DIGIT_SEQ() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r11.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e31); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$currPos;\n      s4 = input.charAt(peg$currPos);\n      if (peg$r9.test(s4)) {\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e29); }\n      }\n      if (s4 === peg$FAILED) {\n        s4 = null;\n      }\n      s5 = input.charAt(peg$currPos);\n      if (peg$r11.test(s5)) {\n        peg$currPos++;\n      } else {\n        s5 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e31); }\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$currPos;\n        s4 = input.charAt(peg$currPos);\n        if (peg$r9.test(s4)) {\n          peg$currPos++;\n        } else {\n          s4 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e29); }\n        }\n        if (s4 === peg$FAILED) {\n          s4 = null;\n        }\n        s5 = input.charAt(peg$currPos);\n        if (peg$r11.test(s5)) {\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e31); }\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      }\n      s1 = [s1, s2];\n      s0 = s1;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseOCT_DIGIT_SEQ() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r12.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e32); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$currPos;\n      s4 = input.charAt(peg$currPos);\n      if (peg$r9.test(s4)) {\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e29); }\n      }\n      if (s4 === peg$FAILED) {\n        s4 = null;\n      }\n      s5 = input.charAt(peg$currPos);\n      if (peg$r12.test(s5)) {\n        peg$currPos++;\n      } else {\n        s5 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e32); }\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$currPos;\n        s4 = input.charAt(peg$currPos);\n        if (peg$r9.test(s4)) {\n          peg$currPos++;\n        } else {\n          s4 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e29); }\n        }\n        if (s4 === peg$FAILED) {\n          s4 = null;\n        }\n        s5 = input.charAt(peg$currPos);\n        if (peg$r12.test(s5)) {\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e32); }\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      }\n      s1 = [s1, s2];\n      s0 = s1;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseBIN_DIGIT_SEQ() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (peg$r13.test(s1)) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e33); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$currPos;\n      s4 = input.charAt(peg$currPos);\n      if (peg$r9.test(s4)) {\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e29); }\n      }\n      if (s4 === peg$FAILED) {\n        s4 = null;\n      }\n      s5 = input.charAt(peg$currPos);\n      if (peg$r13.test(s5)) {\n        peg$currPos++;\n      } else {\n        s5 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e33); }\n      }\n      if (s5 !== peg$FAILED) {\n        s4 = [s4, s5];\n        s3 = s4;\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$currPos;\n        s4 = input.charAt(peg$currPos);\n        if (peg$r9.test(s4)) {\n          peg$currPos++;\n        } else {\n          s4 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e29); }\n        }\n        if (s4 === peg$FAILED) {\n          s4 = null;\n        }\n        s5 = input.charAt(peg$currPos);\n        if (peg$r13.test(s5)) {\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e33); }\n        }\n        if (s5 !== peg$FAILED) {\n          s4 = [s4, s5];\n          s3 = s4;\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      }\n      s1 = [s1, s2];\n      s0 = s1;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseboolean() {\n    let s0, s1;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 4) === peg$c19) {\n      s1 = peg$c19;\n      peg$currPos += 4;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e34); }\n    }\n    if (s1 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s1 = peg$f48();\n    }\n    s0 = s1;\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.substr(peg$currPos, 5) === peg$c20) {\n        s1 = peg$c20;\n        peg$currPos += 5;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e35); }\n      }\n      if (s1 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s1 = peg$f49();\n      }\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsearray() {\n    let s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 91) {\n      s1 = peg$c1;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e2); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parsearray_sep();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parsearray_sep();\n      }\n      if (input.charCodeAt(peg$currPos) === 93) {\n        s3 = peg$c2;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e3); }\n      }\n      if (s3 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f50();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 91) {\n        s1 = peg$c1;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e2); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = [];\n        s3 = peg$parsearray_sep();\n        while (s3 !== peg$FAILED) {\n          s2.push(s3);\n          s3 = peg$parsearray_sep();\n        }\n        s3 = peg$parsevalue();\n        if (s3 !== peg$FAILED) {\n          s4 = [];\n          s5 = peg$currPos;\n          s6 = [];\n          s7 = peg$parsearray_sep();\n          while (s7 !== peg$FAILED) {\n            s6.push(s7);\n            s7 = peg$parsearray_sep();\n          }\n          if (input.charCodeAt(peg$currPos) === 44) {\n            s7 = peg$c21;\n            peg$currPos++;\n          } else {\n            s7 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e36); }\n          }\n          if (s7 !== peg$FAILED) {\n            s8 = [];\n            s9 = peg$parsearray_sep();\n            while (s9 !== peg$FAILED) {\n              s8.push(s9);\n              s9 = peg$parsearray_sep();\n            }\n            s9 = peg$parsevalue();\n            if (s9 !== peg$FAILED) {\n              peg$savedPos = s5;\n              s5 = peg$f51(s3, s9);\n            } else {\n              peg$currPos = s5;\n              s5 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s5;\n            s5 = peg$FAILED;\n          }\n          while (s5 !== peg$FAILED) {\n            s4.push(s5);\n            s5 = peg$currPos;\n            s6 = [];\n            s7 = peg$parsearray_sep();\n            while (s7 !== peg$FAILED) {\n              s6.push(s7);\n              s7 = peg$parsearray_sep();\n            }\n            if (input.charCodeAt(peg$currPos) === 44) {\n              s7 = peg$c21;\n              peg$currPos++;\n            } else {\n              s7 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e36); }\n            }\n            if (s7 !== peg$FAILED) {\n              s8 = [];\n              s9 = peg$parsearray_sep();\n              while (s9 !== peg$FAILED) {\n                s8.push(s9);\n                s9 = peg$parsearray_sep();\n              }\n              s9 = peg$parsevalue();\n              if (s9 !== peg$FAILED) {\n                peg$savedPos = s5;\n                s5 = peg$f51(s3, s9);\n              } else {\n                peg$currPos = s5;\n                s5 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s5;\n              s5 = peg$FAILED;\n            }\n          }\n          s5 = [];\n          s6 = peg$parsearray_sep();\n          while (s6 !== peg$FAILED) {\n            s5.push(s6);\n            s6 = peg$parsearray_sep();\n          }\n          if (input.charCodeAt(peg$currPos) === 44) {\n            s6 = peg$c21;\n            peg$currPos++;\n          } else {\n            s6 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e36); }\n          }\n          if (s6 === peg$FAILED) {\n            s6 = null;\n          }\n          s7 = [];\n          s8 = peg$parsearray_sep();\n          while (s8 !== peg$FAILED) {\n            s7.push(s8);\n            s8 = peg$parsearray_sep();\n          }\n          if (input.charCodeAt(peg$currPos) === 93) {\n            s8 = peg$c2;\n            peg$currPos++;\n          } else {\n            s8 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e3); }\n          }\n          if (s8 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f52(s3, s4);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsearray_sep() {\n    let s0;\n\n    s0 = peg$parseS();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parseNL();\n      if (s0 === peg$FAILED) {\n        s0 = peg$parsecomment();\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseinline_table() {\n    let s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 123) {\n      s1 = peg$c22;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e37); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parseinline_sep();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parseinline_sep();\n      }\n      if (input.charCodeAt(peg$currPos) === 125) {\n        s3 = peg$c23;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e38); }\n      }\n      if (s3 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f53();\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 123) {\n        s1 = peg$c22;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e37); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = [];\n        s3 = peg$parseinline_sep();\n        while (s3 !== peg$FAILED) {\n          s2.push(s3);\n          s3 = peg$parseinline_sep();\n        }\n        s3 = peg$parseinline_table_entry();\n        if (s3 !== peg$FAILED) {\n          s4 = [];\n          s5 = peg$currPos;\n          s6 = [];\n          s7 = peg$parseinline_sep();\n          while (s7 !== peg$FAILED) {\n            s6.push(s7);\n            s7 = peg$parseinline_sep();\n          }\n          if (input.charCodeAt(peg$currPos) === 44) {\n            s7 = peg$c21;\n            peg$currPos++;\n          } else {\n            s7 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e36); }\n          }\n          if (s7 !== peg$FAILED) {\n            s8 = [];\n            s9 = peg$parseinline_sep();\n            while (s9 !== peg$FAILED) {\n              s8.push(s9);\n              s9 = peg$parseinline_sep();\n            }\n            s9 = peg$parseinline_table_entry();\n            if (s9 !== peg$FAILED) {\n              peg$savedPos = s5;\n              s5 = peg$f54(s3, s9);\n            } else {\n              peg$currPos = s5;\n              s5 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s5;\n            s5 = peg$FAILED;\n          }\n          while (s5 !== peg$FAILED) {\n            s4.push(s5);\n            s5 = peg$currPos;\n            s6 = [];\n            s7 = peg$parseinline_sep();\n            while (s7 !== peg$FAILED) {\n              s6.push(s7);\n              s7 = peg$parseinline_sep();\n            }\n            if (input.charCodeAt(peg$currPos) === 44) {\n              s7 = peg$c21;\n              peg$currPos++;\n            } else {\n              s7 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e36); }\n            }\n            if (s7 !== peg$FAILED) {\n              s8 = [];\n              s9 = peg$parseinline_sep();\n              while (s9 !== peg$FAILED) {\n                s8.push(s9);\n                s9 = peg$parseinline_sep();\n              }\n              s9 = peg$parseinline_table_entry();\n              if (s9 !== peg$FAILED) {\n                peg$savedPos = s5;\n                s5 = peg$f54(s3, s9);\n              } else {\n                peg$currPos = s5;\n                s5 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s5;\n              s5 = peg$FAILED;\n            }\n          }\n          s5 = [];\n          s6 = peg$parseinline_sep();\n          while (s6 !== peg$FAILED) {\n            s5.push(s6);\n            s6 = peg$parseinline_sep();\n          }\n          if (input.charCodeAt(peg$currPos) === 44) {\n            s6 = peg$c21;\n            peg$currPos++;\n          } else {\n            s6 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e36); }\n          }\n          if (s6 === peg$FAILED) {\n            s6 = null;\n          }\n          s7 = [];\n          s8 = peg$parseinline_sep();\n          while (s8 !== peg$FAILED) {\n            s7.push(s8);\n            s8 = peg$parseinline_sep();\n          }\n          if (input.charCodeAt(peg$currPos) === 125) {\n            s8 = peg$c23;\n            peg$currPos++;\n          } else {\n            s8 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e38); }\n          }\n          if (s8 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f55(s3, s4);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseinline_table_entry() {\n    let s0, s1, s2, s3, s4, s5;\n\n    s0 = peg$currPos;\n    s1 = peg$parseinline_key();\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parseS();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parseS();\n      }\n      if (input.charCodeAt(peg$currPos) === 61) {\n        s3 = peg$c4;\n        peg$currPos++;\n      } else {\n        s3 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e5); }\n      }\n      if (s3 !== peg$FAILED) {\n        s4 = [];\n        s5 = peg$parseS();\n        while (s5 !== peg$FAILED) {\n          s4.push(s5);\n          s5 = peg$parseS();\n        }\n        s5 = peg$parsevalue();\n        if (s5 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f56(s1, s5);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseinline_sep() {\n    let s0;\n\n    s0 = peg$parseS();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parseNL();\n      if (s0 === peg$FAILED) {\n        s0 = peg$parsecomment();\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseinline_key() {\n    let s0, s1, s2, s3;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parseinline_dot_key_part();\n    if (s2 !== peg$FAILED) {\n      while (s2 !== peg$FAILED) {\n        s1.push(s2);\n        s2 = peg$parseinline_dot_key_part();\n      }\n    } else {\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = [];\n      s3 = peg$parseS();\n      while (s3 !== peg$FAILED) {\n        s2.push(s3);\n        s3 = peg$parseS();\n      }\n      s3 = peg$parsesimple_key();\n      if (s3 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f57(s1, s3);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$parsesimple_key();\n      if (s1 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s1 = peg$f58(s1);\n      }\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parseinline_dot_key_part() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    s1 = [];\n    s2 = peg$parseS();\n    while (s2 !== peg$FAILED) {\n      s1.push(s2);\n      s2 = peg$parseS();\n    }\n    s2 = peg$parsesimple_key();\n    if (s2 !== peg$FAILED) {\n      s3 = [];\n      s4 = peg$parseS();\n      while (s4 !== peg$FAILED) {\n        s3.push(s4);\n        s4 = peg$parseS();\n      }\n      if (input.charCodeAt(peg$currPos) === 46) {\n        s4 = peg$c3;\n        peg$currPos++;\n      } else {\n        s4 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e4); }\n      }\n      if (s4 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f59(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parsesimple_key() {\n    let s0;\n\n    s0 = peg$parsekey();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parsequoted_key();\n    }\n\n    return s0;\n  }\n\n  function peg$parsesecfragment() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    s1 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 46) {\n      s2 = peg$c3;\n      peg$currPos++;\n    } else {\n      s2 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e4); }\n    }\n    if (s2 !== peg$FAILED) {\n      s3 = [];\n      s4 = peg$parseDIGIT();\n      if (s4 !== peg$FAILED) {\n        while (s4 !== peg$FAILED) {\n          s3.push(s4);\n          s4 = peg$parseDIGIT();\n        }\n      } else {\n        s3 = peg$FAILED;\n      }\n      if (s3 !== peg$FAILED) {\n        s2 = [s2, s3];\n        s1 = s2;\n      } else {\n        peg$currPos = s1;\n        s1 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s1;\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s0 = input.substring(s0, peg$currPos);\n    } else {\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsedate_part() {\n    let s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;\n\n    s0 = peg$currPos;\n    s1 = peg$currPos;\n    s2 = peg$parseDIGIT();\n    if (s2 !== peg$FAILED) {\n      s3 = peg$parseDIGIT();\n      if (s3 !== peg$FAILED) {\n        s4 = peg$parseDIGIT();\n        if (s4 !== peg$FAILED) {\n          s5 = peg$parseDIGIT();\n          if (s5 !== peg$FAILED) {\n            if (input.charCodeAt(peg$currPos) === 45) {\n              s6 = peg$c24;\n              peg$currPos++;\n            } else {\n              s6 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e39); }\n            }\n            if (s6 !== peg$FAILED) {\n              s7 = peg$parseDIGIT();\n              if (s7 !== peg$FAILED) {\n                s8 = peg$parseDIGIT();\n                if (s8 !== peg$FAILED) {\n                  if (input.charCodeAt(peg$currPos) === 45) {\n                    s9 = peg$c24;\n                    peg$currPos++;\n                  } else {\n                    s9 = peg$FAILED;\n                    if (peg$silentFails === 0) { peg$fail(peg$e39); }\n                  }\n                  if (s9 !== peg$FAILED) {\n                    s10 = peg$parseDIGIT();\n                    if (s10 !== peg$FAILED) {\n                      s11 = peg$parseDIGIT();\n                      if (s11 !== peg$FAILED) {\n                        s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11];\n                        s1 = s2;\n                      } else {\n                        peg$currPos = s1;\n                        s1 = peg$FAILED;\n                      }\n                    } else {\n                      peg$currPos = s1;\n                      s1 = peg$FAILED;\n                    }\n                  } else {\n                    peg$currPos = s1;\n                    s1 = peg$FAILED;\n                  }\n                } else {\n                  peg$currPos = s1;\n                  s1 = peg$FAILED;\n                }\n              } else {\n                peg$currPos = s1;\n                s1 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s1;\n              s1 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s1;\n            s1 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s1;\n          s1 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s1;\n        s1 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s1;\n      s1 = peg$FAILED;\n    }\n    if (s1 !== peg$FAILED) {\n      s0 = input.substring(s0, peg$currPos);\n    } else {\n      s0 = s1;\n    }\n\n    return s0;\n  }\n\n  function peg$parsetime_part() {\n    let s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;\n\n    s0 = peg$currPos;\n    s1 = peg$currPos;\n    s2 = peg$currPos;\n    s3 = peg$parseDIGIT();\n    if (s3 !== peg$FAILED) {\n      s4 = peg$parseDIGIT();\n      if (s4 !== peg$FAILED) {\n        if (input.charCodeAt(peg$currPos) === 58) {\n          s5 = peg$c25;\n          peg$currPos++;\n        } else {\n          s5 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e40); }\n        }\n        if (s5 !== peg$FAILED) {\n          s6 = peg$parseDIGIT();\n          if (s6 !== peg$FAILED) {\n            s7 = peg$parseDIGIT();\n            if (s7 !== peg$FAILED) {\n              if (input.charCodeAt(peg$currPos) === 58) {\n                s8 = peg$c25;\n                peg$currPos++;\n              } else {\n                s8 = peg$FAILED;\n                if (peg$silentFails === 0) { peg$fail(peg$e40); }\n              }\n              if (s8 !== peg$FAILED) {\n                s9 = peg$parseDIGIT();\n                if (s9 !== peg$FAILED) {\n                  s10 = peg$parseDIGIT();\n                  if (s10 !== peg$FAILED) {\n                    s3 = [s3, s4, s5, s6, s7, s8, s9, s10];\n                    s2 = s3;\n                  } else {\n                    peg$currPos = s2;\n                    s2 = peg$FAILED;\n                  }\n                } else {\n                  peg$currPos = s2;\n                  s2 = peg$FAILED;\n                }\n              } else {\n                peg$currPos = s2;\n                s2 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s2;\n              s2 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s2;\n            s2 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s2;\n          s2 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s2;\n        s2 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s2;\n      s2 = peg$FAILED;\n    }\n    if (s2 !== peg$FAILED) {\n      s1 = input.substring(s1, peg$currPos);\n    } else {\n      s1 = s2;\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$parsesecfragment();\n      if (s2 === peg$FAILED) {\n        s2 = null;\n      }\n      peg$savedPos = s0;\n      s0 = peg$f60(s1, s2);\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$currPos;\n      s2 = peg$currPos;\n      s3 = peg$parseDIGIT();\n      if (s3 !== peg$FAILED) {\n        s4 = peg$parseDIGIT();\n        if (s4 !== peg$FAILED) {\n          if (input.charCodeAt(peg$currPos) === 58) {\n            s5 = peg$c25;\n            peg$currPos++;\n          } else {\n            s5 = peg$FAILED;\n            if (peg$silentFails === 0) { peg$fail(peg$e40); }\n          }\n          if (s5 !== peg$FAILED) {\n            s6 = peg$parseDIGIT();\n            if (s6 !== peg$FAILED) {\n              s7 = peg$parseDIGIT();\n              if (s7 !== peg$FAILED) {\n                s3 = [s3, s4, s5, s6, s7];\n                s2 = s3;\n              } else {\n                peg$currPos = s2;\n                s2 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s2;\n              s2 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s2;\n            s2 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s2;\n          s2 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s2;\n        s2 = peg$FAILED;\n      }\n      if (s2 !== peg$FAILED) {\n        s1 = input.substring(s1, peg$currPos);\n      } else {\n        s1 = s2;\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        peg$silentFails++;\n        if (input.charCodeAt(peg$currPos) === 58) {\n          s3 = peg$c25;\n          peg$currPos++;\n        } else {\n          s3 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e40); }\n        }\n        peg$silentFails--;\n        if (s3 === peg$FAILED) {\n          s2 = undefined;\n        } else {\n          peg$currPos = s2;\n          s2 = peg$FAILED;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f61(s1);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseoffset() {\n    let s0, s1, s2, s3, s4, s5, s6, s7;\n\n    s0 = peg$currPos;\n    s1 = input.charAt(peg$currPos);\n    if (s1.toLowerCase() === peg$c26) {\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e41); }\n    }\n    if (s1 !== peg$FAILED) {\n      peg$savedPos = s0;\n      s1 = peg$f62();\n    }\n    s0 = s1;\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$currPos;\n      s2 = input.charAt(peg$currPos);\n      if (peg$r1.test(s2)) {\n        peg$currPos++;\n      } else {\n        s2 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e6); }\n      }\n      if (s2 !== peg$FAILED) {\n        s3 = peg$parseDIGIT();\n        if (s3 !== peg$FAILED) {\n          s4 = peg$parseDIGIT();\n          if (s4 !== peg$FAILED) {\n            if (input.charCodeAt(peg$currPos) === 58) {\n              s5 = peg$c25;\n              peg$currPos++;\n            } else {\n              s5 = peg$FAILED;\n              if (peg$silentFails === 0) { peg$fail(peg$e40); }\n            }\n            if (s5 !== peg$FAILED) {\n              s6 = peg$parseDIGIT();\n              if (s6 !== peg$FAILED) {\n                s7 = peg$parseDIGIT();\n                if (s7 !== peg$FAILED) {\n                  s2 = [s2, s3, s4, s5, s6, s7];\n                  s1 = s2;\n                } else {\n                  peg$currPos = s1;\n                  s1 = peg$FAILED;\n                }\n              } else {\n                peg$currPos = s1;\n                s1 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s1;\n              s1 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s1;\n            s1 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s1;\n          s1 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s1;\n        s1 = peg$FAILED;\n      }\n      if (s1 !== peg$FAILED) {\n        s0 = input.substring(s0, peg$currPos);\n      } else {\n        s0 = s1;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsedatetime() {\n    let s0, s1, s2, s3, s4;\n\n    s0 = peg$currPos;\n    s1 = peg$parsedate_part();\n    if (s1 !== peg$FAILED) {\n      s2 = peg$parsedatetime_delim();\n      if (s2 !== peg$FAILED) {\n        s3 = peg$parsetime_part();\n        if (s3 !== peg$FAILED) {\n          s4 = peg$parseoffset();\n          if (s4 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f63(s1, s3, s4);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      s1 = peg$parsedate_part();\n      if (s1 !== peg$FAILED) {\n        s2 = peg$parsedatetime_delim();\n        if (s2 !== peg$FAILED) {\n          s3 = peg$parsetime_part();\n          if (s3 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f64(s1, s3);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n      if (s0 === peg$FAILED) {\n        s0 = peg$currPos;\n        s1 = peg$parsedate_part();\n        if (s1 !== peg$FAILED) {\n          s2 = peg$currPos;\n          peg$silentFails++;\n          s3 = peg$parsedatetime_delim();\n          peg$silentFails--;\n          if (s3 === peg$FAILED) {\n            s2 = undefined;\n          } else {\n            peg$currPos = s2;\n            s2 = peg$FAILED;\n          }\n          if (s2 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f65(s1);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n        if (s0 === peg$FAILED) {\n          s0 = peg$currPos;\n          s1 = peg$parsetime_part();\n          if (s1 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s1 = peg$f66(s1);\n          }\n          s0 = s1;\n        }\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parsedatetime_delim() {\n    let s0, s1, s2, s3;\n\n    s0 = input.charAt(peg$currPos);\n    if (s0.toLowerCase() === peg$c27) {\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e42); }\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 32) {\n        s1 = peg$c28;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e43); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        peg$silentFails++;\n        s3 = peg$parseDIGIT();\n        peg$silentFails--;\n        if (s3 !== peg$FAILED) {\n          peg$currPos = s2;\n          s2 = undefined;\n        } else {\n          s2 = peg$FAILED;\n        }\n        if (s2 !== peg$FAILED) {\n          s1 = [s1, s2];\n          s0 = s1;\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseS() {\n    let s0;\n\n    s0 = input.charAt(peg$currPos);\n    if (peg$r14.test(s0)) {\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e44); }\n    }\n\n    return s0;\n  }\n\n  function peg$parseNL() {\n    let s0, s1, s2;\n\n    if (input.charCodeAt(peg$currPos) === 10) {\n      s0 = peg$c29;\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e45); }\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.charCodeAt(peg$currPos) === 13) {\n        s1 = peg$c30;\n        peg$currPos++;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e46); }\n      }\n      if (s1 !== peg$FAILED) {\n        if (input.charCodeAt(peg$currPos) === 10) {\n          s2 = peg$c29;\n          peg$currPos++;\n        } else {\n          s2 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e45); }\n        }\n        if (s2 !== peg$FAILED) {\n          s1 = [s1, s2];\n          s0 = s1;\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    }\n\n    return s0;\n  }\n\n  function peg$parseNLS() {\n    let s0;\n\n    s0 = peg$parseNL();\n    if (s0 === peg$FAILED) {\n      s0 = peg$parseS();\n    }\n\n    return s0;\n  }\n\n  function peg$parseEOF() {\n    let s0, s1;\n\n    s0 = peg$currPos;\n    peg$silentFails++;\n    if (input.length > peg$currPos) {\n      s1 = input.charAt(peg$currPos);\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e14); }\n    }\n    peg$silentFails--;\n    if (s1 === peg$FAILED) {\n      s0 = undefined;\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n\n    return s0;\n  }\n\n  function peg$parseBOM() {\n    let s0;\n\n    if (input.charCodeAt(peg$currPos) === 65279) {\n      s0 = peg$c31;\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e47); }\n    }\n\n    return s0;\n  }\n\n  function peg$parseDIGIT() {\n    let s0;\n\n    s0 = input.charAt(peg$currPos);\n    if (peg$r10.test(s0)) {\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e30); }\n    }\n\n    return s0;\n  }\n\n  function peg$parseHEX() {\n    let s0;\n\n    s0 = input.charAt(peg$currPos);\n    if (peg$r11.test(s0)) {\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e31); }\n    }\n\n    return s0;\n  }\n\n  function peg$parseASCII_BASIC() {\n    let s0;\n\n    s0 = input.charAt(peg$currPos);\n    if (peg$r15.test(s0)) {\n      peg$currPos++;\n    } else {\n      s0 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e48); }\n    }\n\n    return s0;\n  }\n\n  function peg$parseESCAPED() {\n    let s0, s1, s2;\n\n    s0 = peg$currPos;\n    if (input.charCodeAt(peg$currPos) === 92) {\n      s1 = peg$c11;\n      peg$currPos++;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e13); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = input.charAt(peg$currPos);\n      if (peg$r16.test(s2)) {\n        peg$currPos++;\n      } else {\n        s2 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e49); }\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f67(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$parseESCAPED_UNICODE();\n    }\n\n    return s0;\n  }\n\n  function peg$parseESCAPED_UNICODE() {\n    let s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;\n\n    s0 = peg$currPos;\n    if (input.substr(peg$currPos, 2) === peg$c32) {\n      s1 = peg$c32;\n      peg$currPos += 2;\n    } else {\n      s1 = peg$FAILED;\n      if (peg$silentFails === 0) { peg$fail(peg$e50); }\n    }\n    if (s1 !== peg$FAILED) {\n      s2 = peg$currPos;\n      s3 = peg$currPos;\n      s4 = peg$parseHEX();\n      if (s4 !== peg$FAILED) {\n        s5 = peg$parseHEX();\n        if (s5 !== peg$FAILED) {\n          s6 = peg$parseHEX();\n          if (s6 !== peg$FAILED) {\n            s7 = peg$parseHEX();\n            if (s7 !== peg$FAILED) {\n              s8 = peg$parseHEX();\n              if (s8 !== peg$FAILED) {\n                s9 = peg$parseHEX();\n                if (s9 !== peg$FAILED) {\n                  s10 = peg$parseHEX();\n                  if (s10 !== peg$FAILED) {\n                    s11 = peg$parseHEX();\n                    if (s11 !== peg$FAILED) {\n                      s4 = [s4, s5, s6, s7, s8, s9, s10, s11];\n                      s3 = s4;\n                    } else {\n                      peg$currPos = s3;\n                      s3 = peg$FAILED;\n                    }\n                  } else {\n                    peg$currPos = s3;\n                    s3 = peg$FAILED;\n                  }\n                } else {\n                  peg$currPos = s3;\n                  s3 = peg$FAILED;\n                }\n              } else {\n                peg$currPos = s3;\n                s3 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s3;\n              s3 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s3;\n            s3 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s3;\n        s3 = peg$FAILED;\n      }\n      if (s3 !== peg$FAILED) {\n        s2 = input.substring(s2, peg$currPos);\n      } else {\n        s2 = s3;\n      }\n      if (s2 !== peg$FAILED) {\n        peg$savedPos = s0;\n        s0 = peg$f68(s2);\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n    } else {\n      peg$currPos = s0;\n      s0 = peg$FAILED;\n    }\n    if (s0 === peg$FAILED) {\n      s0 = peg$currPos;\n      if (input.substr(peg$currPos, 2) === peg$c33) {\n        s1 = peg$c33;\n        peg$currPos += 2;\n      } else {\n        s1 = peg$FAILED;\n        if (peg$silentFails === 0) { peg$fail(peg$e51); }\n      }\n      if (s1 !== peg$FAILED) {\n        s2 = peg$currPos;\n        s3 = peg$currPos;\n        s4 = peg$parseHEX();\n        if (s4 !== peg$FAILED) {\n          s5 = peg$parseHEX();\n          if (s5 !== peg$FAILED) {\n            s6 = peg$parseHEX();\n            if (s6 !== peg$FAILED) {\n              s7 = peg$parseHEX();\n              if (s7 !== peg$FAILED) {\n                s4 = [s4, s5, s6, s7];\n                s3 = s4;\n              } else {\n                peg$currPos = s3;\n                s3 = peg$FAILED;\n              }\n            } else {\n              peg$currPos = s3;\n              s3 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s3;\n            s3 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s3;\n          s3 = peg$FAILED;\n        }\n        if (s3 !== peg$FAILED) {\n          s2 = input.substring(s2, peg$currPos);\n        } else {\n          s2 = s3;\n        }\n        if (s2 !== peg$FAILED) {\n          peg$savedPos = s0;\n          s0 = peg$f69(s2);\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      } else {\n        peg$currPos = s0;\n        s0 = peg$FAILED;\n      }\n      if (s0 === peg$FAILED) {\n        s0 = peg$currPos;\n        if (input.substr(peg$currPos, 2) === peg$c34) {\n          s1 = peg$c34;\n          peg$currPos += 2;\n        } else {\n          s1 = peg$FAILED;\n          if (peg$silentFails === 0) { peg$fail(peg$e52); }\n        }\n        if (s1 !== peg$FAILED) {\n          s2 = peg$currPos;\n          s3 = peg$currPos;\n          s4 = peg$parseHEX();\n          if (s4 !== peg$FAILED) {\n            s5 = peg$parseHEX();\n            if (s5 !== peg$FAILED) {\n              s4 = [s4, s5];\n              s3 = s4;\n            } else {\n              peg$currPos = s3;\n              s3 = peg$FAILED;\n            }\n          } else {\n            peg$currPos = s3;\n            s3 = peg$FAILED;\n          }\n          if (s3 !== peg$FAILED) {\n            s2 = input.substring(s2, peg$currPos);\n          } else {\n            s2 = s3;\n          }\n          if (s2 !== peg$FAILED) {\n            peg$savedPos = s0;\n            s0 = peg$f70(s2);\n          } else {\n            peg$currPos = s0;\n            s0 = peg$FAILED;\n          }\n        } else {\n          peg$currPos = s0;\n          s0 = peg$FAILED;\n        }\n      }\n    }\n\n    return s0;\n  }\n\n\n  var nodes = [];\n  var inputText = input;\n\n  // Bound on how deeply arrays / inline tables may nest. The generated parser\n  // is recursive-descent, so nesting depth maps directly onto call-stack depth;\n  // without a limit, deeply nested input overflows the stack with an uncatchable\n  // RangeError instead of a normal parse error (GHSA-82x6-q7mm-w9cf).\n  var depth = 0;\n  var MAX_DEPTH = (options && options.maxDepth != null) ? options.maxDepth : 500;\n\n  function resolveLineCol(off) {\n    var line = 1, col = 1;\n    for (var i = 0; i < off; i++) {\n      if (inputText.charCodeAt(i) === 10) { line++; col = 1; }\n      else { col++; }\n    }\n    return { line: line, column: col };\n  }\n\n  function genError(err, off) {\n    var pos = resolveLineCol(off);\n    var ex = new Error(err);\n    ex.line = pos.line;\n    ex.column = pos.column;\n    throw ex;\n  }\n\n  function addNode(node) {\n    nodes.push(node);\n  }\n\n  function node(type, value, off, key) {\n    var obj = { type: type, value: value, offset: off };\n    if (key) obj.key = key;\n    return obj;\n  }\n\n  function validateDate(dateStr, off) {\n    var year = dateStr.charCodeAt(0) * 1000 + dateStr.charCodeAt(1) * 100 + dateStr.charCodeAt(2) * 10 + dateStr.charCodeAt(3) - 53328;\n    var month = (dateStr.charCodeAt(5) - 48) * 10 + dateStr.charCodeAt(6) - 48;\n    var day = (dateStr.charCodeAt(8) - 48) * 10 + dateStr.charCodeAt(9) - 48;\n    if (month < 1 || month > 12) {\n      genError(\"Invalid date: month \" + month + \" out of range.\", off);\n    }\n    var maxDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n    if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {\n      maxDays[1] = 29;\n    }\n    if (day < 1 || day > maxDays[month - 1]) {\n      genError(\"Invalid date: day \" + day + \" out of range for month \" + month + \".\", off);\n    }\n  }\n\n  function validateTime(timeStr, off) {\n    var hour = (timeStr.charCodeAt(0) - 48) * 10 + timeStr.charCodeAt(1) - 48;\n    var minute = (timeStr.charCodeAt(3) - 48) * 10 + timeStr.charCodeAt(4) - 48;\n    var second = (timeStr.charCodeAt(6) - 48) * 10 + timeStr.charCodeAt(7) - 48;\n    if (hour > 23) {\n      genError(\"Invalid time: hour \" + hour + \" out of range.\", off);\n    }\n    if (minute > 59) {\n      genError(\"Invalid time: minute \" + minute + \" out of range.\", off);\n    }\n    if (second > 59) {\n      genError(\"Invalid time: second \" + second + \" out of range.\", off);\n    }\n  }\n\n  function validateOffset(offsetStr, off) {\n    if (offsetStr === \"Z\" || offsetStr === \"z\") return;\n    var hour = (offsetStr.charCodeAt(1) - 48) * 10 + offsetStr.charCodeAt(2) - 48;\n    var minute = (offsetStr.charCodeAt(4) - 48) * 10 + offsetStr.charCodeAt(5) - 48;\n    if (hour > 23) {\n      genError(\"Invalid offset: hour \" + hour + \" out of range.\", off);\n    }\n    if (minute > 59) {\n      genError(\"Invalid offset: minute \" + minute + \" out of range.\", off);\n    }\n  }\n\n  function stripUnderscores(str) {\n    return str.indexOf('_') === -1 ? str : str.replace(/_/g, '');\n  }\n\n  function convertCodePoint(str) {\n    var num = parseInt(str, 16);\n\n    if (\n      num !== num ||\n      num < 0 ||\n      num > 0x10FFFF ||\n      (num > 0xD7FF && num < 0xE000)\n    ) {\n      genError(\"Invalid Unicode escape code: \" + str, offset());\n    } else {\n      return String.fromCodePoint(num);\n    }\n  }\n\n  peg$result = peg$startRuleFunction();\n\n  const peg$success = (peg$result !== peg$FAILED && peg$currPos === input.length);\n  function peg$throw() {\n    if (peg$result !== peg$FAILED && peg$currPos < input.length) {\n      peg$fail(peg$endExpectation());\n    }\n\n    throw peg$buildStructuredError(\n      peg$maxFailExpected,\n      peg$maxFailPos < input.length ? peg$getUnicode(peg$maxFailPos) : null,\n      peg$maxFailPos < input.length\n        ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)\n        : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)\n    );\n  }\n  if (options.peg$library) {\n    return /** @type {any} */ ({\n      peg$result,\n      peg$currPos,\n      peg$FAILED,\n      peg$maxFailExpected,\n      peg$maxFailPos,\n      peg$success,\n      peg$throw: peg$success ? undefined : peg$throw,\n    });\n  }\n  if (peg$success) {\n    return peg$result;\n  } else {\n    peg$throw();\n  }\n}\n\nmodule.exports = {\n  StartRules: [\"start\"],\n  SyntaxError: peg$SyntaxError,\n  parse: peg$parse,\n};\n","\"use strict\";\nfunction compile(nodes, inputText, options) {\n  options = options || {};\n  var temporal = null;\n  if (options.useTemporal) {\n    temporal = options.temporal || (typeof Temporal !== \"undefined\" ? Temporal : null);\n    if (!temporal) {\n      throw new Error(\n        \"The `useTemporal` option was set, but no Temporal implementation is available. \" +\n        \"Use a runtime with global `Temporal` support, or provide an implementation \" +\n        \"(e.g. from the `@js-temporal/polyfill` package) via the `temporal` option.\"\n      );\n    }\n  }\n\n  var assignedPaths = new Set();\n  var valueAssignments = new Set();\n  var explicitTablePaths = new Set();\n  var currentPath = [];\n  var ownedContainers = new WeakSet();\n  var data = createTable();\n  var context = data;\n\n  return reduce(nodes);\n\n  function reduce(nodes) {\n    var node;\n    for (var i = 0; i < nodes.length; i++) {\n      node = nodes[i];\n      switch (node.type) {\n      case \"Assign\":\n        assign(node);\n        break;\n      case \"ObjectPath\":\n        setPath(node);\n        break;\n      case \"ArrayPath\":\n        addTableArray(node);\n        break;\n      }\n    }\n\n    return data;\n  }\n\n  function resolveLineCol(off) {\n    var line = 1, col = 1;\n    for (var i = 0; i < off; i++) {\n      if (inputText.charCodeAt(i) === 10) { line++; col = 1; }\n      else { col++; }\n    }\n    return { line: line, column: col };\n  }\n\n  function genError(err, off) {\n    var pos = resolveLineCol(off);\n    var ex = new Error(err);\n    ex.line = pos.line;\n    ex.column = pos.column;\n    throw ex;\n  }\n\n  function assign(node) {\n    var keys = node.key;\n    var value = node.value;\n    var off = node.offset;\n\n    if (!Array.isArray(keys)) keys = [keys];\n\n    var reduced = reduceValueNode(value);\n\n    var target = context;\n    for (var i = 0; i < keys.length - 1; i++) {\n      var k = keys[i];\n      var intermediatePath = makeFullPath(keys.slice(0, i + 1));\n\n      if (typeof target[k] === \"undefined\") {\n        target[k] = createTable();\n        assignedPaths.add(intermediatePath);\n      } else if (typeof target[k] !== \"object\" || target[k] === null || Array.isArray(target[k])) {\n        genError(\"Cannot redefine existing key '\" + intermediatePath + \"'.\", off);\n      } else if (valueAssignments.has(intermediatePath)) {\n        genError(\"Cannot redefine existing key '\" + intermediatePath + \"'.\", off);\n      } else if (explicitTablePaths.has(intermediatePath) && intermediatePath !== pathKey(currentPath)) {\n        genError(\"Cannot use dotted keys to extend table '\" + intermediatePath + \"' defined elsewhere.\", off);\n      }\n      target = target[k];\n    }\n\n    var lastKey = keys[keys.length - 1];\n    var fullPath = makeFullPath(keys);\n\n    if (typeof target[lastKey] !== \"undefined\") {\n      genError(\"Cannot redefine existing key '\" + fullPath + \"'.\", off);\n    }\n\n    target[lastKey] = reduced;\n\n    assignedPaths.add(fullPath);\n    valueAssignments.add(fullPath);\n  }\n\n\n  function reduceValueNode(node) {\n    if (node.type === \"Array\") {\n      return reduceArray(node.value);\n    } else if (node.type === \"InlineTable\") {\n      return reduceInlineTableNode(node.value);\n    } else if (temporal) {\n      switch (node.type) {\n      case \"Date\":\n        return temporal.ZonedDateTime.from(\n          truncateFractionalSeconds(node.raw) + node.tz +\n          \"[\" + (node.tz === \"Z\" ? \"UTC\" : node.tz) + \"]\"\n        );\n      case \"LocalDateTime\":\n        return temporal.PlainDateTime.from(truncateFractionalSeconds(node.value));\n      case \"LocalDate\":\n        return temporal.PlainDate.from(node.value);\n      case \"LocalTime\":\n        return temporal.PlainTime.from(truncateFractionalSeconds(node.value));\n      }\n    }\n    return node.value;\n  }\n\n  // TOML allows arbitrary fractional-second precision (implementations may\n  // truncate); Temporal rejects more than 9 digits (nanoseconds).\n  function truncateFractionalSeconds(str) {\n    return str.replace(/\\.(\\d{9})\\d+/, \".$1\");\n  }\n\n  function reduceInlineTableNode(values) {\n    var obj = createTable();\n    var definedKeys = new Set();\n\n    for (var i = 0; i < values.length; i++) {\n      var val = values[i];\n      if (val.type !== \"InlineTableValue\") continue;\n\n      var keys = val.key;\n      if (!Array.isArray(keys)) keys = [keys];\n\n      var reduced = reduceValueNode(val.value);\n      setNestedKey(obj, keys, reduced, val.offset, definedKeys);\n\n      definedKeys.add(pathKey(keys));\n    }\n\n    return obj;\n  }\n\n  function setNestedKey(obj, keys, value, off, definedKeys) {\n    for (var i = 0; i < keys.length - 1; i++) {\n      var k = keys[i];\n      var intermediatePath = pathKey(keys.slice(0, i + 1));\n      if (typeof obj[k] === \"undefined\") {\n        obj[k] = createTable();\n      } else if (typeof obj[k] !== \"object\" || obj[k] === null || Array.isArray(obj[k])) {\n        genError(\"Cannot redefine existing key '\" + intermediatePath + \"'.\", off);\n      } else if (definedKeys && definedKeys.has(intermediatePath)) {\n        genError(\"Cannot extend inline table '\" + intermediatePath + \"'.\", off);\n      }\n      obj = obj[k];\n    }\n    var lastKey = keys[keys.length - 1];\n    if (typeof obj[lastKey] !== \"undefined\") {\n      genError(\"Cannot redefine existing key '\" + pathKey(keys) + \"'.\", off);\n    }\n    obj[lastKey] = value;\n  }\n\n  function setPath(node) {\n    var path = node.value;\n    var quotedPath = path.map(quoteDottedString).join(\".\");\n    var off = node.offset;\n\n    if (assignedPaths.has(quotedPath)) {\n      genError(\"Cannot redefine existing key '\" + path + \"'.\", off);\n    }\n    assignedPaths.add(quotedPath);\n    explicitTablePaths.add(quotedPath);\n    context = deepRef(data, path, createTable(), off);\n    currentPath = path;\n  }\n\n  function addTableArray(node) {\n    var path = node.value;\n    var quotedPath = path.map(quoteDottedString).join(\".\");\n    var off = node.offset;\n\n    if (valueAssignments.has(quotedPath)) {\n      genError(\"Cannot append to statically defined array '\" + quotedPath + \"'.\", off);\n    }\n\n    // Clear this table array path and paths nested under it.\n    assignedPaths.forEach(function(p) {\n      if (isSameOrSubPath(p, quotedPath)) assignedPaths.delete(p);\n    });\n    valueAssignments.forEach(function(p) {\n      if (isSameOrSubPath(p, quotedPath)) valueAssignments.delete(p);\n    });\n    assignedPaths.add(quotedPath);\n    context = deepRef(data, path, createTableArray(), off);\n    currentPath = path;\n\n    if (context instanceof Array) {\n      var newObj = createTable();\n      context.push(newObj);\n      context = newObj;\n    } else {\n      genError(\"Cannot redefine existing key '\" + path + \"'.\", off);\n    }\n  }\n\n  function deepRef(start, keys, value, off) {\n    var ctx = start;\n\n    for (var i = 0; i < keys.length; i++) {\n      var key = keys[i];\n      var traversedPath = pathKey(keys.slice(0, i + 1));\n      if (typeof ctx[key] === \"undefined\") {\n        if (i === keys.length - 1) {\n          ctx[key] = value;\n        } else {\n          ctx[key] = createTable();\n        }\n      } else if (i !== keys.length - 1 && valueAssignments.has(traversedPath)) {\n        genError(\"Cannot redefine existing key '\" + traversedPath + \"'.\", off);\n      }\n\n      ctx = ctx[key];\n      if (i < keys.length - 1) {\n        if (!isOwnedContainer(ctx)) {\n          genError(\"Cannot redefine existing key '\" + traversedPath + \"'.\", off);\n        }\n        if (ctx instanceof Array) {\n          if (!ctx.length) {\n            genError(\"Cannot redefine existing key '\" + traversedPath + \"'.\", off);\n          }\n          ctx = ctx[ctx.length - 1];\n          if (!isOwnedContainer(ctx)) {\n            genError(\"Cannot redefine existing key '\" + traversedPath + \"'.\", off);\n          }\n        }\n      }\n    }\n\n    return ctx;\n  }\n\n  function reduceArray(array) {\n    return array.map(reduceValueNode);\n  }\n\n  function quoteDottedString(str) {\n    if (str.indexOf(\".\") > -1) {\n      return \"\\\"\" + str + \"\\\"\";\n    } else {\n      return str;\n    }\n  }\n\n  function createTable() {\n    var table = Object.create(null);\n    ownedContainers.add(table);\n    return table;\n  }\n\n  function createTableArray() {\n    var tableArray = [];\n    ownedContainers.add(tableArray);\n    return tableArray;\n  }\n\n  function isOwnedContainer(value) {\n    return value !== null && typeof value === \"object\" && ownedContainers.has(value);\n  }\n\n  function pathKey(keys) {\n    return keys.map(quoteDottedString).join(\".\");\n  }\n\n  function makeFullPath(keys) {\n    return pathKey(currentPath.concat(keys));\n  }\n\n  function isSameOrSubPath(path, prefix) {\n    return path === prefix || path.indexOf(prefix + \".\") === 0;\n  }\n}\n\nmodule.exports = {\n  compile: compile\n};\n","var parser = require('./lib/parser');\nvar compiler = require('./lib/compiler');\n\nmodule.exports = {\n  parse: function(input, options) {\n    var str = input.toString();\n    var nodes = parser.parse(str, options);\n    return compiler.compile(nodes, str, options);\n  }\n};\n","/**\n * Parses raw command-line strings into typed values.\n *\n * A `Primitive<A>` receives one string and returns an `Effect` that either\n * produces an `A` or fails with a parser message. `Argument` and `Flag` build\n * on these primitives to add names, aliases, defaults, prompts, configuration\n * fallbacks, repetition, and help metadata. Primitive parsers cover common\n * scalar values, paths, files, structured config files, schema-decoded input,\n * redacted values, and key-value pairs.\n *\n * @since 4.0.0\n */\nimport * as Ini from \"ini\";\nimport * as Toml from \"toml\";\nimport * as Yaml from \"yaml\";\nimport * as Config from \"../../Config.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as FileSystem from \"../../FileSystem.js\";\nimport { format } from \"../../Formatter.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Path from \"../../Path.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Schema from \"../../Schema.js\";\nconst TypeId = \"~effect/cli/Primitive\";\nconst Proto = {\n  [TypeId]: {\n    _A: identity\n  }\n};\n/** @internal */\nexport const isTrueValue = /*#__PURE__*/Schema.is(Config.TrueValues);\n/** @internal */\nexport const isFalseValue = /*#__PURE__*/Schema.is(Config.FalseValues);\n/** @internal */\nexport const isBoolean = p => p._tag === \"Boolean\";\nconst makePrimitive = (tag, parse) => Object.assign(Object.create(Proto), {\n  _tag: tag,\n  parse\n});\nconst makeSchemaPrimitive = (tag, schema) => {\n  const toCodecStringTree = Schema.toCodecStringTree(schema);\n  const decode = Schema.decodeUnknownEffect(toCodecStringTree);\n  return makePrimitive(tag, value => Effect.mapError(decode(value), error => error.message));\n};\n/**\n * Creates a primitive that parses boolean values from string input.\n *\n * **Details**\n *\n * Recognizes various forms of true/false values:\n * - True values: \"true\", \"1\", \"y\", \"yes\", \"on\"\n * - False values: \"false\", \"0\", \"n\", \"no\", \"off\"\n *\n * **Example** (Parsing boolean values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseBoolean = Effect.all([\n *   Primitive.boolean.parse(\"true\"),\n *   Primitive.boolean.parse(\"yes\"),\n *   Primitive.boolean.parse(\"false\"),\n *   Primitive.boolean.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseBoolean.pipe(Effect.provide(CliTestLayer))) // => [true, true, false, false]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const boolean = /*#__PURE__*/makeSchemaPrimitive(\"Boolean\", Config.Boolean);\n/**\n * Creates a primitive that parses floating-point numbers from string input.\n *\n * **Example** (Parsing floating-point numbers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseFloat = Effect.all([\n *   Primitive.float.parse(\"3.14\"),\n *   Primitive.float.parse(\"-42.5\"),\n *   Primitive.float.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseFloat.pipe(Effect.provide(CliTestLayer))) // => [3.14, -42.5, 0]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const float = /*#__PURE__*/makeSchemaPrimitive(\"Float\", Schema.Finite);\n/**\n * Creates a primitive that parses integer numbers from string input.\n *\n * **Example** (Parsing integer values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseInteger = Effect.all([\n *   Primitive.integer.parse(\"42\"),\n *   Primitive.integer.parse(\"-123\"),\n *   Primitive.integer.parse(\"0\")\n * ])\n *\n * await Effect.runPromise(parseInteger.pipe(Effect.provide(CliTestLayer))) // => [42, -123, 0]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const integer = /*#__PURE__*/makeSchemaPrimitive(\"Integer\", Schema.Int);\n/**\n * Creates a primitive that parses Date objects from string input.\n *\n * **Example** (Parsing date values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseDate = Effect.gen(function*() {\n *   const result = yield* Primitive.date.parse(\"2023-12-25\")\n *   return result.toISOString()\n * })\n *\n * await Effect.runPromise(parseDate.pipe(Effect.provide(CliTestLayer))) // => \"2023-12-25T00:00:00.000Z\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const date = /*#__PURE__*/makeSchemaPrimitive(\"Date\", Schema.Date);\n/**\n * Creates a primitive that accepts any string value without validation.\n *\n * **Example** (Parsing string values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseString = Effect.all([\n *   Primitive.string.parse(\"hello world\"),\n *   Primitive.string.parse(\"\"),\n *   Primitive.string.parse(\"123\")\n * ])\n *\n * await Effect.runPromise(parseString.pipe(Effect.provide(CliTestLayer))) // => [\"hello world\", \"\", \"123\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const string = /*#__PURE__*/makePrimitive(\"String\", value => Effect.succeed(value));\n/**\n * Creates a primitive that accepts only specific choice values mapped to custom types.\n *\n * **Example** (Parsing choices)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\"\n *\n * const logLevelPrimitive = Primitive.choice<LogLevel>([\n *   [\"debug\", \"debug\"],\n *   [\"info\", \"info\"],\n *   [\"warn\", \"warn\"],\n *   [\"error\", \"error\"]\n * ])\n *\n * const parseLogLevel = Effect.all([\n *   logLevelPrimitive.parse(\"info\"),\n *   logLevelPrimitive.parse(\"debug\")\n * ])\n *\n * await Effect.runPromise(parseLogLevel.pipe(Effect.provide(CliTestLayer))) // => [\"info\", \"debug\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choice = choices => {\n  const choiceMap = new Map(choices);\n  const validChoices = choices.map(([key]) => format(key)).join(\" | \");\n  const primitive = makePrimitive(\"Choice\", value => {\n    if (choiceMap.has(value)) {\n      return Effect.succeed(choiceMap.get(value));\n    }\n    return Effect.fail(validChoices);\n  });\n  return Object.assign(primitive, {\n    choiceKeys: choices.map(([key]) => key)\n  });\n};\n/**\n * Creates a primitive that validates and resolves file system paths.\n *\n * **Example** (Parsing file system paths)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const services = Layer.mergeAll(\n *   Path.layer,\n *   FileSystem.layerNoop({\n *     exists: () => Effect.succeed(true),\n *     stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info)\n *   }),\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   const filePrimitive = Primitive.path(\"file\", true)\n *   const filePath = yield* filePrimitive.parse(\"./package.json\")\n *   return filePath.endsWith(\"/package.json\")\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const path = (pathType, mustExist) => makePrimitive(\"Path\", Effect.fnUntraced(function* (value) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  // Resolve the path to absolute\n  const absolutePath = path.isAbsolute(value) ? value : path.resolve(value);\n  // Check if path exists\n  const exists = yield* Effect.mapError(fs.exists(absolutePath), error => `Failed to check path existence: ${error.message}`);\n  // Validate existence requirements\n  if (mustExist === true && !exists) {\n    return yield* Effect.fail(`Path does not exist: ${absolutePath}`);\n  }\n  // Validate path type if it exists\n  if (exists && pathType !== \"either\") {\n    const stat = yield* Effect.mapError(fs.stat(absolutePath), error => `Failed to stat path: ${error.message}`);\n    if (pathType === \"file\" && stat.type !== \"File\") {\n      return yield* Effect.fail(`Path is not a file: ${absolutePath}`);\n    }\n    if (pathType === \"directory\" && stat.type !== \"Directory\") {\n      return yield* Effect.fail(`Path is not a directory: ${absolutePath}`);\n    }\n  }\n  return absolutePath;\n}));\n/**\n * Creates a primitive that wraps string input in `Redacted`.\n *\n * **Details**\n *\n * The wrapped value is hidden when formatted or inspected, while the original\n * string remains available through the `Redacted` API when explicitly needed.\n *\n * **Example** (Parsing redacted values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Redacted, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseRedacted = Effect.gen(function*() {\n *   const result = yield* Primitive.redacted.parse(\"secret-password\")\n *   return [Redacted.value(result), String(result)] as const\n * })\n *\n * await Effect.runPromise(parseRedacted.pipe(Effect.provide(CliTestLayer))) // => [\"secret-password\", \"<redacted>\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const redacted = /*#__PURE__*/makePrimitive(\"Redacted\", value => Effect.succeed(Redacted.make(value)));\n/**\n * Creates a primitive that reads and returns the contents of a file as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const services = Layer.mergeAll(\n *   Path.layer,\n *   FileSystem.layerNoop({\n *     exists: () => Effect.succeed(true),\n *     stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n *     readFileString: () => Effect.succeed('{\"private\":true}')\n *   }),\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const readConfigFile = Effect.gen(function*() {\n *   const content = yield* Primitive.fileText.parse(\"./package.json\")\n *   return JSON.parse(content) as { private: boolean }\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(readConfigFile) // => { private: true }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileText = /*#__PURE__*/makePrimitive(\"FileText\", /*#__PURE__*/Effect.fnUntraced(function* (filePath) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  // Resolve to absolute path\n  const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);\n  // Check if file exists\n  const exists = yield* Effect.mapError(fs.exists(absolutePath), error => `Failed to check file existence: ${error.message}`);\n  if (!exists) {\n    return yield* Effect.fail(`File does not exist: ${absolutePath}`);\n  }\n  // Check if it's actually a file\n  const stat = yield* Effect.mapError(fs.stat(absolutePath), error => `Failed to stat file: ${error.message}`);\n  if (stat.type !== \"File\") {\n    return yield* Effect.fail(`Path is not a file: ${absolutePath}`);\n  }\n  // Read file content\n  const content = yield* Effect.mapError(fs.readFileString(absolutePath), error => `Failed to read file: ${error.message}`);\n  return content;\n}));\nconst fileParsers = {\n  ini: content => Ini.parse(content),\n  json: content => JSON.parse(content),\n  toml: content => Toml.parse(content),\n  yml: content => Yaml.parse(content),\n  yaml: content => Yaml.parse(content)\n};\n/**\n * Creates a primitive that reads a file and parses its content as structured\n * data.\n *\n * **Details**\n *\n * The parser is selected from `options.format` when provided, otherwise from\n * the file extension. Supported formats include INI, JSON, TOML, YAML, and YML.\n *\n * **Example** (Parsing file content)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const services = Layer.mergeAll(\n *   Path.layer,\n *   FileSystem.layerNoop({\n *     exists: () => Effect.succeed(true),\n *     stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n *     readFileString: () => Effect.succeed('{\"private\":true}')\n *   }),\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const jsonFilePrimitive = Primitive.fileParse({ format: \"json\" })\n *\n * const loadConfig = Effect.gen(function*() {\n *   const config = yield* jsonFilePrimitive.parse(\"./package.json\")\n *   return config as { private: boolean }\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(loadConfig) // => { private: true }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileParse = options => {\n  return makePrimitive(\"FileParse\", Effect.fnUntraced(function* (filePath) {\n    const fileFormat = options?.format ?? filePath.split(\".\").pop();\n    const parser = fileParsers[fileFormat];\n    if (parser === undefined) {\n      return yield* Effect.fail(`Unsupported file format: ${fileFormat}`);\n    }\n    const content = yield* fileText.parse(filePath);\n    return yield* Effect.try({\n      try: () => parser(content),\n      catch: error => `Failed to parse '.${fileFormat}' file content: ${error}`\n    });\n  }));\n};\n/**\n * Reads and parses file content using the specified schema.\n *\n * **Example** (Parsing file content with a schema)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Schema, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const services = Layer.mergeAll(\n *   Path.layer,\n *   FileSystem.layerNoop({\n *     exists: () => Effect.succeed(true),\n *     stat: () => Effect.succeed({ type: \"File\" } as FileSystem.File.Info),\n *     readFileString: () => Effect.succeed('{\"private\":true}')\n *   }),\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const ConfigSchema = Schema.Struct({\n *   private: Schema.Boolean\n * })\n *\n * const jsonConfigPrimitive = Primitive.fileSchema(ConfigSchema, {\n *   format: \"json\"\n * })\n *\n * const loadConfig = Effect.gen(function*() {\n *   return yield* jsonConfigPrimitive.parse(\"./package.json\")\n * }).pipe(Effect.provide(services))\n *\n * await Effect.runPromise(loadConfig) // => { private: true }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileSchema = (schema, options) => {\n  const decode = Schema.decodeUnknownEffect(schema);\n  return makePrimitive(\"FileSchema\", Effect.fnUntraced(function* (filePath) {\n    const content = yield* fileParse(options).parse(filePath);\n    return yield* Effect.mapError(decode(content), error => options?.errorFormatter?.(error.issue) ?? error.toString());\n  }));\n};\n/**\n * Parses a single `key=value` pair into a record object.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parseKeyValue = Effect.all([\n *   Primitive.keyValuePair.parse(\"name=john\"),\n *   Primitive.keyValuePair.parse(\"port=3000\"),\n *   Primitive.keyValuePair.parse(\"debug=true\")\n * ])\n *\n * const result = await Effect.runPromise(parseKeyValue.pipe(Effect.provide(CliTestLayer)))\n * result // => [{ name: \"john\" }, { port: \"3000\" }, { debug: \"true\" }]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const keyValuePair = /*#__PURE__*/makePrimitive(\"KeyValuePair\", /*#__PURE__*/Effect.fnUntraced(function* (value) {\n  const parts = value.split(\"=\");\n  if (parts.length !== 2) {\n    return yield* Effect.fail(`Invalid key=value format. Expected format: key=value, got: ${value}`);\n  }\n  const [key, val] = parts;\n  if (!key || !val) {\n    return yield* Effect.fail(`Invalid key=value format. Both key and value must be non-empty. Got: ${value}`);\n  }\n  return {\n    [key]: val\n  };\n}));\n/**\n * Creates a sentinel primitive that always fails to parse a value.\n *\n * **When to use**\n *\n * Use when you need a CLI primitive for flags that do not accept values.\n *\n * **Example** (Rejecting option values)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Primitive } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   // This will always fail - useful for boolean flags\n *   return yield* Primitive.none.parse(\"any-value\")\n * })\n *\n * await Effect.runPromise(Effect.flip(program).pipe(Effect.provide(CliTestLayer))) // => \"This option does not accept values\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const none = /*#__PURE__*/makePrimitive(\"None\", () => Effect.fail(\"This option does not accept values\"));\n/**\n * Gets a human-readable type name for a primitive.\n *\n * **When to use**\n *\n * Use when you need the display type name for a `Primitive`, such as when\n * generating CLI help documentation.\n *\n * **Example** (Getting primitive type names)\n *\n * ```ts import.meta.vitest\n * import { Primitive } from \"effect/unstable/cli\"\n *\n * Primitive.getTypeName(Primitive.string) // => \"string\"\n * Primitive.getTypeName(Primitive.integer) // => \"integer\"\n * Primitive.getTypeName(Primitive.boolean) // => \"boolean\"\n * Primitive.getTypeName(Primitive.date) // => \"date\"\n * Primitive.getTypeName(Primitive.keyValuePair) // => \"key=value\"\n *\n * const logLevelChoice = Primitive.choice([\n *   [\"debug\", \"debug\"],\n *   [\"info\", \"info\"]\n * ])\n * Primitive.getTypeName(logLevelChoice) // => \"choice\"\n * ```\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getTypeName = primitive => {\n  switch (primitive._tag) {\n    case \"Boolean\":\n      return \"boolean\";\n    case \"String\":\n      return \"string\";\n    case \"Integer\":\n      return \"integer\";\n    case \"Float\":\n      return \"number\";\n    case \"Date\":\n      return \"date\";\n    case \"Path\":\n      return \"path\";\n    case \"Choice\":\n      return \"choice\";\n    case \"Redacted\":\n      return \"string\";\n    case \"FileText\":\n      return \"file\";\n    case \"FileParse\":\n      return \"file\";\n    case \"FileSchema\":\n      return \"file\";\n    case \"KeyValuePair\":\n      return \"key=value\";\n    case \"None\":\n      return \"none\";\n    default:\n      return \"value\";\n  }\n};\n/** @internal */\nexport const getChoiceKeys = primitive => primitive._tag === \"Choice\" ? primitive.choiceKeys : undefined;\n//# sourceMappingURL=Primitive.js.map","/**\n * Internal ANSI escape sequence helpers used by the unstable CLI rendering\n * implementation. This module centralizes the control codes for text styling,\n * cursor movement, line erasing, and terminal notifications so renderers can\n * compose terminal output without scattering raw escape sequences throughout\n * the CLI internals.\n *\n * The helpers deliberately work with plain strings because terminal rendering\n * is sensitive to ordering: style codes must be reset after annotated text,\n * cursor operations must account for one-based terminal coordinates, and line\n * clearing usually needs to preserve the cursor position expected by the next\n * frame.\n */\nconst ESC = \"\\x1B[\";\nconst BEL = \"\\x07\";\nconst SEP = \";\";\n/** @internal */\nexport const reset = `${ESC}0m`;\n/** @internal */\nexport const bold = `${ESC}1m`;\n/** @internal */\nexport const italicized = `${ESC}3m`;\n/** @internal */\nexport const underlined = `${ESC}4m`;\n/** @internal */\nexport const strikethrough = `${ESC}9m`;\n/** @internal */\nexport const cursorShow = `${ESC}?25h`;\n/** @internal */\nexport const cursorHide = `${ESC}?25l`;\n/** @internal */\nexport const cursorLeft = `${ESC}G`;\n/** @internal */\nexport const cursorSavePosition = `${ESC}s`;\n/** @internal */\nexport const cursorRestorePosition = `${ESC}u`;\n/** @internal */\nexport const eraseLine = `${ESC}2K`;\n/** @internal */\nexport const beep = BEL;\n/** @internal */\nexport const red = `${ESC}31m`;\n/** @internal */\nexport const green = `${ESC}32m`;\n/** @internal */\nexport const magenta = `${ESC}35m`;\n/** @internal */\nexport const white = `${ESC}37m`;\n/** @internal */\nexport const blackBright = `${ESC}90m`;\n/** @internal */\nexport const cyanBright = `${ESC}96m`;\nexport const annotate = (text, ...styles) => {\n  const flat = styles.flat();\n  return `${flat.join(\"\")}${text}${reset}`;\n};\nexport const combine = (...styles) => styles;\n/** @internal */\nexport const cursorTo = (column, row) => {\n  if (row === undefined) {\n    return `\\x1b${Math.max(column + 1, 0)} G`;\n  }\n  return `\\x1b${row + 1}${SEP}${Math.max(column + 1, 0)} H`;\n};\n/** @internal */\nexport const cursorDown = (lines = 1) => {\n  return `${ESC}${lines}B`;\n};\n/** @internal */\nexport const cursorMove = (column, row = 0) => {\n  let command = \"\";\n  if (row < 0) {\n    command += `${ESC}${-row}A`;\n  }\n  if (row > 0) {\n    command += `${ESC}${row}B`;\n  }\n  if (column > 0) {\n    command += `${ESC}${column}C`;\n  }\n  if (column < 0) {\n    command += `${ESC}${-column}D`;\n  }\n  return command;\n};\n/** @internal */\nexport const eraseLines = rows => {\n  let command = \"\";\n  for (let i = 0; i < rows; i++) {\n    command += `${ESC}2K` + (i < rows - 1 ? `${ESC}1A` : \"\");\n  }\n  if (rows > 0) {\n    command += `${ESC}G`;\n  }\n  return command;\n};\n//# sourceMappingURL=ansi.js.map","/**\n * Builds interactive terminal prompts for CLI applications.\n *\n * A `Prompt<A>` describes a small terminal UI that renders frames, reads\n * keyboard input, validates responses, and eventually produces an `A`. Prompts\n * can ask for simple values, selections, lists, files, hidden text, or custom\n * interactions. This module includes prompt constructors, tools for combining\n * and transforming prompt output, and support for running prompts through the\n * `Terminal` service.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Effectable from \"../../Effectable.js\";\nimport * as FileSystem from \"../../FileSystem.js\";\nimport { dual, pipe } from \"../../Function.js\";\nimport * as EffectNumber from \"../../Number.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Path from \"../../Path.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Terminal from \"../../Terminal.js\";\nimport * as Ansi from \"./internal/ansi.js\";\nconst TypeId = \"~effect/cli/Prompt\";\n/**\n * Returns `true` if the provided value is a `Prompt`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isPrompt = u => Predicate.hasProperty(u, TypeId);\nconst defaultFigures = {\n  arrowUp: \"↑\",\n  arrowDown: \"↓\",\n  arrowLeft: \"←\",\n  arrowRight: \"→\",\n  radioOn: \"◉\",\n  radioOff: \"◯\",\n  checkboxOn: \"☒\",\n  checkboxOff: \"☐\",\n  tick: \"✔\",\n  cross: \"✖\",\n  ellipsis: \"…\",\n  pointerSmall: \"›\",\n  line: \"─\",\n  pointer: \"❯\"\n};\nconst windowsFigures = {\n  arrowUp: defaultFigures.arrowUp,\n  arrowDown: defaultFigures.arrowDown,\n  arrowLeft: defaultFigures.arrowLeft,\n  arrowRight: defaultFigures.arrowRight,\n  radioOn: \"(*)\",\n  radioOff: \"( )\",\n  checkboxOn: \"[*]\",\n  checkboxOff: \"[ ]\",\n  tick: \"√\",\n  cross: \"×\",\n  ellipsis: \"...\",\n  pointerSmall: \"»\",\n  line: \"─\",\n  pointer: \">\"\n};\n/** @internal */\nexport const platformFigures = /*#__PURE__*/Effect.map(/*#__PURE__*/Effect.sync(() => process.platform === \"win32\"), isWindows => isWindows ? windowsFigures : defaultFigures);\n/**\n * Runs all the provided prompts in sequence respecting the structure provided\n * in input.\n *\n * **Details**\n *\n * Supports either a tuple / iterable of prompts or a record / struct of prompts\n * as an argument.\n *\n * **Example** (Collecting prompt results)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Terminal } from \"effect\"\n * import { Prompt } from \"effect/unstable/cli\"\n *\n * const terminal = Terminal.make({\n *   columns: Effect.succeed(80),\n *   rows: Effect.succeed(24),\n *   readInput: Effect.succeed({} as never),\n *   readLine: Effect.die(\"unused\"),\n *   display: () => Effect.void\n * })\n * const services = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Layer.succeed(Terminal.Terminal, terminal)\n * )\n *\n * const username = Prompt.succeed(\"alice\")\n * const password = Prompt.succeed(\"secret\")\n *\n * const allWithTuple = Prompt.all([username, password])\n *\n * const allWithRecord = Prompt.all({ username, password })\n *\n * await Effect.runPromise(Effect.provide(allWithTuple, services)) // => [\"alice\", \"secret\"]\n * await Effect.runPromise(Effect.provide(allWithRecord, services)) // => { username: \"alice\", password: \"secret\" }\n * ```\n *\n * @category combining\n * @since 4.0.0\n */\nexport const all = function () {\n  if (arguments.length === 1) {\n    if (isPrompt(arguments[0])) {\n      return map(arguments[0], x => [x]);\n    } else if (Array.isArray(arguments[0])) {\n      return allTupled(arguments[0]);\n    } else {\n      const entries = Object.entries(arguments[0]);\n      let result = map(entries[0][1], value => ({\n        [entries[0][0]]: value\n      }));\n      if (entries.length === 1) {\n        return result;\n      }\n      const rest = entries.slice(1);\n      for (const [key, prompt] of rest) {\n        result = result.pipe(flatMap(record => prompt.pipe(map(value => ({\n          ...record,\n          [key]: value\n        })))));\n      }\n      return result;\n    }\n  }\n  return allTupled(arguments[0]);\n};\nconst annotateLine = line => Ansi.annotate(line, Ansi.bold);\nconst annotateErrorLine = line => Ansi.annotate(line, Ansi.combine(Ansi.italicized, Ansi.red));\n/**\n * Creates a confirmation prompt that asks the user to choose a boolean yes/no\n * value.\n *\n * **When to use**\n *\n * Use to ask for a yes/no answer that can be submitted directly.\n *\n * **Details**\n *\n * `initial` defaults to `false`. Enter submits the current default, yes-style\n * input submits `true`, no-style input submits `false`, and other input beeps.\n *\n * @see {@link toggle} for an interactive switch-before-submit boolean prompt\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const confirm = options => {\n  const opts = {\n    initial: false,\n    ...options,\n    label: {\n      confirm: \"yes\",\n      deny: \"no\",\n      ...options.label\n    },\n    placeholder: {\n      defaultConfirm: \"(Y/n)\",\n      defaultDeny: \"(y/N)\",\n      ...options.placeholder\n    }\n  };\n  const initialState = {\n    value: opts.initial\n  };\n  return custom(initialState, {\n    render: handleConfirmRender(opts),\n    process: input => handleConfirmProcess(input, opts.initial),\n    clear: handleConfirmClear(opts)\n  });\n};\n/**\n * Creates a custom `Prompt` from the specified initial state and handlers.\n *\n * **Details**\n *\n * The initial state can either be a pure value or an `Effect`. This is\n * particularly useful when the initial state of the `Prompt` must be computed\n * by performing an effectful computation, such as reading data from the file\n * system. A `Prompt` runs as a render loop: `render` returns ANSI output for\n * the current frame, the `Terminal` obtains user input, `process` returns the\n * next prompt action, and `clear` returns ANSI output used to clear the previous\n * frame.\n *\n * Optionally, an external `events` dequeue can be provided as the third\n * argument. When present, the render loop will race user input against events\n * from the dequeue, allowing background events to trigger re-renders without\n * waiting for a keypress. When an event is received from the dequeue, the\n * `receive` handler is called instead of `process`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const custom = (initialState, ...args) => {\n  const [events, handlers] = args.length === 1 ? [undefined, args[0]] : [args[0], args[1]];\n  const op = Object.create(proto);\n  op._tag = \"Loop\";\n  op.initialState = initialState;\n  op.render = handlers.render;\n  op.process = handlers.process;\n  op.clear = handlers.clear;\n  op.events = events;\n  return op;\n};\n/**\n * Creates a date prompt that lets the user edit a formatted date value and\n * validates the final `Date` before submission.\n *\n * **Details**\n *\n * `initial` defaults to the current `Date`, `dateMask` defaults to\n * `YYYY-MM-DD HH:mm:ss`, mask parsing creates editable date parts plus literal\n * tokens, `locales` customizes month and weekday labels, and `validate` runs on\n * submission.\n *\n * **Gotchas**\n *\n * A supplied `initial` `Date` is edited in place during prompt interaction.\n * Date edits use JavaScript `Date` setters, so out-of-range typed values can\n * normalize before validation. If the prompt is meant to be editable,\n * `dateMask` should contain at least one editable date token.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const date = options => {\n  const opts = {\n    initial: new Date(),\n    dateMask: \"YYYY-MM-DD HH:mm:ss\",\n    validate: Effect.succeed,\n    ...options,\n    locales: {\n      ...defaultLocales,\n      ...options.locales\n    }\n  };\n  const dateParts = makeDateParts(opts.dateMask, opts.initial, opts.locales);\n  const initialCursorPosition = dateParts.findIndex(part => !part.isToken());\n  const initialState = {\n    dateParts,\n    typed: \"\",\n    cursor: initialCursorPosition,\n    value: opts.initial,\n    error: Option.none()\n  };\n  return custom(initialState, {\n    render: handleDateRender(opts),\n    process: handleDateProcess(opts),\n    clear: handleDateClear(opts)\n  });\n};\n/**\n * Creates a file-system selection prompt and returns the selected path.\n *\n * **Details**\n *\n * The prompt can be configured to select files, directories, or either path\n * type.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (options = {}) => {\n  const opts = {\n    type: options.type ?? \"file\",\n    message: options.message ?? `Choose a file`,\n    startingPath: Option.fromUndefinedOr(options.startingPath),\n    default: Option.fromUndefinedOr(options.default),\n    maxPerPage: options.maxPerPage ?? 10,\n    filter: options.filter ?? (() => Effect.succeed(true))\n  };\n  const initialState = Effect.gen(function* () {\n    const currentPath = yield* resolveCurrentPath(Option.none(), opts);\n    const path = yield* Path.Path;\n    const defaultPath = Option.map(opts.default, defaultValue => path.resolve(currentPath, defaultValue));\n    const initialPath = Option.match(defaultPath, {\n      onNone: () => currentPath,\n      onSome: defaultPath => path.dirname(defaultPath)\n    });\n    const files = yield* getFileList(initialPath, opts);\n    const cursor = Option.match(defaultPath, {\n      onNone: () => 0,\n      onSome: defaultPath => {\n        const index = files.indexOf(path.basename(defaultPath));\n        return index === -1 ? 0 : index;\n      }\n    });\n    const confirm = Confirm.Hide();\n    return {\n      cursor,\n      files,\n      allFiles: files,\n      query: \"\",\n      path: Option.map(defaultPath, path.dirname),\n      confirm\n    };\n  });\n  return custom(initialState, {\n    render: handleFileRender(opts),\n    process: handleFileProcess(opts),\n    clear: handleFileClear(opts)\n  });\n};\n/**\n * Composes prompts by using the output of this prompt to create the next prompt.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => {\n  const op = Object.create(proto);\n  op._tag = \"OnSuccess\";\n  op.prompt = self;\n  op.onSuccess = f;\n  return op;\n});\n/**\n * Creates a floating-point number prompt.\n *\n * **Details**\n *\n * The prompt supports minimum and maximum bounds, keyboard step sizes, display\n * precision, and additional validation before submission.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const float = options => {\n  const opts = {\n    default: 0,\n    min: Number.NEGATIVE_INFINITY,\n    max: Number.POSITIVE_INFINITY,\n    incrementBy: 1,\n    decrementBy: 1,\n    precision: 2,\n    validate: n => {\n      if (n < opts.min) {\n        return Effect.fail(`${n} must be greater than or equal to ${opts.min}`);\n      }\n      if (n > opts.max) {\n        return Effect.fail(`${n} must be less than or equal to ${opts.max}`);\n      }\n      return Effect.succeed(n);\n    },\n    ...options\n  };\n  const initialValue = options.default === undefined ? \"\" : `${opts.default}`;\n  const initialState = {\n    cursor: initialValue.length,\n    value: initialValue,\n    error: Option.none()\n  };\n  return custom(initialState, {\n    render: handleRenderFloat(opts),\n    process: handleProcessFloat(opts),\n    clear: handleNumberClear(opts)\n  });\n};\n/**\n * Creates a text prompt that does not echo typed input and returns the\n * submitted value wrapped in `Redacted`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const hidden = options => basePrompt(options, \"hidden\").pipe(map(Redacted.make));\n/**\n * Creates an integer prompt.\n *\n * **Details**\n *\n * The prompt supports minimum and maximum bounds, keyboard step sizes, and\n * additional validation before submission.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const integer = options => {\n  const opts = {\n    default: 0,\n    min: Number.NEGATIVE_INFINITY,\n    max: Number.POSITIVE_INFINITY,\n    incrementBy: 1,\n    decrementBy: 1,\n    validate: n => {\n      if (n < opts.min) {\n        return Effect.fail(`${n} must be greater than or equal to ${opts.min}`);\n      }\n      if (n > opts.max) {\n        return Effect.fail(`${n} must be less than or equal to ${opts.max}`);\n      }\n      return Effect.succeed(n);\n    },\n    ...options\n  };\n  const initialValue = options.default === undefined ? \"\" : `${opts.default}`;\n  const initialState = {\n    cursor: initialValue.length,\n    value: initialValue,\n    error: Option.none()\n  };\n  return custom(initialState, {\n    render: handleRenderInteger(opts),\n    process: handleProcessInteger(opts),\n    clear: handleNumberClear(opts)\n  });\n};\n/**\n * Creates a text prompt that returns an array of strings by splitting the\n * submitted input on the configured delimiter.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const list = options => text(options).pipe(map(output => output.split(options.delimiter || \",\")));\n/**\n * Transforms the output value produced by a prompt.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => flatMap(self, a => succeed(f(a))));\n/**\n * Creates a password prompt that masks typed input and returns the submitted\n * value wrapped in `Redacted`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const password = options => basePrompt(options, \"password\").pipe(map(Redacted.make));\n/**\n * Runs a prompt by reading terminal input and rendering prompt frames until the\n * prompt submits a value.\n *\n * **Gotchas**\n *\n * The returned effect may fail with `Terminal.QuitError` if terminal input ends\n * or the prompt is quit.\n *\n * @category running\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (self) {\n  const terminal = yield* Terminal.Terminal;\n  const input = yield* terminal.readInput;\n  return yield* runWithInput(self, terminal, input);\n}, /*#__PURE__*/Effect.mapError(() => new Terminal.QuitError({})), Effect.scoped);\nconst getSelectInitialIndex = choices => {\n  let initialIndex = 0;\n  let seenSelected = -1;\n  for (let i = 0; i < choices.length; i++) {\n    const choice = choices[i];\n    if (choice.selected === true) {\n      if (seenSelected !== -1) {\n        throw new Error(\"InvalidArgumentException: only a single choice can be selected by default for Prompt.select\");\n      }\n      seenSelected = i;\n    }\n  }\n  if (seenSelected !== -1) {\n    initialIndex = seenSelected;\n  }\n  return initialIndex;\n};\n/**\n * Creates a prompt that lets the user select a single value from a list of\n * choices.\n *\n * **Gotchas**\n *\n * At most one choice may be marked as selected by default.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const select = options => {\n  const opts = {\n    maxPerPage: 10,\n    ...options\n  };\n  const initialIndex = getSelectInitialIndex(opts.choices);\n  return custom(initialIndex, {\n    render: handleSelectRender(opts),\n    process: handleSelectProcess(opts),\n    clear: handleSelectClear(opts)\n  });\n};\n/**\n * Creates a prompt that lets users filter select choices by typing.\n *\n * **Example** (Filtering choices with autocomplete)\n *\n * ```ts import.meta.vitest\n * import { Prompt } from \"effect/unstable/cli\"\n *\n * const language = Prompt.autoComplete({\n *   message: \"Choose a language\",\n *   choices: [\n *     { title: \"TypeScript\", value: \"ts\" },\n *     { title: \"Rust\", value: \"rs\" },\n *     { title: \"Kotlin\", value: \"kt\" }\n *   ]\n * })\n *\n * Prompt.isPrompt(language) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const autoComplete = options => {\n  const opts = {\n    maxPerPage: 10,\n    filterLabel: \"filter\",\n    filterPlaceholder: \"type to filter\",\n    emptyMessage: \"No matches\",\n    ...options\n  };\n  const initialIndex = getSelectInitialIndex(opts.choices);\n  const filtered = filterAutoCompleteChoices(opts.choices, \"\");\n  const index = filtered.length === 0 ? 0 : filtered.includes(initialIndex) ? initialIndex : filtered[0];\n  const initialState = {\n    query: \"\",\n    index,\n    filtered\n  };\n  return custom(initialState, {\n    render: handleAutoCompleteRender(opts),\n    process: handleAutoCompleteProcess(opts),\n    clear: handleAutoCompleteClear(opts)\n  });\n};\n/**\n * Creates a prompt that lets the user select multiple choices and returns their\n * values as an array.\n *\n * **Details**\n *\n * The prompt supports default selected choices, bulk-selection commands, and\n * minimum or maximum selection counts.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const multiSelect = options => {\n  const opts = {\n    maxPerPage: 10,\n    ...options\n  };\n  // Seed initial selection from choices marked as selected: true\n  const initialSelected = new Set();\n  for (let i = 0; i < opts.choices.length; i++) {\n    const choice = opts.choices[i];\n    if (choice.selected === true) {\n      initialSelected.add(i);\n    }\n  }\n  const initialState = {\n    index: 0,\n    selectedIndices: initialSelected,\n    error: Option.none()\n  };\n  return custom(initialState, {\n    render: handleMultiSelectRender(opts),\n    process: handleMultiSelectProcess(opts),\n    clear: handleMultiSelectClear(opts)\n  });\n};\n/**\n * Creates a `Prompt` which immediately succeeds with the specified value.\n *\n * **Details**\n *\n * This prompt does not attempt to obtain user input or render anything to the\n * screen.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const succeed = value => {\n  const op = Object.create(proto);\n  op._tag = \"Succeed\";\n  op.value = value;\n  return op;\n};\n/**\n * Creates a text-entry prompt that echoes input and returns the submitted\n * string after validation.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const text = options => basePrompt(options, \"text\");\n/**\n * Creates a toggle prompt that lets the user switch between active and inactive\n * states and returns the selected boolean value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const toggle = options => {\n  const opts = {\n    initial: false,\n    active: \"on\",\n    inactive: \"off\",\n    ...options\n  };\n  return custom(opts.initial, {\n    render: handleToggleRender(opts),\n    process: handleToggleProcess,\n    clear: () => handleToggleClear(opts)\n  });\n};\nconst proto = {\n  ... /*#__PURE__*/Effectable.Prototype({\n    label: \"Prompt\",\n    evaluate() {\n      return run(this);\n    }\n  }),\n  [TypeId]: {\n    _Output: _ => _\n  }\n};\nconst allTupled = arg => {\n  if (arg.length === 0) {\n    return succeed([]);\n  }\n  if (arg.length === 1) {\n    return map(arg[0], x => [x]);\n  }\n  let result = map(arg[0], x => [x]);\n  for (let i = 1; i < arg.length; i++) {\n    const curr = arg[i];\n    result = flatMap(result, tuple => map(curr, a => [...tuple, a]));\n  }\n  return result;\n};\nconst runWithInput = (prompt, terminal, input) => Effect.suspend(() => {\n  const op = prompt;\n  switch (op._tag) {\n    case \"Loop\":\n      {\n        return runLoop(op, terminal, input);\n      }\n    case \"OnSuccess\":\n      {\n        return Effect.flatMap(runWithInput(op.prompt, terminal, input), a => runWithInput(op.onSuccess(a), terminal, input));\n      }\n    case \"Succeed\":\n      {\n        return Effect.succeed(op.value);\n      }\n  }\n});\nconst runLoop = /*#__PURE__*/Effect.fnUntraced(function* (loop, terminal, input) {\n  let state = Effect.isEffect(loop.initialState) ? yield* loop.initialState : loop.initialState;\n  let action = Action.NextFrame({\n    state\n  });\n  while (true) {\n    const msg = yield* loop.render(state, action);\n    yield* Effect.orDie(terminal.display(msg));\n    if (loop.events) {\n      const takeInput = Queue.take(input).pipe(Effect.map(input => ({\n        _tag: \"Input\",\n        input\n      })));\n      const result = yield* Effect.raceFirst(takeInput, Queue.take(loop.events).pipe(Effect.map(value => ({\n        _tag: \"Event\",\n        value\n      }))));\n      action = yield* loop.process(result, state);\n    } else {\n      const result = yield* Queue.take(input);\n      action = yield* loop.process(result, state);\n    }\n    switch (action._tag) {\n      case \"Beep\":\n        continue;\n      case \"NextFrame\":\n        {\n          yield* Effect.orDie(terminal.display(yield* loop.clear(state, action)));\n          state = action.state;\n          continue;\n        }\n      case \"Submit\":\n        {\n          yield* Effect.orDie(terminal.display(yield* loop.clear(state, action)));\n          const msg = yield* loop.render(state, action);\n          yield* Effect.orDie(terminal.display(msg));\n          return action.value;\n        }\n    }\n  }\n}, (effect, _, terminal) => Effect.ensuring(effect, Effect.orDie(terminal.display(Ansi.cursorShow))));\nconst Action = /*#__PURE__*/Data.taggedEnum();\n/**\n * Clears all lines taken up by the specified `text`.\n */\nconst eraseText = (text, columns) => {\n  if (columns === 0) {\n    return Ansi.eraseLine + Ansi.cursorTo(0);\n  }\n  let rows = 0;\n  const lines = text.split(NEWLINE_REGEXP);\n  for (const line of lines) {\n    rows += 1 + Math.floor(Math.max(line.length - 1, 0) / columns);\n  }\n  return Ansi.eraseLines(rows);\n};\nconst lines = (prompt, columns) => {\n  const lines = prompt.split(NEWLINE_REGEXP);\n  return columns === 0 ? lines.length : pipe(Arr.map(lines, line => Math.ceil(line.length / columns)), Arr.reduce(0, (left, right) => left + right));\n};\nconst clearOutputWithError = (outputText, columns, errorText) => {\n  if (errorText !== undefined && errorText.length > 0) {\n    return Ansi.cursorDown(lines(errorText, columns)) + eraseText(`\\n${errorText}`, columns) + eraseText(outputText, columns);\n  }\n  return eraseText(outputText, columns);\n};\nconst renderBeep = Ansi.beep;\nconst NEWLINE_REGEXP = /\\r?\\n/;\nconst handleConfirmClear = options => {\n  return Effect.fnUntraced(function* (state, _) {\n    const terminal = yield* Terminal.Terminal;\n    const columns = yield* terminal.columns;\n    const figures = yield* platformFigures;\n    const confirmMessage = state.value ? options.placeholder.defaultConfirm : options.placeholder.defaultDeny;\n    const promptText = renderConfirmOutput(confirmMessage, \"?\", figures.pointerSmall, options, {\n      plain: true\n    });\n    const clearOutput = eraseText(promptText, columns);\n    const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n    return clearOutput + resetCurrentLine;\n  });\n};\nconst renderConfirmOutput = (confirm, leadingSymbol, trailingSymbol, options, renderOptions) => renderPrompt(confirm, options.message, leadingSymbol, trailingSymbol, renderOptions);\nconst renderConfirmNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  // Marking these explicitly as present with `!` because they always will be\n  // and there is really no value in adding a `DeepRequired` type helper just\n  // for these internal cases\n  const confirmMessage = state.value ? options.placeholder.defaultConfirm : options.placeholder.defaultDeny;\n  const confirm = Ansi.annotate(confirmMessage, Ansi.blackBright);\n  const promptMsg = renderConfirmOutput(confirm, leadingSymbol, trailingSymbol, options);\n  return Ansi.cursorHide + promptMsg;\n});\nconst renderConfirmSubmission = /*#__PURE__*/Effect.fnUntraced(function* (value, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const confirmMessage = value ? options.label.confirm : options.label.deny;\n  const promptMsg = renderConfirmOutput(confirmMessage, leadingSymbol, trailingSymbol, options);\n  return promptMsg + \"\\n\";\n});\nconst handleConfirmRender = options => {\n  return (_, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderConfirmNextFrame(state, options),\n      Submit: ({\n        value\n      }) => renderConfirmSubmission(value, options)\n    });\n  };\n};\nconst TRUE_VALUE_REGEXP = /^y|t$/;\nconst FALSE_VALUE_REGEXP = /^n|f$/;\nconst handleConfirmProcess = (input, defaultValue) => {\n  const value = Option.getOrElse(input.input, () => \"\");\n  if (input.key.name === \"enter\" || input.key.name === \"return\") {\n    return Effect.succeed(Action.Submit({\n      value: defaultValue\n    }));\n  }\n  if (TRUE_VALUE_REGEXP.test(value.toLowerCase())) {\n    return Effect.succeed(Action.Submit({\n      value: true\n    }));\n  }\n  if (FALSE_VALUE_REGEXP.test(value.toLowerCase())) {\n    return Effect.succeed(Action.Submit({\n      value: false\n    }));\n  }\n  return Effect.succeed(Action.Beep());\n};\nconst handleDateClear = options => {\n  return Effect.fnUntraced(function* (state, _) {\n    const terminal = yield* Terminal.Terminal;\n    const columns = yield* terminal.columns;\n    const figures = yield* platformFigures;\n    const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n    const parts = Arr.reduce(state.dateParts, \"\", (doc, part) => doc + part.toString());\n    const promptText = renderDateOutput(\"?\", figures.pointerSmall, parts, options, {\n      plain: true\n    });\n    const errorText = Option.isSome(state.error) ? Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n      onEmpty: () => \"\",\n      onNonEmpty: errorLines => `${figures.pointerSmall} ${errorLines.join(\"\\n\")}`\n    }) : \"\";\n    const clearOutput = clearOutputWithError(promptText, columns, errorText);\n    return clearOutput + resetCurrentLine;\n  });\n};\nconst renderDateError = (state, pointer) => {\n  if (Option.isSome(state.error)) {\n    const errorLines = state.error.value.split(NEWLINE_REGEXP);\n    if (Arr.isReadonlyArrayNonEmpty(errorLines)) {\n      const prefix = Ansi.annotate(pointer, Ansi.red) + \" \";\n      const lines = Arr.map(errorLines, str => annotateErrorLine(str));\n      return Ansi.cursorSavePosition + \"\\n\" + prefix + lines.join(\"\\n\") + Ansi.cursorRestorePosition;\n    }\n  }\n  return \"\";\n};\nconst renderParts = (state, submitted = false) => {\n  return Arr.reduce(state.dateParts, \"\", (doc, part, currentIndex) => {\n    const partDoc = part.toString();\n    if (currentIndex === state.cursor && !submitted) {\n      const annotation = Ansi.combine(Ansi.underlined, Ansi.cyanBright);\n      return doc + Ansi.annotate(partDoc, annotation);\n    }\n    return doc + partDoc;\n  });\n};\nconst renderDateOutput = (leadingSymbol, trailingSymbol, parts, options, renderOptions) => renderPrompt(parts, options.message, leadingSymbol, trailingSymbol, renderOptions);\nconst renderDateNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const parts = renderParts(state);\n  const promptMsg = renderDateOutput(leadingSymbol, trailingSymbol, parts, options);\n  const errorMsg = renderDateError(state, figures.pointerSmall);\n  return Ansi.cursorHide + promptMsg + errorMsg;\n});\nconst renderDateSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const parts = renderParts(state, true);\n  const promptMsg = renderDateOutput(leadingSymbol, trailingSymbol, parts, options);\n  return promptMsg + \"\\n\";\n});\nconst processUp = state => {\n  state.dateParts[state.cursor].increment();\n  return Action.NextFrame({\n    state: {\n      ...state,\n      typed: \"\"\n    }\n  });\n};\nconst processDown = state => {\n  state.dateParts[state.cursor].decrement();\n  return Action.NextFrame({\n    state: {\n      ...state,\n      typed: \"\"\n    }\n  });\n};\nconst processDateCursorLeft = state => {\n  const previous = state.dateParts[state.cursor].previousPart();\n  if (Option.isSome(previous)) {\n    return Action.NextFrame({\n      state: {\n        ...state,\n        typed: \"\",\n        cursor: state.dateParts.indexOf(previous.value)\n      }\n    });\n  }\n  return Action.Beep();\n};\nconst processDateCursorRight = state => {\n  const next = state.dateParts[state.cursor].nextPart();\n  if (Option.isSome(next)) {\n    return Action.NextFrame({\n      state: {\n        ...state,\n        typed: \"\",\n        cursor: state.dateParts.indexOf(next.value)\n      }\n    });\n  }\n  return Action.Beep();\n};\nconst processDateNext = state => {\n  const next = state.dateParts[state.cursor].nextPart();\n  const cursor = Option.match(next, {\n    onNone: () => state.dateParts.findIndex(part => !part.isToken()),\n    onSome: next => state.dateParts.indexOf(next)\n  });\n  return Action.NextFrame({\n    state: {\n      ...state,\n      cursor\n    }\n  });\n};\nconst defaultDateProcessor = (value, state) => {\n  if (/\\d/.test(value)) {\n    const typed = state.typed + value;\n    state.dateParts[state.cursor].setValue(typed);\n    return Action.NextFrame({\n      state: {\n        ...state,\n        typed\n      }\n    });\n  }\n  return Action.Beep();\n};\nconst defaultLocales = {\n  months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n  monthsShort: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"],\n  weekdays: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n  weekdaysShort: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]\n};\nconst handleDateRender = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderDateNextFrame(state, options),\n      Submit: () => renderDateSubmission(state, options)\n    });\n  };\n};\nconst handleDateProcess = options => {\n  return (input, state) => {\n    switch (input.key.name) {\n      case \"left\":\n        {\n          return Effect.succeed(processDateCursorLeft(state));\n        }\n      case \"right\":\n        {\n          return Effect.succeed(processDateCursorRight(state));\n        }\n      case \"k\":\n      case \"up\":\n        {\n          return Effect.succeed(processUp(state));\n        }\n      case \"j\":\n      case \"down\":\n        {\n          return Effect.succeed(processDown(state));\n        }\n      case \"tab\":\n        {\n          return Effect.succeed(processDateNext(state));\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          return Effect.match(options.validate(state.value), {\n            onFailure: error => Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(error)\n              }\n            }),\n            onSuccess: value => Action.Submit({\n              value\n            })\n          });\n        }\n      default:\n        {\n          return Effect.succeed(defaultDateProcessor(Option.getOrElse(input.input, () => \"\"), state));\n        }\n    }\n  };\n};\nconst DATE_PART_REGEXP = /\\\\(.)|\"((?:\\\\[\"\\\\]|[^\"])+)\"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g;\nconst regExpGroups = {\n  1: ({\n    token,\n    ...opts\n  }) => new Token({\n    token: token.replace(/\\\\(.)/g, \"$1\"),\n    ...opts\n  }),\n  2: opts => new Day(opts),\n  3: opts => new Month(opts),\n  4: opts => new Year(opts),\n  5: opts => new Meridiem(opts),\n  6: opts => new Hours(opts),\n  7: opts => new Minutes(opts),\n  8: opts => new Seconds(opts),\n  9: opts => new Milliseconds(opts)\n};\nconst makeDateParts = (dateMask, date, locales) => {\n  const parts = [];\n  let result = null;\n  // oxlint-disable-next-line no-cond-assign\n  while (result = DATE_PART_REGEXP.exec(dateMask)) {\n    const match = result.shift();\n    const index = result.findIndex(group => group !== undefined);\n    if (index in regExpGroups) {\n      const token = result[index] || match;\n      parts.push(regExpGroups[index]({\n        token,\n        date,\n        parts,\n        locales\n      }));\n    } else {\n      parts.push(new Token({\n        token: result[index] || match,\n        date,\n        parts,\n        locales\n      }));\n    }\n  }\n  const orderedParts = parts.reduce((array, element) => {\n    const lastElement = array[array.length - 1];\n    if (element.isToken() && lastElement !== undefined && lastElement.isToken()) {\n      lastElement.setValue(element.token);\n    } else {\n      array.push(element);\n    }\n    return array;\n  }, Arr.empty());\n  parts.splice(0, parts.length, ...orderedParts);\n  return parts;\n};\nclass DatePart {\n  token;\n  date;\n  parts;\n  locales;\n  constructor(params) {\n    this.token = params.token;\n    this.locales = params.locales;\n    this.date = params.date || new Date();\n    this.parts = params.parts || [this];\n  }\n  /**\n   * Returns `true` if this `DatePart` is a `Token`, `false` otherwise.\n   */\n  isToken() {\n    return false;\n  }\n  /**\n   * Retrieves the next date part in the list of parts.\n   */\n  nextPart() {\n    const currentPartIndex = Option.getOrElse(Arr.findFirstIndex(this.parts, part => part === this), () => 0);\n    return Arr.findFirst(this.parts.slice(currentPartIndex + 1), part => !part.isToken());\n  }\n  /**\n   * Retrieves the previous date part in the list of parts.\n   */\n  previousPart() {\n    const currentPartIndex = Arr.findFirstIndex(this.parts, part => part === this);\n    if (Option.isSome(currentPartIndex)) {\n      return Arr.findLast(this.parts.slice(0, currentPartIndex.value), part => !part.isToken());\n    }\n    return Option.none();\n  }\n  toString() {\n    return String(this.date);\n  }\n}\nclass Token extends DatePart {\n  increment() {}\n  decrement() {}\n  setValue(value) {\n    this.token = this.token + value;\n  }\n  isToken() {\n    return true;\n  }\n  toString() {\n    return this.token;\n  }\n}\nclass Milliseconds extends DatePart {\n  increment() {\n    this.date.setMilliseconds(this.date.getMilliseconds() + 1);\n  }\n  decrement() {\n    this.date.setMilliseconds(this.date.getMilliseconds() - 1);\n  }\n  setValue(value) {\n    this.date.setMilliseconds(Number.parseInt(value.slice(-this.token.length)));\n  }\n  toString() {\n    const millis = `${this.date.getMilliseconds()}`;\n    return millis.padStart(4, \"0\").substring(0, this.token.length);\n  }\n}\nclass Seconds extends DatePart {\n  increment() {\n    this.date.setSeconds(this.date.getSeconds() + 1);\n  }\n  decrement() {\n    this.date.setSeconds(this.date.getSeconds() - 1);\n  }\n  setValue(value) {\n    this.date.setSeconds(Number.parseInt(value.slice(-2)));\n  }\n  toString() {\n    const seconds = `${this.date.getSeconds()}`;\n    return this.token.length > 1 ? seconds.padStart(2, \"0\") : seconds;\n  }\n}\nclass Minutes extends DatePart {\n  increment() {\n    this.date.setMinutes(this.date.getMinutes() + 1);\n  }\n  decrement() {\n    this.date.setMinutes(this.date.getMinutes() - 1);\n  }\n  setValue(value) {\n    this.date.setMinutes(Number.parseInt(value.slice(-2)));\n  }\n  toString() {\n    const minutes = `${this.date.getMinutes()}`;\n    return this.token.length > 1 ? minutes.padStart(2, \"0\") : minutes;\n  }\n}\nclass Hours extends DatePart {\n  increment() {\n    this.date.setHours(this.date.getHours() + 1);\n  }\n  decrement() {\n    this.date.setHours(this.date.getHours() - 1);\n  }\n  setValue(value) {\n    this.date.setHours(Number.parseInt(value.slice(-2)));\n  }\n  toString() {\n    const hours = /h/.test(this.token) ? this.date.getHours() % 12 || 12 : this.date.getHours();\n    return this.token.length > 1 ? `${hours}`.padStart(2, \"0\") : `${hours}`;\n  }\n}\nclass Day extends DatePart {\n  increment() {\n    this.date.setDate(this.date.getDate() + 1);\n  }\n  decrement() {\n    this.date.setDate(this.date.getDate() - 1);\n  }\n  setValue(value) {\n    this.date.setDate(Number.parseInt(value.slice(-2)));\n  }\n  toString() {\n    const date = this.date.getDate();\n    const day = this.date.getDay();\n    switch (this.token) {\n      case \"DD\":\n        return `${date}`.padStart(2, \"0\");\n      case \"Do\":\n        return `${date}${this.ordinalIndicator(date)}`;\n      case \"d\":\n        return `${day + 1}`;\n      case \"ddd\":\n        return this.locales.weekdaysShort[day];\n      case \"dddd\":\n        return this.locales.weekdays[day];\n      default:\n        return `${date}`;\n    }\n  }\n  ordinalIndicator(day) {\n    switch (day % 10) {\n      case 1:\n        return \"st\";\n      case 2:\n        return \"nd\";\n      case 3:\n        return \"rd\";\n      default:\n        return \"th\";\n    }\n  }\n}\nclass Month extends DatePart {\n  increment() {\n    this.date.setMonth(this.date.getMonth() + 1);\n  }\n  decrement() {\n    this.date.setMonth(this.date.getMonth() - 1);\n  }\n  setValue(value) {\n    const month = Number.parseInt(value.slice(-2)) - 1;\n    this.date.setMonth(month < 0 ? 0 : month);\n  }\n  toString() {\n    const month = this.date.getMonth();\n    switch (this.token.length) {\n      case 2:\n        return `${month + 1}`.padStart(2, \"0\");\n      case 3:\n        return this.locales.monthsShort[month];\n      case 4:\n        return this.locales.months[month];\n      default:\n        return `${month + 1}`;\n    }\n  }\n}\nclass Year extends DatePart {\n  increment() {\n    this.date.setFullYear(this.date.getFullYear() + 1);\n  }\n  decrement() {\n    this.date.setFullYear(this.date.getFullYear() - 1);\n  }\n  setValue(value) {\n    this.date.setFullYear(Number.parseInt(value.slice(-4)));\n  }\n  toString() {\n    const year = `${this.date.getFullYear()}`.padStart(4, \"0\");\n    return this.token.length === 2 ? year.substring(-2) : year;\n  }\n}\nclass Meridiem extends DatePart {\n  increment() {\n    this.date.setHours((this.date.getHours() + 12) % 24);\n  }\n  decrement() {\n    this.increment();\n  }\n  setValue(_value) {}\n  toString() {\n    const meridiem = this.date.getHours() > 12 ? \"pm\" : \"am\";\n    return /A/.test(this.token) ? meridiem.toUpperCase() : meridiem;\n  }\n}\nconst CONFIRM_MESSAGE = \"The selected directory contains files. Would you like to traverse the selected directory?\";\nconst FILE_FILTER_LABEL = \"filter\";\nconst FILE_FILTER_PLACEHOLDER = \"type to filter\";\nconst FILE_EMPTY_MESSAGE = \"No matches\";\nconst Confirm = /*#__PURE__*/Data.taggedEnum();\nconst showConfirmation = /*#__PURE__*/Confirm.$is(\"Show\");\nconst resolveCurrentPath = (path, options) => {\n  if (Option.isSome(path)) {\n    return Effect.succeed(path.value);\n  }\n  if (Option.isSome(options.startingPath)) {\n    const startingPath = options.startingPath.value;\n    return Effect.flatMap(FileSystem.FileSystem, fs =>\n    // Ensure the user provided starting path exists\n    Effect.orDie(fs.exists(startingPath)).pipe(Effect.flatMap(exists => exists ? Effect.void : Effect.die(`The provided starting path '${startingPath}' does not exist`)), Effect.as(startingPath)));\n  }\n  return Effect.sync(() => process.cwd());\n};\nconst getFileList = /*#__PURE__*/Effect.fnUntraced(function* (directory, options) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const files = yield* Effect.orDie(fs.readDirectory(directory)).pipe(\n  // Always prepend the `\"..\"` option to the file list but allow it\n  // to be filtered out if the user so desires\n  Effect.map(files => [\"..\", ...files]));\n  return yield* Effect.filter(files, file => {\n    const result = options.filter(file);\n    const userDefinedFilter = Effect.isEffect(result) ? result : Effect.succeed(result);\n    const directoryFilter = options.type === \"directory\" ? Effect.map(Effect.orDie(fs.stat(path.join(directory, file))), info => info.type === \"Directory\") : Effect.succeed(true);\n    return Effect.zipWith(userDefinedFilter, directoryFilter, (a, b) => a && b);\n  }, {\n    concurrency: files.length\n  });\n});\nconst filterFiles = (files, query) => {\n  if (query.length === 0) {\n    return files;\n  }\n  const normalizedQuery = query.toLowerCase();\n  const filtered = [];\n  for (let index = 0; index < files.length; index++) {\n    if (files[index].toLowerCase().includes(normalizedQuery)) {\n      filtered.push(files[index]);\n    }\n  }\n  return filtered;\n};\nconst updateFileState = (state, query, allFiles = state.allFiles) => {\n  const files = filterFiles(allFiles, query);\n  if (files.length === 0) {\n    return {\n      ...state,\n      query,\n      allFiles,\n      files,\n      cursor: 0\n    };\n  }\n  const selected = state.files[state.cursor];\n  const cursor = selected === undefined ? 0 : files.indexOf(selected);\n  return {\n    ...state,\n    query,\n    allFiles,\n    files,\n    cursor: cursor === -1 ? 0 : cursor\n  };\n};\nconst handleFileClear = options => {\n  return Effect.fnUntraced(function* (state, _) {\n    const terminal = yield* Terminal.Terminal;\n    const columns = yield* terminal.columns;\n    const path = yield* Path.Path;\n    const figures = yield* platformFigures;\n    const currentPath = yield* resolveCurrentPath(state.path, options);\n    const selectedPath = state.files[state.cursor];\n    const resolvedPath = selectedPath === undefined ? currentPath : path.resolve(currentPath, selectedPath);\n    const resolvedPathText = `${figures.pointerSmall} ${resolvedPath}`;\n    const isConfirming = showConfirmation(state.confirm);\n    const promptText = isConfirming ? renderPrompt(\"(Y/n)\", CONFIRM_MESSAGE, \"?\", figures.pointerSmall, {\n      plain: true\n    }) : renderPrompt(renderFileFilter(state, {\n      plain: true\n    }), options.message, figures.tick, figures.ellipsis, {\n      plain: true\n    });\n    const filesText = isConfirming ? \"\" : renderFiles(state, state.files, figures, options, {\n      plain: true\n    });\n    const outputText = isConfirming ? `${promptText}\\n${resolvedPathText}` : `${promptText}\\n${resolvedPathText}\\n${filesText}`;\n    const clearOutput = eraseText(outputText, columns);\n    const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n    return clearOutput + resetCurrentLine;\n  });\n};\nconst renderPrompt = (confirm, message, leadingSymbol, trailingSymbol, options) => {\n  const prefix = leadingSymbol + \" \";\n  const annotate = options?.plain === true ? line => line : annotateLine;\n  return Arr.match(message.split(NEWLINE_REGEXP), {\n    onEmpty: () => prefix + \" \" + trailingSymbol + \" \" + confirm,\n    onNonEmpty: promptLines => {\n      const lines = Arr.map(promptLines, line => annotate(line));\n      return prefix + lines.join(\"\\n\") + \" \" + trailingSymbol + \" \" + confirm;\n    }\n  });\n};\nconst renderPrefix = (state, toDisplay, currentIndex, length, figures, renderOptions) => {\n  let prefix = \" \";\n  if (currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0) {\n    prefix = figures.arrowUp;\n  } else if (currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < length) {\n    prefix = figures.arrowDown;\n  }\n  if (state.cursor === currentIndex) {\n    return renderOptions?.plain === true ? figures.pointer + prefix : Ansi.annotate(figures.pointer, Ansi.cyanBright) + prefix;\n  }\n  return prefix + \" \";\n};\nconst renderFileName = (file, isSelected, renderOptions) => {\n  if (renderOptions?.plain === true) {\n    return file;\n  }\n  return isSelected ? Ansi.annotate(file, Ansi.combine(Ansi.underlined, Ansi.cyanBright)) : file;\n};\nconst renderFileFilter = (state, renderOptions) => {\n  const filterValue = state.query.length === 0 ? renderOptions?.plain === true ? FILE_FILTER_PLACEHOLDER : Ansi.annotate(FILE_FILTER_PLACEHOLDER, Ansi.blackBright) : renderOptions?.plain === true ? state.query : Ansi.annotate(state.query, Ansi.combine(Ansi.underlined, Ansi.cyanBright));\n  return `[${FILE_FILTER_LABEL}: ${filterValue}]`;\n};\nconst renderFiles = (state, files, figures, options, renderOptions) => {\n  const length = files.length;\n  if (length === 0) {\n    return renderOptions?.plain === true ? FILE_EMPTY_MESSAGE : Ansi.annotate(FILE_EMPTY_MESSAGE, Ansi.blackBright);\n  }\n  const toDisplay = entriesToDisplay(state.cursor, length, options.maxPerPage);\n  const documents = [];\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const isSelected = state.cursor === index;\n    const prefix = renderPrefix(state, toDisplay, index, length, figures, renderOptions);\n    const fileName = renderFileName(files[index], isSelected, renderOptions);\n    documents.push(prefix + fileName);\n  }\n  return documents.join(\"\\n\");\n};\nconst renderFileNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const path = yield* Path.Path;\n  const figures = yield* platformFigures;\n  const currentPath = yield* resolveCurrentPath(state.path, options);\n  const selectedPath = state.files[state.cursor];\n  const resolvedPath = selectedPath === undefined ? currentPath : path.resolve(currentPath, selectedPath);\n  const resolvedPathMsg = Ansi.annotate(figures.pointerSmall + \" \" + resolvedPath, Ansi.blackBright);\n  if (showConfirmation(state.confirm)) {\n    const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n    const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n    const confirm = Ansi.annotate(\"(Y/n)\", Ansi.blackBright);\n    const promptMsg = renderPrompt(confirm, CONFIRM_MESSAGE, leadingSymbol, trailingSymbol);\n    return Ansi.cursorHide + promptMsg + \"\\n\" + resolvedPathMsg;\n  }\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderPrompt(renderFileFilter(state), options.message, leadingSymbol, trailingSymbol);\n  const files = renderFiles(state, state.files, figures, options);\n  return Ansi.cursorHide + promptMsg + \"\\n\" + resolvedPathMsg + \"\\n\" + files;\n});\nconst renderFileSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, value, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderPrompt(renderFileFilter(state), options.message, leadingSymbol, trailingSymbol);\n  return promptMsg + \" \" + Ansi.annotate(value, Ansi.white) + \"\\n\";\n});\nconst handleFileRender = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderFileNextFrame(state, options),\n      Submit: ({\n        value\n      }) => renderFileSubmission(state, value, options)\n    });\n  };\n};\nconst processFileCursorUp = state => {\n  if (state.files.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const cursor = state.cursor - 1;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      cursor: cursor < 0 ? state.files.length - 1 : cursor\n    }\n  }));\n};\nconst processFileCursorDown = state => {\n  if (state.files.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      cursor: (state.cursor + 1) % state.files.length\n    }\n  }));\n};\nconst processFileBackspace = state => {\n  if (state.query.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const query = state.query.slice(0, state.query.length - 1);\n  return Effect.succeed(Action.NextFrame({\n    state: updateFileState(state, query)\n  }));\n};\nconst processFileClear = state => Effect.succeed(Action.NextFrame({\n  state: updateFileState(state, \"\")\n}));\nconst processFileInput = (input, state) => {\n  if (input.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const query = state.query + input;\n  return Effect.succeed(Action.NextFrame({\n    state: updateFileState(state, query)\n  }));\n};\nconst processSelection = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  if (state.files.length === 0) {\n    return Action.Beep();\n  }\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const currentPath = yield* resolveCurrentPath(state.path, options);\n  const selectedPath = state.files[state.cursor];\n  const resolvedPath = path.resolve(currentPath, selectedPath);\n  const info = yield* Effect.orDie(fs.stat(resolvedPath));\n  if (info.type === \"Directory\") {\n    const files = yield* getFileList(resolvedPath, options);\n    const filesWithoutParent = files.filter(file => file !== \"..\");\n    // If the user selected a directory AND the prompt type can result with\n    // a directory, we must confirm:\n    //  - If the selected directory has any files\n    //  - Confirm whether or not the user wants to traverse those files\n    if (options.type === \"directory\" || options.type === \"either\") {\n      return filesWithoutParent.length === 0\n      // Directory is empty so it's safe to select it\n      ? Action.Submit({\n        value: resolvedPath\n      })\n      // Directory has contents - show confirmation to user\n      : Action.NextFrame({\n        state: {\n          ...state,\n          confirm: Confirm.Show()\n        }\n      });\n    }\n    return Action.NextFrame({\n      state: {\n        cursor: 0,\n        files,\n        allFiles: files,\n        query: \"\",\n        path: Option.some(resolvedPath),\n        confirm: Confirm.Hide()\n      }\n    });\n  }\n  return Action.Submit({\n    value: resolvedPath\n  });\n});\nconst handleFileProcess = options => {\n  return Effect.fnUntraced(function* (input, state) {\n    if (input.key.ctrl) {\n      if (input.key.name === \"u\") {\n        if (showConfirmation(state.confirm)) {\n          return Action.Beep();\n        }\n        return yield* processFileClear(state);\n      }\n      return Action.Beep();\n    }\n    switch (input.key.name) {\n      case \"k\":\n      case \"up\":\n        {\n          return yield* processFileCursorUp(state);\n        }\n      case \"j\":\n      case \"down\":\n      case \"tab\":\n        {\n          return yield* processFileCursorDown(state);\n        }\n      case \"backspace\":\n        {\n          if (showConfirmation(state.confirm)) {\n            return Action.Beep();\n          }\n          return yield* processFileBackspace(state);\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          return yield* processSelection(state, options);\n        }\n      case \"y\":\n      case \"t\":\n        {\n          if (showConfirmation(state.confirm)) {\n            const path = yield* Path.Path;\n            const currentPath = yield* resolveCurrentPath(state.path, options);\n            const selectedPath = state.files[state.cursor];\n            const resolvedPath = path.resolve(currentPath, selectedPath);\n            const files = yield* getFileList(resolvedPath, options);\n            return Action.NextFrame({\n              state: {\n                cursor: 0,\n                files,\n                allFiles: files,\n                query: \"\",\n                path: Option.some(resolvedPath),\n                confirm: Confirm.Hide()\n              }\n            });\n          }\n          return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n        }\n      case \"n\":\n      case \"f\":\n        {\n          if (showConfirmation(state.confirm)) {\n            const path = yield* Path.Path;\n            const currentPath = yield* resolveCurrentPath(state.path, options);\n            const selectedPath = state.files[state.cursor];\n            const resolvedPath = path.resolve(currentPath, selectedPath);\n            return Action.Submit({\n              value: resolvedPath\n            });\n          }\n          return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n        }\n      default:\n        {\n          if (showConfirmation(state.confirm)) {\n            return Action.Beep();\n          }\n          return yield* processFileInput(Option.getOrElse(input.input, () => \"\"), state);\n        }\n    }\n  });\n};\nconst renderMultiSelectError = (state, pointer, renderOptions) => {\n  if (Option.isSome(state.error)) {\n    return Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n      onEmpty: () => \"\",\n      onNonEmpty: errorLines => {\n        if (renderOptions?.plain === true) {\n          return `${pointer} ${errorLines.join(\"\\n\")}`;\n        }\n        const prefix = Ansi.annotate(pointer, Ansi.red) + \" \";\n        const lines = Arr.map(errorLines, str => annotateErrorLine(str));\n        return Ansi.cursorSavePosition + \"\\n\" + prefix + lines.join(\"\\n\") + Ansi.cursorRestorePosition;\n      }\n    });\n  }\n  return \"\";\n};\nconst renderChoiceDescription = (choice, isActive, renderOptions) => {\n  if (!choice.disabled && choice.description && isActive) {\n    return renderOptions?.plain === true ? \"- \" + choice.description : Ansi.annotate(\"- \" + choice.description, Ansi.blackBright);\n  }\n  return \"\";\n};\nconst metaOptionsCount = 2;\nconst renderMultiSelectTitle = (title, isHighlighted, renderOptions) => {\n  if (renderOptions?.plain === true || !isHighlighted) {\n    return title;\n  }\n  return Ansi.annotate(title, Ansi.combine(Ansi.underlined, Ansi.cyanBright));\n};\nconst renderMultiSelectChoices = (state, options, figures, renderOptions) => {\n  const choices = options.choices;\n  const totalChoices = choices.length;\n  const selectedCount = state.selectedIndices.size;\n  const allSelected = selectedCount === totalChoices;\n  const selectAllText = allSelected ? options?.selectNone ?? \"Select None\" : options?.selectAll ?? \"Select All\";\n  const inverseSelectionText = options?.inverseSelection ?? \"Inverse Selection\";\n  const metaOptions = [{\n    title: selectAllText\n  }, {\n    title: inverseSelectionText\n  }];\n  const allChoices = [...metaOptions, ...choices];\n  const toDisplay = entriesToDisplay(state.index, allChoices.length, options.maxPerPage);\n  const documents = [];\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const choice = allChoices[index];\n    const isHighlighted = state.index === index;\n    let prefix = \" \";\n    if (index === toDisplay.startIndex && toDisplay.startIndex > 0) {\n      prefix = figures.arrowUp;\n    } else if (index === toDisplay.endIndex - 1 && toDisplay.endIndex < allChoices.length) {\n      prefix = figures.arrowDown;\n    }\n    if (index < metaOptions.length) {\n      // Meta options\n      const title = renderMultiSelectTitle(choice.title, isHighlighted, renderOptions);\n      documents.push(prefix + \" \" + title);\n    } else {\n      // Regular choices\n      const choiceIndex = index - metaOptions.length;\n      const isSelected = state.selectedIndices.has(choiceIndex);\n      const checkbox = isSelected ? figures.checkboxOn : figures.checkboxOff;\n      const annotatedCheckbox = isHighlighted && renderOptions?.plain !== true ? Ansi.annotate(checkbox, Ansi.cyanBright) : checkbox;\n      const title = renderMultiSelectTitle(choice.title, isHighlighted, renderOptions);\n      const description = renderChoiceDescription(choice, isHighlighted, renderOptions);\n      documents.push(prefix + \" \" + annotatedCheckbox + \" \" + title + \" \" + description);\n    }\n  }\n  return documents.join(\"\\n\");\n};\nconst renderMultiSelectNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const choices = renderMultiSelectChoices(state, options, figures);\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options);\n  const error = renderMultiSelectError(state, figures.pointer);\n  return Ansi.cursorHide + promptMsg + \"\\n\" + choices + error;\n});\nconst renderMultiSelectSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const selectedChoices = Array.from(state.selectedIndices).sort(EffectNumber.Order).map(index => options.choices[index].title);\n  const selectedText = selectedChoices.join(\", \");\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options);\n  return promptMsg + \" \" + Ansi.annotate(selectedText, Ansi.white) + \"\\n\";\n});\nconst processMultiSelectCursorUp = (state, totalChoices) => {\n  const newIndex = state.index === 0 ? totalChoices - 1 : state.index - 1;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      index: newIndex\n    }\n  }));\n};\nconst processMultiSelectCursorDown = (state, totalChoices) => {\n  const newIndex = (state.index + 1) % totalChoices;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      index: newIndex\n    }\n  }));\n};\nconst processSpace = (state, options) => {\n  const selectedIndices = new Set(state.selectedIndices);\n  if (state.index === 0) {\n    if (state.selectedIndices.size === options.choices.length) {\n      selectedIndices.clear();\n    } else {\n      for (let i = 0; i < options.choices.length; i++) {\n        selectedIndices.add(i);\n      }\n    }\n  } else if (state.index === 1) {\n    for (let i = 0; i < options.choices.length; i++) {\n      if (state.selectedIndices.has(i)) {\n        selectedIndices.delete(i);\n      } else {\n        selectedIndices.add(i);\n      }\n    }\n  } else {\n    const choiceIndex = state.index - metaOptionsCount;\n    if (selectedIndices.has(choiceIndex)) {\n      selectedIndices.delete(choiceIndex);\n    } else {\n      selectedIndices.add(choiceIndex);\n    }\n  }\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      selectedIndices\n    }\n  }));\n};\nconst handleMultiSelectClear = options => Effect.fnUntraced(function* (state, _) {\n  const terminal = yield* Terminal.Terminal;\n  const columns = yield* terminal.columns;\n  const figures = yield* platformFigures;\n  const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n  const promptText = renderSelectOutput(\"?\", figures.pointerSmall, options, {\n    plain: true\n  });\n  const choicesText = renderMultiSelectChoices(state, options, figures, {\n    plain: true\n  });\n  const errorText = renderMultiSelectError(state, figures.pointer, {\n    plain: true\n  });\n  const clearOutput = clearOutputWithError(`${promptText}\\n${choicesText}`, columns, errorText);\n  return clearOutput + clearPrompt;\n});\nconst handleMultiSelectProcess = options => {\n  return (input, state) => {\n    const totalChoices = options.choices.length + metaOptionsCount;\n    switch (input.key.name) {\n      case \"k\":\n      case \"up\":\n        {\n          return processMultiSelectCursorUp({\n            ...state,\n            error: Option.none()\n          }, totalChoices);\n        }\n      case \"j\":\n      case \"down\":\n      case \"tab\":\n        {\n          return processMultiSelectCursorDown({\n            ...state,\n            error: Option.none()\n          }, totalChoices);\n        }\n      case \"space\":\n        {\n          return processSpace(state, options);\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          const selectedCount = state.selectedIndices.size;\n          if (options.min !== undefined && selectedCount < options.min) {\n            return Effect.succeed(Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(`At least ${options.min} are required`)\n              }\n            }));\n          }\n          if (options.max !== undefined && selectedCount > options.max) {\n            return Effect.succeed(Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(`At most ${options.max} choices are allowed`)\n              }\n            }));\n          }\n          const selectedValues = Array.from(state.selectedIndices).sort(EffectNumber.Order).map(index => options.choices[index].value);\n          return Effect.succeed(Action.Submit({\n            value: selectedValues\n          }));\n        }\n      default:\n        {\n          return Effect.succeed(Action.Beep());\n        }\n    }\n  };\n};\nconst handleMultiSelectRender = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderMultiSelectNextFrame(state, options),\n      Submit: () => renderMultiSelectSubmission(state, options)\n    });\n  };\n};\nconst handleNumberClear = options => {\n  return Effect.fnUntraced(function* (state, _) {\n    const terminal = yield* Terminal.Terminal;\n    const columns = yield* terminal.columns;\n    const figures = yield* platformFigures;\n    const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n    const errorText = renderNumberError(state, figures.pointerSmall, {\n      plain: true\n    });\n    const promptText = renderNumberOutput(state, \"?\", figures.pointerSmall, options, {\n      plain: true\n    });\n    const clearOutput = clearOutputWithError(promptText, columns, errorText);\n    return clearOutput + resetCurrentLine;\n  });\n};\nconst renderNumberInput = (state, submitted, renderOptions) => {\n  const value = state.value === \"\" ? \"\" : `${state.value}`;\n  if (submitted || renderOptions?.plain === true) {\n    return value;\n  }\n  const annotation = Option.isSome(state.error) ? Ansi.red : Ansi.combine(Ansi.underlined, Ansi.cyanBright);\n  return Ansi.annotate(value, annotation);\n};\nconst renderNumberError = (state, pointer, renderOptions) => {\n  if (Option.isSome(state.error)) {\n    return Arr.match(state.error.value.split(NEWLINE_REGEXP), {\n      onEmpty: () => \"\",\n      onNonEmpty: errorLines => {\n        if (renderOptions?.plain === true) {\n          return `${pointer} ${errorLines.join(\"\\n\")}`;\n        }\n        const prefix = Ansi.annotate(pointer, Ansi.red) + \" \";\n        const lines = Arr.map(errorLines, str => annotateErrorLine(str));\n        return Ansi.cursorSavePosition + \"\\n\" + prefix + lines.join(\"\\n\") + Ansi.cursorRestorePosition;\n      }\n    });\n  }\n  return \"\";\n};\nconst renderNumberOutput = (state, leadingSymbol, trailingSymbol, options, renderOptions, submitted = false) => {\n  const value = renderNumberInput(state, submitted, renderOptions);\n  return renderPrompt(value, options.message, leadingSymbol, trailingSymbol, renderOptions);\n};\nconst renderNumberNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const errorMsg = renderNumberError(state, figures.pointerSmall);\n  const promptMsg = renderNumberOutput(state, leadingSymbol, trailingSymbol, options);\n  return promptMsg + errorMsg;\n});\nconst renderNumberSubmission = /*#__PURE__*/Effect.fnUntraced(function* (nextState, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderNumberOutput(nextState, leadingSymbol, trailingSymbol, options, undefined, true);\n  return promptMsg + \"\\n\";\n});\nconst processNumberBackspace = state => {\n  if (state.value.length <= 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const value = state.value.slice(0, state.value.length - 1);\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      value,\n      error: Option.none()\n    }\n  }));\n};\nconst processNumberClear = state => Effect.succeed(Action.NextFrame({\n  state: {\n    ...state,\n    cursor: 0,\n    value: \"\",\n    error: Option.none()\n  }\n}));\nconst defaultIntProcessor = (input, state) => {\n  if (state.value.length === 0 && input === \"-\") {\n    return Effect.succeed(Action.NextFrame({\n      state: {\n        ...state,\n        value: \"-\",\n        error: Option.none()\n      }\n    }));\n  }\n  const parsed = Number.parseInt(state.value + input);\n  if (Number.isNaN(parsed)) {\n    return Effect.succeed(Action.Beep());\n  } else {\n    return Effect.succeed(Action.NextFrame({\n      state: {\n        ...state,\n        value: `${parsed}`,\n        error: Option.none()\n      }\n    }));\n  }\n};\nconst defaultFloatProcessor = (input, state) => {\n  if (input === \".\" && state.value.includes(\".\")) {\n    return Effect.succeed(Action.Beep());\n  }\n  if (state.value.length === 0 && input === \"-\") {\n    return Effect.succeed(Action.NextFrame({\n      state: {\n        ...state,\n        value: \"-\",\n        error: Option.none()\n      }\n    }));\n  }\n  const parsed = Number.parseFloat(state.value + input);\n  if (Number.isNaN(parsed)) {\n    return Effect.succeed(Action.Beep());\n  } else {\n    return Effect.succeed(Action.NextFrame({\n      state: {\n        ...state,\n        value: input === \".\" ? `${parsed}.` : `${parsed}`,\n        error: Option.none()\n      }\n    }));\n  }\n};\nconst handleRenderInteger = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderNumberNextFrame(state, options),\n      Submit: () => renderNumberSubmission(state, options)\n    });\n  };\n};\nconst handleProcessInteger = options => {\n  return (input, state) => {\n    if (input.key.ctrl && input.key.name === \"u\") {\n      return processNumberClear(state);\n    }\n    switch (input.key.name) {\n      case \"backspace\":\n        {\n          return processNumberBackspace(state);\n        }\n      case \"k\":\n      case \"up\":\n        {\n          return Effect.succeed(Action.NextFrame({\n            state: {\n              ...state,\n              value: state.value === \"\" || state.value === \"-\" ? `${options.incrementBy}` : `${Number.parseInt(state.value) + options.incrementBy}`,\n              error: Option.none()\n            }\n          }));\n        }\n      case \"j\":\n      case \"down\":\n        {\n          return Effect.succeed(Action.NextFrame({\n            state: {\n              ...state,\n              value: state.value === \"\" || state.value === \"-\" ? `-${options.decrementBy}` : `${Number.parseInt(state.value) - options.decrementBy}`,\n              error: Option.none()\n            }\n          }));\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          const parsed = Number.parseInt(state.value);\n          if (Number.isNaN(parsed)) {\n            return Effect.succeed(Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(\"Must provide an integer value\")\n              }\n            }));\n          } else {\n            return Effect.match(options.validate(parsed), {\n              onFailure: error => Action.NextFrame({\n                state: {\n                  ...state,\n                  error: Option.some(error)\n                }\n              }),\n              onSuccess: value => Action.Submit({\n                value\n              })\n            });\n          }\n        }\n      default:\n        {\n          return defaultIntProcessor(Option.getOrElse(input.input, () => \"\"), state);\n        }\n    }\n  };\n};\nconst handleRenderFloat = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderNumberNextFrame(state, options),\n      Submit: () => renderNumberSubmission(state, options)\n    });\n  };\n};\nconst handleProcessFloat = options => {\n  return (input, state) => {\n    if (input.key.ctrl && input.key.name === \"u\") {\n      return processNumberClear(state);\n    }\n    switch (input.key.name) {\n      case \"backspace\":\n        {\n          return processNumberBackspace(state);\n        }\n      case \"k\":\n      case \"up\":\n        {\n          return Effect.succeed(Action.NextFrame({\n            state: {\n              ...state,\n              value: state.value === \"\" || state.value === \"-\" ? `${options.incrementBy}` : `${Number.parseFloat(state.value) + options.incrementBy}`,\n              error: Option.none()\n            }\n          }));\n        }\n      case \"j\":\n      case \"down\":\n        {\n          return Effect.succeed(Action.NextFrame({\n            state: {\n              ...state,\n              value: state.value === \"\" || state.value === \"-\" ? `-${options.decrementBy}` : `${Number.parseFloat(state.value) - options.decrementBy}`,\n              error: Option.none()\n            }\n          }));\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          const parsed = Number.parseFloat(state.value);\n          if (Number.isNaN(parsed)) {\n            return Effect.succeed(Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(\"Must provide a floating point value\")\n              }\n            }));\n          } else {\n            return Effect.flatMap(Effect.sync(() => EffectNumber.round(parsed, options.precision)), rounded => Effect.match(options.validate(rounded), {\n              onFailure: error => Action.NextFrame({\n                state: {\n                  ...state,\n                  error: Option.some(error)\n                }\n              }),\n              onSuccess: value => Action.Submit({\n                value\n              })\n            }));\n          }\n        }\n      default:\n        {\n          return defaultFloatProcessor(Option.getOrElse(input.input, () => \"\"), state);\n        }\n    }\n  };\n};\nconst filterAutoCompleteChoices = (choices, query) => {\n  const normalizedQuery = query.toLowerCase();\n  const indices = [];\n  for (let i = 0; i < choices.length; i++) {\n    if (choices[i].title.toLowerCase().includes(normalizedQuery)) {\n      indices.push(i);\n    }\n  }\n  return indices;\n};\nconst updateAutoCompleteState = (state, options, query) => {\n  const filtered = filterAutoCompleteChoices(options.choices, query);\n  if (filtered.length === 0) {\n    return {\n      ...state,\n      query,\n      filtered,\n      index: 0\n    };\n  }\n  if (filtered.includes(state.index)) {\n    return {\n      ...state,\n      query,\n      filtered\n    };\n  }\n  return {\n    ...state,\n    query,\n    filtered,\n    index: filtered[0]\n  };\n};\nconst autoCompleteCursor = state => Option.getOrElse(Arr.findFirstIndex(state.filtered, index => index === state.index), () => 0);\nconst renderSelectOutput = (leadingSymbol, trailingSymbol, options, renderOptions) => renderPrompt(\"\", options.message, leadingSymbol, trailingSymbol, renderOptions);\nconst renderAutoCompleteFilter = (state, options, renderOptions) => {\n  const filterValue = state.query.length === 0 ? renderOptions?.plain === true ? options.filterPlaceholder : Ansi.annotate(options.filterPlaceholder, Ansi.blackBright) : renderOptions?.plain === true ? state.query : Ansi.annotate(state.query, Ansi.combine(Ansi.underlined, Ansi.cyanBright));\n  return `[${options.filterLabel}: ${filterValue}]`;\n};\nconst renderAutoCompleteOutput = (state, leadingSymbol, trailingSymbol, options, renderOptions) => {\n  const filter = renderAutoCompleteFilter(state, options, renderOptions);\n  return renderPrompt(filter, options.message, leadingSymbol, trailingSymbol, renderOptions);\n};\nconst renderChoicePrefix = (state, choices, toDisplay, currentIndex, figures, renderOptions) => {\n  let prefix = \" \";\n  if (currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0) {\n    prefix = figures.arrowUp;\n  } else if (currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < choices.length) {\n    prefix = figures.arrowDown;\n  }\n  if (renderOptions?.plain === true) {\n    return state === currentIndex ? figures.pointer + prefix : prefix + \" \";\n  }\n  if (choices[currentIndex].disabled) {\n    const annotation = Ansi.combine(Ansi.bold, Ansi.blackBright);\n    return state === currentIndex ? Ansi.annotate(figures.pointer, annotation) + prefix : prefix + \" \";\n  }\n  return state === currentIndex ? Ansi.annotate(figures.pointer, Ansi.cyanBright) + prefix : prefix + \" \";\n};\nconst renderAutoCompleteChoicePrefix = (state, options, toDisplay, currentIndex, figures, renderOptions) => {\n  let prefix = \" \";\n  if (currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0) {\n    prefix = figures.arrowUp;\n  } else if (currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < state.filtered.length) {\n    prefix = figures.arrowDown;\n  }\n  const choiceIndex = state.filtered[currentIndex];\n  if (renderOptions?.plain === true) {\n    return state.index === choiceIndex ? figures.pointer + prefix : prefix + \" \";\n  }\n  const choice = options.choices[choiceIndex];\n  if (choice.disabled) {\n    const annotation = Ansi.combine(Ansi.bold, Ansi.blackBright);\n    return state.index === choiceIndex ? Ansi.annotate(figures.pointer, annotation) + prefix : prefix + \" \";\n  }\n  return state.index === choiceIndex ? Ansi.annotate(figures.pointer, Ansi.cyanBright) + prefix : prefix + \" \";\n};\nconst renderChoiceTitle = (choice, isSelected, renderOptions) => {\n  if (renderOptions?.plain === true) {\n    return choice.title;\n  }\n  const title = choice.title;\n  if (isSelected) {\n    return choice.disabled ? Ansi.annotate(title, Ansi.combine(Ansi.underlined, Ansi.blackBright)) : Ansi.annotate(title, Ansi.combine(Ansi.underlined, Ansi.cyanBright));\n  }\n  return choice.disabled ? Ansi.annotate(title, Ansi.combine(Ansi.strikethrough, Ansi.blackBright)) : title;\n};\nconst renderSelectChoices = (state, options, figures, renderOptions) => {\n  const choices = options.choices;\n  const toDisplay = entriesToDisplay(state, choices.length, options.maxPerPage);\n  const documents = [];\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const choice = choices[index];\n    const isSelected = state === index;\n    const prefix = renderChoicePrefix(state, choices, toDisplay, index, figures, renderOptions);\n    const title = renderChoiceTitle(choice, isSelected, renderOptions);\n    const description = renderChoiceDescription(choice, isSelected, renderOptions);\n    documents.push(prefix + title + \" \" + description);\n  }\n  return documents.join(\"\\n\");\n};\nconst renderAutoCompleteChoices = (state, options, figures, renderOptions) => {\n  if (state.filtered.length === 0) {\n    return renderOptions?.plain === true ? options.emptyMessage : Ansi.annotate(options.emptyMessage, Ansi.blackBright);\n  }\n  const cursor = autoCompleteCursor(state);\n  const toDisplay = entriesToDisplay(cursor, state.filtered.length, options.maxPerPage);\n  const documents = [];\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const choiceIndex = state.filtered[index];\n    const choice = options.choices[choiceIndex];\n    const isSelected = state.index === choiceIndex;\n    const prefix = renderAutoCompleteChoicePrefix(state, options, toDisplay, index, figures, renderOptions);\n    const title = renderChoiceTitle(choice, isSelected, renderOptions);\n    const description = renderChoiceDescription(choice, isSelected, renderOptions);\n    documents.push(prefix + title + \" \" + description);\n  }\n  return documents.join(\"\\n\");\n};\nconst renderSelectNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const choices = renderSelectChoices(state, options, figures);\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options);\n  return Ansi.cursorHide + promptMsg + \"\\n\" + choices;\n});\nconst renderAutoCompleteNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const choices = renderAutoCompleteChoices(state, options, figures);\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const promptMsg = renderAutoCompleteOutput(state, leadingSymbol, trailingSymbol, options);\n  return Ansi.cursorHide + promptMsg + \"\\n\" + choices;\n});\nconst renderSelectSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const selected = options.choices[state].title;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderSelectOutput(leadingSymbol, trailingSymbol, options);\n  return promptMsg + \" \" + Ansi.annotate(selected, Ansi.white) + \"\\n\";\n});\nconst renderAutoCompleteSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const selected = options.choices[state.index].title;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderAutoCompleteOutput(state, leadingSymbol, trailingSymbol, options);\n  return promptMsg + \" \" + Ansi.annotate(selected, Ansi.white) + \"\\n\";\n});\nconst processSelectCursorUp = (state, choices) => {\n  if (state === 0) {\n    return Effect.succeed(Action.NextFrame({\n      state: choices.length - 1\n    }));\n  }\n  return Effect.succeed(Action.NextFrame({\n    state: state - 1\n  }));\n};\nconst processSelectCursorDown = (state, choices) => {\n  if (state === choices.length - 1) {\n    return Effect.succeed(Action.NextFrame({\n      state: 0\n    }));\n  }\n  return Effect.succeed(Action.NextFrame({\n    state: state + 1\n  }));\n};\nconst processSelectNext = (state, choices) => {\n  return Effect.succeed(Action.NextFrame({\n    state: (state + 1) % choices.length\n  }));\n};\nconst processAutoCompleteCursorUp = state => {\n  if (state.filtered.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const cursor = autoCompleteCursor(state);\n  const nextCursor = cursor === 0 ? state.filtered.length - 1 : cursor - 1;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      index: state.filtered[nextCursor]\n    }\n  }));\n};\nconst processAutoCompleteCursorDown = state => {\n  if (state.filtered.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const cursor = autoCompleteCursor(state);\n  const nextCursor = (cursor + 1) % state.filtered.length;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      index: state.filtered[nextCursor]\n    }\n  }));\n};\nconst processAutoCompleteNext = state => processAutoCompleteCursorDown(state);\nconst processAutoCompleteBackspace = (state, options) => {\n  if (state.query.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const query = state.query.slice(0, state.query.length - 1);\n  return Effect.succeed(Action.NextFrame({\n    state: updateAutoCompleteState(state, options, query)\n  }));\n};\nconst processAutoCompleteClear = (state, options) => Effect.succeed(Action.NextFrame({\n  state: updateAutoCompleteState(state, options, \"\")\n}));\nconst processAutoCompleteInput = (input, state, options) => {\n  if (input.length === 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const query = state.query + input;\n  return Effect.succeed(Action.NextFrame({\n    state: updateAutoCompleteState(state, options, query)\n  }));\n};\nconst handleSelectRender = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderSelectNextFrame(state, options),\n      Submit: () => renderSelectSubmission(state, options)\n    });\n  };\n};\nconst handleAutoCompleteRender = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderAutoCompleteNextFrame(state, options),\n      Submit: () => renderAutoCompleteSubmission(state, options)\n    });\n  };\n};\nconst handleSelectClear = options => Effect.fnUntraced(function* (state, _) {\n  const terminal = yield* Terminal.Terminal;\n  const columns = yield* terminal.columns;\n  const figures = yield* platformFigures;\n  const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n  const promptText = renderSelectOutput(\"?\", figures.pointerSmall, options, {\n    plain: true\n  });\n  const choicesText = renderSelectChoices(state, options, figures, {\n    plain: true\n  });\n  const clearOutput = eraseText(`${promptText}\\n${choicesText}`, columns);\n  return clearOutput + clearPrompt;\n});\nconst handleAutoCompleteClear = options => Effect.fnUntraced(function* (state, _) {\n  const terminal = yield* Terminal.Terminal;\n  const columns = yield* terminal.columns;\n  const figures = yield* platformFigures;\n  const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n  const promptText = renderAutoCompleteOutput(state, \"?\", figures.pointerSmall, options, {\n    plain: true\n  });\n  const choicesText = renderAutoCompleteChoices(state, options, figures, {\n    plain: true\n  });\n  const clearOutput = eraseText(`${promptText}\\n${choicesText}`, columns);\n  return clearOutput + clearPrompt;\n});\nconst handleSelectProcess = options => {\n  return (input, state) => {\n    switch (input.key.name) {\n      case \"k\":\n      case \"up\":\n        {\n          return processSelectCursorUp(state, options.choices);\n        }\n      case \"j\":\n      case \"down\":\n        {\n          return processSelectCursorDown(state, options.choices);\n        }\n      case \"tab\":\n        {\n          return processSelectNext(state, options.choices);\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          const selected = options.choices[state];\n          if (selected.disabled) {\n            return Effect.succeed(Action.Beep());\n          }\n          return Effect.succeed(Action.Submit({\n            value: selected.value\n          }));\n        }\n      default:\n        {\n          return Effect.succeed(Action.Beep());\n        }\n    }\n  };\n};\nconst handleAutoCompleteProcess = options => {\n  return (input, state) => {\n    if (input.key.ctrl) {\n      if (input.key.name === \"u\") {\n        return processAutoCompleteClear(state, options);\n      }\n      return Effect.succeed(Action.Beep());\n    }\n    switch (input.key.name) {\n      case \"k\":\n      case \"up\":\n        {\n          return processAutoCompleteCursorUp(state);\n        }\n      case \"j\":\n      case \"down\":\n        {\n          return processAutoCompleteCursorDown(state);\n        }\n      case \"tab\":\n        {\n          return processAutoCompleteNext(state);\n        }\n      case \"backspace\":\n        {\n          return processAutoCompleteBackspace(state, options);\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          if (state.filtered.length === 0) {\n            return Effect.succeed(Action.Beep());\n          }\n          const selected = options.choices[state.index];\n          if (selected.disabled) {\n            return Effect.succeed(Action.Beep());\n          }\n          return Effect.succeed(Action.Submit({\n            value: selected.value\n          }));\n        }\n      default:\n        {\n          return processAutoCompleteInput(Option.getOrElse(input.input, () => \"\"), state, options);\n        }\n    }\n  };\n};\nconst renderClearScreen = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const terminal = yield* Terminal.Terminal;\n  const columns = yield* terminal.columns;\n  const figures = yield* platformFigures;\n  const resetCurrentLine = Ansi.eraseLine + Ansi.cursorLeft;\n  const errorText = renderTextError(state, figures.pointerSmall, {\n    plain: true\n  });\n  const clearOutput = clearOutputWithError(renderTextOutput(state, \"?\", figures.pointerSmall, options, {\n    plain: true\n  }), columns, errorText);\n  return clearOutput + resetCurrentLine;\n});\nconst renderTextInput = (nextState, options, submitted, renderOptions) => {\n  const text = nextState.value;\n  if (renderOptions?.plain === true) {\n    switch (options.type) {\n      case \"hidden\":\n        {\n          return \"\";\n        }\n      case \"password\":\n        {\n          return \"*\".repeat(text.length);\n        }\n      case \"text\":\n        {\n          return text;\n        }\n    }\n  }\n  const annotation = Option.isSome(nextState.error) ? Ansi.red : submitted ? Ansi.white : nextState.value.length === 0 ? Ansi.blackBright : Ansi.combine(Ansi.underlined, Ansi.cyanBright);\n  switch (options.type) {\n    case \"hidden\":\n      {\n        return \"\";\n      }\n    case \"password\":\n      {\n        return Ansi.annotate(\"*\".repeat(text.length), annotation);\n      }\n    case \"text\":\n      {\n        return Ansi.annotate(text, annotation);\n      }\n  }\n};\nconst renderTextError = (nextState, pointer, renderOptions) => {\n  if (Option.isSome(nextState.error)) {\n    return Arr.match(nextState.error.value.split(NEWLINE_REGEXP), {\n      onEmpty: () => \"\",\n      onNonEmpty: errorLines => {\n        if (renderOptions?.plain === true) {\n          return `${pointer} ${errorLines.join(\"\\n\")}`;\n        }\n        const prefix = Ansi.annotate(pointer, Ansi.red) + \" \";\n        const lines = Arr.map(errorLines, str => annotateErrorLine(str));\n        return Ansi.cursorSavePosition + \"\\n\" + prefix + lines.join(\"\\n\") + Ansi.cursorRestorePosition;\n      }\n    });\n  }\n  return \"\";\n};\nconst renderTextOutput = (nextState, leadingSymbol, trailingSymbol, options, renderOptions, submitted = false) => {\n  const value = renderTextInput(nextState, options, submitted, renderOptions);\n  return renderPrompt(value, options.message, leadingSymbol, trailingSymbol, renderOptions);\n};\nconst renderTextNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const promptMsg = renderTextOutput(state, leadingSymbol, trailingSymbol, options);\n  const errorMsg = renderTextError(state, figures.pointerSmall);\n  const offset = state.cursor - state.value.length;\n  return promptMsg + errorMsg + Ansi.cursorMove(offset);\n});\nconst renderTextSubmission = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const promptMsg = renderTextOutput(state, leadingSymbol, trailingSymbol, options, undefined, true);\n  return promptMsg + \"\\n\";\n});\nconst processTextBackspace = state => {\n  if (state.cursor <= 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const beforeCursor = state.value.slice(0, state.cursor - 1);\n  const afterCursor = state.value.slice(state.cursor);\n  const cursor = state.cursor - 1;\n  const value = `${beforeCursor}${afterCursor}`;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      cursor,\n      value,\n      error: Option.none()\n    }\n  }));\n};\nconst processTextClear = state => Effect.succeed(Action.NextFrame({\n  state: {\n    ...state,\n    cursor: 0,\n    value: \"\",\n    error: Option.none()\n  }\n}));\nconst processTextCursorLeft = state => {\n  if (state.cursor <= 0) {\n    return Effect.succeed(Action.Beep());\n  }\n  const cursor = state.cursor - 1;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      cursor,\n      error: Option.none()\n    }\n  }));\n};\nconst processTextCursorRight = state => {\n  if (state.cursor >= state.value.length) {\n    return Effect.succeed(Action.Beep());\n  }\n  const cursor = Math.min(state.cursor + 1, state.value.length);\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      cursor,\n      error: Option.none()\n    }\n  }));\n};\nconst processTextCursorStart = state => Effect.succeed(Action.NextFrame({\n  state: {\n    ...state,\n    cursor: 0,\n    error: Option.none()\n  }\n}));\nconst processTextCursorEnd = state => Effect.succeed(Action.NextFrame({\n  state: {\n    ...state,\n    cursor: state.value.length,\n    error: Option.none()\n  }\n}));\nconst processTab = (state, options) => {\n  if (state.value === options.default) {\n    return Effect.succeed(Action.Beep());\n  }\n  const value = state.value.length === 0 ? options.default : state.value;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      value,\n      cursor: value.length,\n      error: Option.none()\n    }\n  }));\n};\nconst defaultTextProcessor = (input, state) => {\n  const beforeCursor = state.value.slice(0, state.cursor);\n  const afterCursor = state.value.slice(state.cursor);\n  const value = `${beforeCursor}${input}${afterCursor}`;\n  const cursor = state.cursor + input.length;\n  return Effect.succeed(Action.NextFrame({\n    state: {\n      ...state,\n      cursor,\n      value,\n      error: Option.none()\n    }\n  }));\n};\nconst handleTextRender = options => {\n  return (state, action) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({\n        state\n      }) => renderTextNextFrame(state, options),\n      Submit: () => renderTextSubmission(state, options)\n    });\n  };\n};\nconst handleTextProcess = options => {\n  return (input, state) => {\n    if (input.key.ctrl) {\n      switch (input.key.name) {\n        case \"u\":\n          {\n            return processTextClear(state);\n          }\n        case \"a\":\n          {\n            return processTextCursorStart(state);\n          }\n        case \"e\":\n          {\n            return processTextCursorEnd(state);\n          }\n        default:\n          {\n            return Effect.succeed(Action.Beep());\n          }\n      }\n    }\n    switch (input.key.name) {\n      case \"backspace\":\n        {\n          return processTextBackspace(state);\n        }\n      case \"left\":\n        {\n          return processTextCursorLeft(state);\n        }\n      case \"right\":\n        {\n          return processTextCursorRight(state);\n        }\n      case \"home\":\n        {\n          return processTextCursorStart(state);\n        }\n      case \"end\":\n        {\n          return processTextCursorEnd(state);\n        }\n      case \"enter\":\n      case \"return\":\n        {\n          const value = state.value;\n          return Effect.match(options.validate(value), {\n            onFailure: error => Action.NextFrame({\n              state: {\n                ...state,\n                value,\n                error: Option.some(error)\n              }\n            }),\n            onSuccess: value => Action.Submit({\n              value\n            })\n          });\n        }\n      case \"tab\":\n        {\n          return processTab(state, options);\n        }\n      default:\n        {\n          return defaultTextProcessor(Option.getOrElse(input.input, () => \"\"), state);\n        }\n    }\n  };\n};\nconst handleTextClear = options => {\n  return (state, _) => {\n    return renderClearScreen(state, options);\n  };\n};\nconst basePrompt = (options, type) => {\n  const opts = {\n    default: \"\",\n    type,\n    validate: Effect.succeed,\n    ...options\n  };\n  const initialState = {\n    cursor: opts.default.length,\n    value: opts.default,\n    error: Option.none()\n  };\n  return custom(initialState, {\n    render: handleTextRender(opts),\n    process: handleTextProcess(opts),\n    clear: handleTextClear(opts)\n  });\n};\nconst handleToggleClear = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const terminal = yield* Terminal.Terminal;\n  const columns = yield* terminal.columns;\n  const figures = yield* platformFigures;\n  const clearPrompt = Ansi.eraseLine + Ansi.cursorLeft;\n  const toggleText = `${options.active} / ${options.inactive}`;\n  const promptText = renderPrompt(toggleText, options.message, \"?\", figures.pointerSmall, {\n    plain: true\n  });\n  const clearOutput = eraseText(promptText, columns);\n  return clearOutput + clearPrompt;\n});\nconst renderToggle = (value, options, submitted = false) => {\n  const separator = Ansi.annotate(\"/\", Ansi.blackBright);\n  const selectedAnnotation = Ansi.combine(Ansi.underlined, submitted ? Ansi.white : Ansi.cyanBright);\n  const inactive = value ? options.inactive : Ansi.annotate(options.inactive, selectedAnnotation);\n  const active = value ? Ansi.annotate(options.active, selectedAnnotation) : options.active;\n  return active + \" \" + separator + \" \" + inactive;\n};\nconst renderToggleOutput = (toggle, leadingSymbol, trailingSymbol, options) => {\n  const promptLines = options.message.split(NEWLINE_REGEXP);\n  const prefix = leadingSymbol + \" \";\n  if (Arr.isReadonlyArrayNonEmpty(promptLines)) {\n    const lines = Arr.map(promptLines, line => annotateLine(line));\n    return prefix + lines.join(\"\\n\") + \" \" + trailingSymbol + \" \" + toggle;\n  }\n  return prefix + \" \" + trailingSymbol + \" \" + toggle;\n};\nconst renderToggleNextFrame = /*#__PURE__*/Effect.fnUntraced(function* (state, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(\"?\", Ansi.cyanBright);\n  const trailingSymbol = Ansi.annotate(figures.pointerSmall, Ansi.blackBright);\n  const toggle = renderToggle(state, options);\n  const promptMsg = renderToggleOutput(toggle, leadingSymbol, trailingSymbol, options);\n  return Ansi.cursorHide + promptMsg;\n});\nconst renderToggleSubmission = /*#__PURE__*/Effect.fnUntraced(function* (value, options) {\n  const figures = yield* platformFigures;\n  const leadingSymbol = Ansi.annotate(figures.tick, Ansi.green);\n  const trailingSymbol = Ansi.annotate(figures.ellipsis, Ansi.blackBright);\n  const toggle = renderToggle(value, options, true);\n  const promptMsg = renderToggleOutput(toggle, leadingSymbol, trailingSymbol, options);\n  return promptMsg + \"\\n\";\n});\nconst activate = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Action.NextFrame({\n  state: true\n}));\nconst deactivate = /*#__PURE__*/Effect.succeed(/*#__PURE__*/Action.NextFrame({\n  state: false\n}));\nconst handleToggleRender = options => {\n  return (state, action) => {\n    switch (action._tag) {\n      case \"Beep\":\n        {\n          return Effect.succeed(renderBeep);\n        }\n      case \"NextFrame\":\n        {\n          return renderToggleNextFrame(state, options);\n        }\n      case \"Submit\":\n        {\n          return renderToggleSubmission(state, options);\n        }\n    }\n  };\n};\nconst handleToggleProcess = (input, state) => {\n  switch (input.key.name) {\n    case \"0\":\n    case \"j\":\n    case \"delete\":\n    case \"right\":\n    case \"down\":\n      {\n        return deactivate;\n      }\n    case \"1\":\n    case \"k\":\n    case \"left\":\n    case \"up\":\n      {\n        return activate;\n      }\n    case \" \":\n    case \"tab\":\n      {\n        return state ? deactivate : activate;\n      }\n    case \"enter\":\n    case \"return\":\n      {\n        return Effect.succeed(Action.Submit({\n          value: state\n        }));\n      }\n    default:\n      {\n        return Effect.succeed(Action.Beep());\n      }\n  }\n};\nconst entriesToDisplay = (cursor, total, maxVisible) => {\n  const max = maxVisible === undefined ? total : maxVisible;\n  let startIndex = Math.min(total - max, cursor - Math.floor(max / 2));\n  if (startIndex < 0) {\n    startIndex = 0;\n  }\n  const endIndex = Math.min(startIndex + max, total);\n  return {\n    startIndex,\n    endIndex\n  };\n};\n//# sourceMappingURL=Prompt.js.map","/**\n * Defines the shared parameter model for CLI arguments and flags.\n *\n * A `Param<Kind, A>` describes how to consume parsed command-line input and\n * return a typed value. The `Kind` decides whether the parameter reads\n * positional arguments or named flags. `Argument` and `Flag` build on this\n * module to share parsing structure, primitive constructors, help metadata,\n * aliases, defaults, prompts, configuration fallbacks, validation, schema\n * decoding, fallback parameters, and traversal helpers.\n *\n * @since 4.0.0\n */\nimport * as Config from \"../../Config.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { dual, identity } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as CliError from \"./CliError.js\";\nimport * as Primitive from \"./Primitive.js\";\nimport * as Prompt from \"./Prompt.js\";\nconst TypeId = \"~effect/cli/Param\";\n/**\n * Defines the kind discriminator for positional argument parameters.\n *\n * **When to use**\n *\n * Use to build low-level `Param` constructors or type positions for positional\n * argument parameters.\n *\n * @see {@link flagKind} for the named flag parameter discriminator\n * @see {@link ParamKind} for the full parameter kind union\n *\n * @category constants\n * @since 4.0.0\n */\nexport const argumentKind = \"argument\";\n/**\n * Defines the kind discriminator for flag parameters.\n *\n * **When to use**\n *\n * Use to build low-level `Param` constructors or type positions for named flag\n * parameters.\n *\n * @see {@link argumentKind} for the positional argument parameter discriminator\n *\n * @category constants\n * @since 4.0.0\n */\nexport const flagKind = \"flag\";\nconst Proto = {\n  [TypeId]: {\n    _A: identity\n  },\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/**\n * Type guard to check if a value is a Param.\n *\n * **Example** (Checking for params)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const maybeParam = Param.string(Param.flagKind, \"name\")\n *\n * Param.isParam(maybeParam) // => true\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isParam = u => Predicate.hasProperty(u, TypeId);\n/**\n * Type guard to check if a param is a Single param (not composed).\n *\n * **Example** (Checking for single params)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const nameParam = Param.string(Param.flagKind, \"name\")\n * const optionalParam = Param.optional(nameParam)\n *\n * Param.isSingle(nameParam) // => true\n * Param.isSingle(optionalParam) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isSingle = param => Predicate.isTagged(param, \"Single\");\n/**\n * Type guard to check if a Single param is a flag (not an argument).\n *\n * @internal\n */\nexport const isFlagParam = single => single.kind === \"flag\";\n/**\n * Constructs a leaf `Single` parameter from its kind, name, primitive parser,\n * and optional help metadata.\n *\n * **Details**\n *\n * The returned parser reads either one positional argument or the named flag,\n * depending on `kind`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeSingle = params => {\n  const parse = args => params.kind === argumentKind ? parsePositional(params.name, params.primitiveType, args) : parseFlag(params.name, params.primitiveType, args);\n  return Object.setPrototypeOf({\n    _tag: \"Single\",\n    ...params,\n    description: params.description ?? Option.none(),\n    aliases: params.aliases ?? [],\n    hidden: params.hidden ?? false,\n    parse\n  }, Proto);\n};\n/**\n * Creates a string parameter.\n *\n * **Example** (Creating string parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create a string flag\n * const nameFlag = Param.string(Param.flagKind, \"name\")\n *\n * // Create a string argument\n * const fileArg = Param.string(Param.argumentKind, \"file\")\n *\n * // Usage in CLI: --name \"John Doe\" or as positional argument\n * const kinds = [nameFlag.kind, fileArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const string = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.string,\n  kind\n});\n/**\n * Creates a boolean parameter.\n *\n * **Example** (Creating boolean parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create a boolean flag\n * const verboseFlag = Param.boolean(Param.flagKind, \"verbose\")\n *\n * // Create a boolean argument\n * const enableArg = Param.boolean(Param.argumentKind, \"enable\")\n *\n * // Usage in CLI: --verbose (defaults to true when present, false when absent)\n * // or as positional: true/false\n * const kinds = [verboseFlag.kind, enableArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const boolean = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.boolean,\n  kind\n});\n/**\n * Creates an integer parameter.\n *\n * **Example** (Creating integer parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create an integer flag\n * const portFlag = Param.integer(Param.flagKind, \"port\")\n *\n * // Create an integer argument\n * const countArg = Param.integer(Param.argumentKind, \"count\")\n *\n * // Usage in CLI: --port 8080 or as positional argument: 42\n * const kinds = [portFlag.kind, countArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const integer = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.integer,\n  kind\n});\n/**\n * Creates a floating-point number parameter.\n *\n * **Example** (Creating float parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create a float flag\n * const rateFlag = Param.float(Param.flagKind, \"rate\")\n *\n * // Create a float argument\n * const thresholdArg = Param.float(Param.argumentKind, \"threshold\")\n *\n * // Usage in CLI: --rate 0.95 or as positional argument: 3.14159\n * const kinds = [rateFlag.kind, thresholdArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const float = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.float,\n  kind\n});\n/**\n * Creates a date parameter that parses ISO date strings.\n *\n * **Example** (Creating date parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create a date flag\n * const startFlag = Param.date(Param.flagKind, \"start-date\")\n *\n * // Create a date argument\n * const dueDateArg = Param.date(Param.argumentKind, \"due-date\")\n *\n * // Usage in CLI: --start-date \"2023-12-25\" or as positional: \"2023-01-01\"\n * // Parses to JavaScript Date object\n * const kinds = [startFlag.kind, dueDateArg.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const date = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.date,\n  kind\n});\n/**\n * Constructs command-line params that represent a choice between several\n * inputs. The input will be mapped to it's associated value during parsing.\n *\n * **Example** (Creating valued choices)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * type Animal = Dog | Cat\n *\n * interface Dog {\n *   readonly _tag: \"Dog\"\n * }\n *\n * interface Cat {\n *   readonly _tag: \"Cat\"\n * }\n *\n * const animal = Param.choiceWithValue(Param.flagKind, \"animal\", [\n *   [\"dog\", { _tag: \"Dog\" }],\n *   [\"cat\", { _tag: \"Cat\" }]\n * ])\n * animal.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choiceWithValue = (kind, name, choices) => makeSingle({\n  name,\n  primitiveType: Primitive.choice(choices),\n  kind\n});\n/**\n * Constructs command-line params that represent a choice between several\n * string inputs.\n *\n * **Example** (Creating string choices)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const logLevel = Param.choice(Param.flagKind, \"log-level\", [\n *   \"debug\",\n *   \"info\",\n *   \"warn\",\n *   \"error\"\n * ])\n * logLevel.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choice = (kind, name, choices) => {\n  const mappedChoices = choices.map(value => [value, value]);\n  return choiceWithValue(kind, name, mappedChoices);\n};\n/**\n * Creates a path parameter that accepts file or directory paths.\n *\n * **Example** (Creating path parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Basic path parameter\n * const outputPath = Param.path(Param.flagKind, \"output\")\n *\n * // Path that must exist\n * const inputPath = Param.path(Param.flagKind, \"input\", { mustExist: true })\n *\n * // File-only path\n * const configFile = Param.path(Param.flagKind, \"config\", {\n *   pathType: \"file\",\n *   mustExist: true,\n *   typeName: \"config-file\"\n * })\n * const kinds = [outputPath.kind, inputPath.kind, configFile.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const path = (kind, name, options) => makeSingle({\n  name,\n  kind,\n  primitiveType: Primitive.path(options?.pathType ?? \"either\", options?.mustExist),\n  typeName: options?.typeName\n});\n/**\n * Creates a directory path parameter.\n *\n * **Details**\n *\n * This is a convenience function that creates a path parameter with the\n * `pathType` set to `\"directory\"` and a default type name of `\"directory\"`.\n *\n * **Example** (Creating directory parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Basic directory parameter\n * const outputDir = Param.directory(Param.flagKind, \"output-dir\")\n *\n * // Directory that must exist\n * const sourceDir = Param.directory(Param.flagKind, \"source\", { mustExist: true })\n *\n * // Usage: --output-dir /path/to/dir --source /existing/dir\n * const kinds = [outputDir.kind, sourceDir.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const directory = (kind, name, options) => path(kind, name, {\n  pathType: \"directory\",\n  typeName: \"directory\",\n  mustExist: options?.mustExist\n});\n/**\n * Creates a file path parameter.\n *\n * **Details**\n *\n * This is a convenience function that creates a path parameter with a\n * `pathType` set to `\"file\"` and a default type name of `\"file\"`.\n *\n * **Example** (Creating file parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Basic file parameter\n * const outputFile = Param.file(Param.flagKind, \"output\")\n *\n * // File that must exist\n * const inputFile = Param.file(Param.flagKind, \"input\", { mustExist: true })\n *\n * // Usage: --output result.txt --input existing-file.txt\n * const kinds = [outputFile.kind, inputFile.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (kind, name, options) => path(kind, name, {\n  pathType: \"file\",\n  typeName: \"file\",\n  mustExist: options?.mustExist\n});\n/**\n * Creates a redacted parameter for sensitive data like passwords.\n * The value is masked in help output and logging.\n *\n * **Example** (Creating redacted parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create a password parameter\n * const password = Param.redacted(Param.flagKind, \"password\")\n *\n * // Create an API key argument\n * const apiKey = Param.redacted(Param.argumentKind, \"api-key\")\n *\n * // Usage: --password (value will be hidden in help/logs)\n * const kinds = [password.kind, apiKey.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const redacted = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.redacted,\n  kind\n});\n/**\n * Creates a parameter that reads and returns file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Read a config file as string\n * const configContent = Param.fileText(Param.flagKind, \"config\")\n *\n * // Read a template file as argument\n * const templateContent = Param.fileText(Param.argumentKind, \"template\")\n *\n * // Usage: --config config.txt (reads file content into string)\n * const kinds = [configContent.kind, templateContent.kind] // => [\"flag\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileText = (kind, name) => makeSingle({\n  name,\n  primitiveType: Primitive.fileText,\n  kind\n});\n/**\n * Creates a param that reads and parses the content of the specified file.\n *\n * **Details**\n *\n * The parser that is utilized will depend on the specified `format`, or the\n * extension of the file passed on the command-line if no `format` is specified.\n *\n * **Example** (Parsing file contents)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Will use the extension of the file passed on the command line to determine\n * // the parser to use\n * const config = Param.fileParse(Param.flagKind, \"config\")\n *\n * // Will use the JSON parser\n * const jsonConfig = Param.fileParse(Param.flagKind, \"json-config\", {\n *   format: \"json\"\n * })\n * const kinds = [config.kind, jsonConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileParse = (kind, name, options) => makeSingle({\n  name,\n  primitiveType: Primitive.fileParse(options),\n  kind\n});\n/**\n * Creates a parameter that reads and validates file content using a schema.\n *\n * **Example** (Validating file contents)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Param } from \"effect/unstable/cli\"\n * // Parse JSON config file\n * const configSchema = Schema.Struct({\n *   port: Schema.Number,\n *   host: Schema.String\n * })\n *\n * const config = Param.fileSchema(Param.flagKind, \"config\", configSchema, {\n *   format: \"json\"\n * })\n *\n * // Parse YAML file\n * const yamlConfig = Param.fileSchema(Param.flagKind, \"config\", configSchema, {\n *   format: \"yaml\"\n * })\n *\n * // Usage: --config config.json (reads and validates file content)\n * const kinds = [config.kind, yamlConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileSchema = (kind, name, schema, options) => makeSingle({\n  name,\n  primitiveType: Primitive.fileSchema(schema, options),\n  kind\n});\n/**\n * Creates a param that parses key=value pairs.\n *\n * **When to use**\n *\n * Use when you need command-line options or arguments that collect `key=value`\n * configuration entries.\n *\n * **Details**\n *\n * Requires at least one key=value pair. The parsed pairs are merged into a\n * single record object.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const env = Param.keyValuePair(Param.flagKind, \"env\")\n * // --env FOO=bar --env BAZ=qux will parse to { FOO: \"bar\", BAZ: \"qux\" }\n *\n * const props = Param.keyValuePair(Param.flagKind, \"property\")\n * // --property name=value --property debug=true\n * const kinds = [env.kind, props.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const keyValuePair = (kind, name) => map(variadic(makeSingle({\n  name,\n  primitiveType: Primitive.keyValuePair,\n  kind\n}), {\n  min: 1\n}), objects => Object.fromEntries(objects.flatMap(Object.entries)));\n/**\n * Creates an empty sentinel parameter that always fails to parse.\n *\n * **When to use**\n *\n * Use when you need an empty CLI parameter sentinel for optional parameter\n * construction or internal combinators.\n *\n * **Example** (Creating sentinel parameters)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const disabledDebugParam = Param.none(Param.flagKind)\n *\n * const makeDebugParam = (enableDebug: boolean) =>\n *   enableDebug ? Param.string(Param.flagKind, \"debug\") : disabledDebugParam\n *\n * makeDebugParam(true) === disabledDebugParam // => false\n * makeDebugParam(false) === disabledDebugParam // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const none = kind => makeSingle({\n  name: \"__none__\",\n  primitiveType: Primitive.none,\n  kind\n});\nconst FLAG_DASH_REGEXP = /^-+/;\n/**\n * Adds an alias to an option.\n *\n * **When to use**\n *\n * Use when you need a CLI parameter to accept an alternate name, such as \"-f\"\n * for \"--force\".\n *\n * **Details**\n *\n * This works on any param structure by recursively finding the underlying\n * `Single` node and applying the alias there.\n *\n * **Example** (Adding parameter aliases)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const force = Param.boolean(Param.flagKind, \"force\").pipe(\n *   Param.withAlias(\"-f\"),\n *   Param.withAlias(\"-F\")\n * )\n *\n * // Also works on composed params:\n * const count = Param.integer(Param.flagKind, \"count\").pipe(\n *   Param.optional,\n *   Param.withAlias(\"-c\") // finds the underlying Single and adds alias\n * )\n * const kinds = [force.kind, count.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => {\n  return transformSingle(self, single => makeSingle({\n    ...single,\n    aliases: [...single.aliases, alias.replace(FLAG_DASH_REGEXP, \"\")]\n  }));\n});\n/**\n * Adds a description to an option for help text.\n *\n * **Details**\n *\n * Descriptions provide users with information about what the option does\n * when they view help documentation.\n *\n * **Example** (Adding help descriptions)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const verbose = Param.boolean(Param.flagKind, \"verbose\").pipe(\n *   Param.withAlias(\"-v\"),\n *   Param.withDescription(\"Enable verbose output\")\n * )\n * verbose.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => {\n  return transformSingle(self, single => makeSingle({\n    ...single,\n    description: Option.some(description)\n  }));\n});\n/**\n * Hides a parameter from generated help output and completions while keeping\n * it parseable on the command line.\n *\n * **When to use**\n *\n * Use when experimental, internal, or deprecated flags should be accepted but\n * not advertised.\n *\n * **Example** (Hiding a flag from help)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const experimental = Param.boolean(Param.flagKind, \"experimental-foo\").pipe(\n *   Param.withHidden\n * )\n * experimental.kind // => \"flag\"\n * ```\n *\n * @category metadata\n * @since 4.0.0\n */\nexport const withHidden = self => transformSingle(self, single => makeSingle({\n  ...single,\n  hidden: true\n}));\n/**\n * Transforms the parsed value of an option using a mapping function.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const port = Param.integer(Param.flagKind, \"port\").pipe(\n *   Param.map((n) => ({ port: n, url: `http://localhost:${n}` }))\n * )\n * port.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => {\n  const parse = args => Effect.map(self.parse(args), ([operands, value]) => [operands, f(value)]);\n  return Object.assign(Object.create(Proto), {\n    _tag: \"Map\",\n    kind: self.kind,\n    param: self,\n    f,\n    parse\n  });\n});\nconst transform = (self, f) => Object.assign(Object.create(Proto), {\n  _tag: \"Transform\",\n  kind: self.kind,\n  param: self,\n  f,\n  parse: f(self.parse)\n});\n/**\n * Transforms the parsed value of an option using an effectful mapping function.\n *\n * **Example** (Mapping parsed values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { CliError, Param } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const validatedEmail = Param.string(Param.flagKind, \"email\").pipe(\n *   Param.mapEffect((email) =>\n *     email.includes(\"@\")\n *       ? Effect.succeed(email)\n *       : Effect.fail(\n *         new CliError.InvalidValue({\n *           option: \"email\",\n *           value: email,\n *           expected: \"valid email format\",\n *           kind: \"flag\"\n *         })\n *       )\n *   )\n * )\n *\n * const [, value] = await Effect.runPromise(\n *   validatedEmail.parse({\n *     arguments: [],\n *     flags: { email: [\"alice@example.com\"] }\n *   }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"alice@example.com\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => transform(self, parse => args => Effect.flatMap(parse(args), ([leftover, a]) => f(a).pipe(Effect.map(b => [leftover, b])))));\n/**\n * Transforms the parsed value of an option using a function that may throw,\n * converting any thrown errors into failure messages.\n *\n * **Example** (Mapping thrown errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Param } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const parsedJson = Param.string(Param.flagKind, \"config\").pipe(\n *   Param.mapTryCatch(\n *     (str) => JSON.parse(str),\n *     (error) =>\n *       `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`\n *   )\n * )\n *\n * const [, value] = await Effect.runPromise(\n *   parsedJson.parse({\n *     arguments: [],\n *     flags: { config: ['{\"enabled\":true}'] }\n *   }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => {\n  const single = getUnderlyingSingleOrThrow(self);\n  return transform(self, parse => args => Effect.flatMap(parse(args), ([leftover, a]) => Effect.try({\n    try: () => f(a),\n    catch: error => onError(error)\n  }).pipe(Effect.mapError(error => new CliError.InvalidValue({\n    option: single.name,\n    value: String(a),\n    expected: error,\n    kind: single.kind\n  })), Effect.map(b => [leftover, b]))));\n});\n/**\n * Makes a flag or positional argument optional.\n *\n * **Details**\n *\n * When the parameter is absent, parsing succeeds with `Option.none()` instead\n * of failing with a missing option or missing argument error. When present, the\n * parsed value is wrapped in `Option.some()`.\n *\n * **Example** (Making parameters optional)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Create an optional port option\n * // - When not provided: returns Option.none()\n * // - When provided: returns Option.some(parsedValue)\n * const port = Param.optional(Param.integer(Param.flagKind, \"port\"))\n * port.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const optional = param => {\n  const parse = Effect.fnUntraced(function* (args) {\n    const single = getUnderlyingSingleOrThrow(param);\n    // Handle boolean params that are explicitly marked as optional (i.e. the\n    // end user wants to return `Option.none()` instead of `false` when the\n    // flag (or its negated variant) are not present on the command line\n    if (isFlagParam(single) && Primitive.isBoolean(single.primitiveType) && ![single.name, ...single.aliases].some(name => (args.flags[name] ?? []).length > 0)) {\n      return [args.arguments, Option.none()];\n    }\n    return yield* param.parse(args).pipe(Effect.map(([leftover, value]) => [leftover, Option.some(value)]),\n    // Catch both MissingOption (for flags) and MissingArgument (for positional arguments)\n    Effect.catchTags({\n      MissingOption: () => Effect.succeed([args.arguments, Option.none()]),\n      MissingArgument: () => Effect.succeed([args.arguments, Option.none()])\n    }));\n  });\n  return Object.assign(Object.create(Proto), {\n    _tag: \"Optional\",\n    kind: param.kind,\n    param,\n    parse\n  });\n};\n/**\n * Makes a flag or positional argument optional by supplying a fallback value.\n *\n * **Details**\n *\n * The fallback may be a pure value or an effect. It is used only when the\n * parameter is absent; provided values are parsed normally.\n *\n * **Example** (Providing default values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Using the pipe operator to make an option optional\n * const port = Param.integer(Param.flagKind, \"port\").pipe(\n *   Param.withDefault(8080)\n * )\n *\n * // Can also be used with other combinators\n * const verbose = Param.boolean(Param.flagKind, \"verbose\").pipe(\n *   Param.withAlias(\"-v\"),\n *   Param.withDescription(\"Enable verbose output\"),\n *   Param.withDefault(false)\n * )\n * const kinds = [port.kind, verbose.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withDefault = /*#__PURE__*/dual(2, (self, defaultValue) => {\n  if (!Effect.isEffect(defaultValue)) {\n    return map(optional(self), Option.getOrElse(() => defaultValue));\n  }\n  return mapEffect(optional(self), Option.match({\n    onNone: () => defaultValue,\n    onSome: Effect.succeed\n  }));\n});\n/**\n * Adds a fallback config that is loaded when a required parameter is missing.\n *\n * **When to use**\n *\n * Use when you need config to provide a fallback source for required flags or\n * arguments that are absent from CLI input.\n *\n * **Details**\n *\n * Provided CLI values win. Config is loaded only after a missing option or\n * missing argument error.\n *\n * **Gotchas**\n *\n * Missing config preserves the original missing-parameter error. Config parse\n * failure becomes `CliError.InvalidValue`.\n *\n * @see {@link withDefault} for a pure default value\n * @see {@link withFallbackPrompt} for prompting interactively when input is missing\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => {\n  const toInvalidValue = (error, configError) => new CliError.InvalidValue({\n    option: error._tag === \"MissingOption\" ? error.option : error.argument,\n    value: \"config\",\n    expected: configError.message,\n    kind: error._tag === \"MissingOption\" ? \"flag\" : \"argument\"\n  });\n  const runConfig = (error, args) => Config.option(config).pipe(Effect.mapError(configError => toInvalidValue(error, configError)), Effect.flatMap(Option.match({\n    onNone: () => Effect.fail(error),\n    onSome: value => Effect.succeed([args.arguments, value])\n  })));\n  return transform(self, parse => args => parse(args).pipe(Effect.catchTag([\"MissingOption\", \"MissingArgument\"], error => runConfig(error, args))));\n});\n/**\n * Adds a fallback prompt that is shown when a required parameter is missing.\n *\n * **When to use**\n *\n * Use when a CLI should ask interactively for a missing required flag or\n * argument.\n *\n * **Details**\n *\n * `FallbackPrompt` accepts either a `Prompt` or an effect that builds one.\n * Effectful prompt creation is lazy and runs only when the fallback is needed.\n *\n * **Gotchas**\n *\n * This only handles missing options and missing arguments. Invalid values do not\n * prompt, and prompt cancellation re-fails with the original missing error.\n *\n * @see {@link FallbackPrompt} for accepted fallback prompt forms\n * @see {@link withFallbackConfig} for loading a fallback from config\n * @see {@link withDefault} for a pure default value\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => {\n  const runPrompt = (error, args) => Effect.flatMap(Prompt.isPrompt(prompt) ? Effect.succeed(prompt) : prompt, Prompt.run).pipe(Effect.map(value => [args.arguments, value]), Effect.catchTag(\"QuitError\", () => Effect.fail(error)));\n  return transform(self, parse => args => parse(args).pipe(Effect.catchTag([\"MissingOption\", \"MissingArgument\"], error => runPrompt(error, args))));\n});\n/**\n * Creates a variadic parameter that can be specified multiple times.\n *\n * **Details**\n *\n * This is the base combinator for creating parameters that accept multiple values.\n * The `min` and `max` parameters are optional. When they are not provided, the\n * parameter can be specified any number of times, from 0 to infinity.\n *\n * **Example** (Accepting multiple values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Basic variadic parameter (0 to infinity)\n * const tags = Param.variadic(Param.string(Param.flagKind, \"tag\"))\n *\n * // Variadic with minimum count\n * const inputs = Param.variadic(\n *   Param.string(Param.flagKind, \"input\"),\n *   { min: 1 } // at least 1 required\n * )\n *\n * // Variadic with both min and max\n * const limited = Param.variadic(Param.string(Param.flagKind, \"item\"), {\n *   min: 2, // at least 2 times\n *   max: 2 // at most 2 times\n * })\n * const kinds = [tags.kind, inputs.kind, limited.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const variadic = (self, options) => {\n  const single = getUnderlyingSingleOrThrow(self);\n  const parse = args => {\n    if (single.kind === \"argument\") {\n      return parsePositionalVariadic(self, single, args, options);\n    } else {\n      return parseOptionVariadic(self, single, args, options);\n    }\n  };\n  return Object.assign(Object.create(Proto), {\n    _tag: \"Variadic\",\n    kind: self.kind,\n    param: self,\n    min: Option.fromUndefinedOr(options?.min),\n    max: Option.fromUndefinedOr(options?.max),\n    parse\n  });\n};\n/**\n * Wraps an option to allow it to be specified multiple times within a range.\n *\n * **Details**\n *\n * This combinator transforms an option to accept between `min` and `max`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Bounding repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Allow 1-3 file inputs\n * const files = Param.string(Param.flagKind, \"file\").pipe(\n *   Param.between(1, 3),\n *   Param.withAlias(\"-f\")\n * )\n *\n * // Parse: --file a.txt --file b.txt\n * // Result: [\"a.txt\", \"b.txt\"]\n *\n * // Allow 0 or more tags\n * const tags = Param.string(Param.flagKind, \"tag\").pipe(\n *   Param.between(0, Number.MAX_SAFE_INTEGER)\n * )\n *\n * // Parse: --tag dev --tag staging --tag v1.0\n * // Result: [\"dev\", \"staging\", \"v1.0\"]\n * const kinds = [files.kind, tags.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => {\n  if (min < 0) {\n    throw new Error(\"between: min must be non-negative\");\n  }\n  if (max < min) {\n    throw new Error(\"between: max must be greater than or equal to min\");\n  }\n  return variadic(self, {\n    min,\n    max\n  });\n});\n/**\n * Wraps an option to allow it to be specified at most `max` times.\n *\n * **Details**\n *\n * This combinator transforms an option to accept between 0 and `max`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Limiting repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Allow at most 3 warning suppressions\n * const suppressions = Param.string(Param.flagKind, \"suppress\").pipe(\n *   Param.atMost(3)\n * )\n *\n * // Parse: --suppress warning1 --suppress warning2\n * // Result: [\"warning1\", \"warning2\"]\n * suppressions.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => {\n  if (max < 0) {\n    throw new Error(\"atMost: max must be non-negative\");\n  }\n  return variadic(self, {\n    max\n  });\n});\n/**\n * Wraps an option to require it to be specified at least `min` times.\n *\n * **Details**\n *\n * This combinator transforms an option to accept at least `min`\n * occurrences on the command line, returning an array of all provided values.\n *\n * **Example** (Requiring repeated values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * // Require at least 2 input files\n * const inputs = Param.string(Param.flagKind, \"input\").pipe(\n *   Param.atLeast(2),\n *   Param.withAlias(\"-i\")\n * )\n *\n * // Parse: --input file1.txt --input file2.txt --input file3.txt\n * // Result: [\"file1.txt\", \"file2.txt\", \"file3.txt\"]\n * inputs.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => {\n  if (min < 0) {\n    throw new Error(\"atLeast: min must be non-negative\");\n  }\n  return variadic(self, {\n    min\n  });\n});\n/**\n * Filters and transforms parsed values, failing with a custom error message\n * if the filter function returns `Option.none()`.\n *\n * **When to use**\n *\n * Use when you need validation and transformation in a single parameter\n * combinator.\n *\n * **Example** (Filtering and transforming values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Param } from \"effect/unstable/cli\"\n * const positiveInt = Param.integer(Param.flagKind, \"count\").pipe(\n *   Param.filterMap(\n *     (n) => n > 0 ? Option.some(n) : Option.none(),\n *     (n) => `Expected positive integer, got ${n}`\n *   )\n * )\n * positiveInt.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, filter, onNone) => mapEffect(self, Effect.fnUntraced(function* (a) {\n  const result = filter(a);\n  if (Option.isSome(result)) {\n    return result.value;\n  }\n  const single = getUnderlyingSingleOrThrow(self);\n  return yield* new CliError.InvalidValue({\n    option: single.name,\n    value: String(a),\n    expected: onNone(a),\n    kind: single.kind\n  });\n})));\n/**\n * Filters parsed values, failing with a custom error message if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const evenNumber = Param.integer(Param.flagKind, \"num\").pipe(\n *   Param.filter(\n *     (n) => n % 2 === 0,\n *     (n) => `Expected even number, got ${n}`\n *   )\n * )\n * evenNumber.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => filterMap(self, Option.liftPredicate(predicate), onFalse));\n/**\n * Sets a custom metavar (placeholder name) for the param in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should provide.\n * For example, `--output FILE` shows `FILE` as the metavar.\n *\n * **Example** (Setting metavars)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const port = Param.integer(Param.flagKind, \"port\").pipe(\n *   Param.withMetavar(\"PORT\"),\n *   Param.filter(\n *     (p) => p >= 1 && p <= 65535,\n *     () => \"Port must be between 1 and 65535\"\n *   )\n * )\n * port.kind // => \"flag\"\n * ```\n *\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => transformSingle(self, single => makeSingle({\n  ...single,\n  typeName: metavar\n})));\n/**\n * Validates parsed values against a Schema, providing detailed error messages.\n *\n * **Example** (Validating with schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Param } from \"effect/unstable/cli\"\n * const isEmail = Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)\n *\n * const Email = Schema.String.pipe(\n *   Schema.check(isEmail)\n * )\n *\n * const email = Param.string(Param.flagKind, \"email\").pipe(\n *   Param.withSchema(Email)\n * )\n * email.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => {\n  const decodeParam = Schema.decodeUnknownEffect(schema);\n  return mapEffect(self, value => Effect.mapError(decodeParam(value), error => {\n    const single = getUnderlyingSingleOrThrow(self);\n    return new CliError.InvalidValue({\n      option: single.name,\n      value: String(value),\n      expected: `Schema validation failed: ${error.message}`,\n      kind: single.kind\n    });\n  }));\n});\n/**\n * Provides a fallback param to use if this param fails to parse.\n *\n * **Example** (Falling back to another parameter)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const config = Param.file(Param.flagKind, \"config\").pipe(\n *   Param.orElse(() => Param.string(Param.flagKind, \"config-url\"))\n * )\n * config.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, orElse) => transform(self, parse => args => Effect.catch(parse(args), err => orElse(err).parse(args))));\n/**\n * Provides a fallback param and returns a `Result` indicating which param\n * succeeded.\n *\n * **Details**\n *\n * The original param's value is returned as `Result.succeed`, while the\n * fallback param's value is returned as `Result.fail`.\n *\n * **Example** (Returning fallback results)\n *\n * ```ts import.meta.vitest\n * import { Param } from \"effect/unstable/cli\"\n *\n * const configSource = Param.file(Param.flagKind, \"config\").pipe(\n *   Param.orElseResult(() => Param.string(Param.flagKind, \"config-url\"))\n * )\n * // Returns Result<string, string>\n * configSource.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, orElse) => {\n  return transform(self, parse => args => Effect.catch(Effect.map(parse(args), ([leftover, value]) => [leftover, Result.succeed(value)]), err => Effect.map(orElse(err).parse(args), ([leftover, value]) => [leftover, Result.fail(value)])));\n});\n// =============================================================================\n// Parsing Utilities\n// =============================================================================\nconst parsePositional = /*#__PURE__*/Effect.fnUntraced(function* (name, primitiveType, args) {\n  if (args.arguments.length === 0) {\n    return yield* new CliError.MissingArgument({\n      argument: name\n    });\n  }\n  const arg = args.arguments[0];\n  const value = yield* Effect.mapError(primitiveType.parse(arg), error => new CliError.InvalidValue({\n    option: name,\n    value: arg,\n    expected: error,\n    kind: \"argument\"\n  }));\n  return [args.arguments.slice(1), value];\n});\nconst parseFlag = /*#__PURE__*/Effect.fnUntraced(function* (name, primitiveType, args) {\n  const providedValues = args.flags[name];\n  if (providedValues === undefined || providedValues.length === 0) {\n    // Option not provided (empty array due to initialization)\n    if (Primitive.isBoolean(primitiveType)) {\n      // Boolean params default to false when not present\n      return [args.arguments, false];\n    } else {\n      return yield* new CliError.MissingOption({\n        option: name\n      });\n    }\n  }\n  // Parse the first value (later we can handle multiple)\n  const arg = providedValues[0];\n  const value = yield* Effect.mapError(primitiveType.parse(arg), error => new CliError.InvalidValue({\n    option: name,\n    value: arg,\n    expected: error,\n    kind: \"flag\"\n  }));\n  return [args.arguments, value];\n});\nconst parsePositionalVariadic = /*#__PURE__*/Effect.fnUntraced(function* (self, single, args, options) {\n  const results = [];\n  const minValue = options?.min ?? 0;\n  const maxValue = options?.max ?? Number.POSITIVE_INFINITY;\n  let count = 0;\n  let currentArgs = args.arguments;\n  while (currentArgs.length > 0 && count < maxValue) {\n    const [remainingArgs, value] = yield* self.parse({\n      flags: args.flags,\n      arguments: currentArgs\n    });\n    results.push(value);\n    currentArgs = remainingArgs;\n    count++;\n  }\n  if (count < minValue) {\n    return yield* new CliError.InvalidValue({\n      option: single.name,\n      value: `${count} values`,\n      expected: `at least ${minValue} value${minValue === 1 ? \"\" : \"s\"}`,\n      kind: single.kind\n    });\n  }\n  return [currentArgs, results];\n});\nconst parseOptionVariadic = /*#__PURE__*/Effect.fnUntraced(function* (self, single, args, options) {\n  const results = [];\n  const names = [single.name, ...single.aliases];\n  const values = names.flatMap(name => args.flags[name] ?? []);\n  const count = values.length;\n  // Validate count constraints\n  if (Predicate.isNotUndefined(options?.min) && count < options.min) {\n    return yield* count === 0 ? new CliError.MissingOption({\n      option: single.name\n    }) : new CliError.InvalidValue({\n      option: single.name,\n      value: `${count} occurrences`,\n      expected: `at least ${options.min} value${options.min === 1 ? \"\" : \"s\"}`,\n      kind: single.kind\n    });\n  }\n  if (Predicate.isNotUndefined(options?.max) && count > options.max) {\n    return yield* new CliError.InvalidValue({\n      option: single.name,\n      value: `${count} occurrences`,\n      expected: `at most ${options.max} value${options.max === 1 ? \"\" : \"s\"}`,\n      kind: single.kind\n    });\n  }\n  // Parse each value individually\n  for (const value of values) {\n    const [, parsedValue] = yield* self.parse({\n      flags: {\n        [single.name]: [value]\n      },\n      arguments: []\n    });\n    results.push(parsedValue);\n  }\n  return [args.arguments, results];\n});\n/**\n * Type-safe param matcher that handles the unsafe casting internally.\n * This provides a clean API for pattern matching on param types while\n * maintaining type safety at the call site.\n */\nconst matchParam = (param, patterns) => {\n  const p = param;\n  switch (p._tag) {\n    case \"Single\":\n      return patterns.Single(p);\n    case \"Map\":\n      return patterns.Map(p);\n    case \"Transform\":\n      return patterns.Transform(p);\n    case \"Optional\":\n      return patterns.Optional(p);\n    case \"Variadic\":\n      return patterns.Variadic(p);\n  }\n};\n/**\n * Recursively transforms a param by applying a function to any `Single` nodes.\n * This is used internally by combinators like `withAlias` to traverse the param tree.\n */\nconst transformSingle = (param, f) => {\n  return matchParam(param, {\n    Single: single => f(single),\n    Map: mapped => map(transformSingle(mapped.param, f), mapped.f),\n    Transform: mapped => transform(transformSingle(mapped.param, f), mapped.f),\n    Optional: p => optional(transformSingle(p.param, f)),\n    Variadic: p => variadic(transformSingle(p.param, f), {\n      min: Option.getOrUndefined(p.min),\n      max: Option.getOrUndefined(p.max)\n    })\n  });\n};\n/**\n * Extracts all Single params from a potentially nested param structure.\n * This handles all param combinators including Map, Transform, Optional, and Variadic.\n *\n * @internal\n */\nexport const extractSingleParams = param => {\n  return matchParam(param, {\n    Single: single => [single],\n    Map: mapped => extractSingleParams(mapped.param),\n    Transform: mapped => extractSingleParams(mapped.param),\n    Optional: optional => extractSingleParams(optional.param),\n    Variadic: variadic => extractSingleParams(variadic.param)\n  });\n};\n/**\n * Gets the underlying Single param from a potentially nested param structure.\n * Throws an error if there are no singles or multiple singles found.\n *\n * @internal\n */\nexport const getUnderlyingSingleOrThrow = param => {\n  const singles = extractSingleParams(param);\n  if (singles.length === 0) {\n    throw new Error(\"No Single param found in param structure\");\n  }\n  if (singles.length > 1) {\n    throw new Error(`Multiple Single params found: ${singles.map(s => s.name).join(\", \")}`);\n  }\n  return singles[0];\n};\n/**\n * Gets param metadata by traversing the structure.\n *\n * @internal\n */\nexport const getParamMetadata = param => {\n  return matchParam(param, {\n    Single: () => ({\n      isOptional: false,\n      isVariadic: false,\n      variadicMin: Option.none(),\n      variadicMax: Option.none()\n    }),\n    Map: mapped => getParamMetadata(mapped.param),\n    Transform: mapped => getParamMetadata(mapped.param),\n    Optional: optional => ({\n      ...getParamMetadata(optional.param),\n      isOptional: true\n    }),\n    Variadic: variadic => ({\n      ...getParamMetadata(variadic.param),\n      isVariadic: true,\n      variadicMin: variadic.min,\n      variadicMax: variadic.max\n    })\n  });\n};\n//# sourceMappingURL=Param.js.map","import { dual } from \"../../Function.js\";\nimport * as Param from \"./Param.js\";\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a positional string argument.\n *\n * **Example** (Creating a string argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const filename = Argument.string(\"filename\")\n * filename.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const string = name => Param.string(Param.argumentKind, name);\n/**\n * Creates a positional integer argument.\n *\n * **Example** (Creating an integer argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const count = Argument.integer(\"count\")\n * count.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const integer = name => Param.integer(Param.argumentKind, name);\n/**\n * Creates a positional file path argument.\n *\n * **Example** (Creating file path arguments)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const inputFile = Argument.file(\"input\", { mustExist: true }) // Must exist\n * const outputFile = Argument.file(\"output\", { mustExist: false }) // Must not exist\n * const kinds = [inputFile.kind, outputFile.kind] // => [\"argument\", \"argument\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (name, options) => Param.file(Param.argumentKind, name, options);\n/**\n * Creates a positional directory path argument.\n *\n * **Example** (Creating a directory path argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const workspace = Argument.directory(\"workspace\", { mustExist: true }) // Must exist\n * workspace.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const directory = (name, options) => Param.directory(Param.argumentKind, name, options);\n/**\n * Creates a positional float argument.\n *\n * **Example** (Creating a float argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const ratio = Argument.float(\"ratio\")\n * ratio.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const float = name => Param.float(Param.argumentKind, name);\n/**\n * Creates a positional date argument.\n *\n * **Example** (Creating a date argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const startDate = Argument.date(\"start-date\")\n * startDate.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const date = name => Param.date(Param.argumentKind, name);\n/**\n * Creates a positional choice argument.\n *\n * **Example** (Creating a choice argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const environment = Argument.choice(\"environment\", [\"dev\", \"staging\", \"prod\"])\n * environment.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choice = (name, choices) => Param.choice(Param.argumentKind, name, choices);\n/**\n * Creates a positional path argument.\n *\n * **Example** (Creating a path argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const configPath = Argument.path(\"config\")\n * configPath.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const path = (name, options) => Param.path(Param.argumentKind, name, options);\n/**\n * Creates a positional redacted argument that obscures its value.\n *\n * **Example** (Creating a redacted argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const secret = Argument.redacted(\"secret\")\n * secret.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const redacted = name => Param.redacted(Param.argumentKind, name);\n/**\n * Creates a positional argument that reads file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const config = Argument.fileText(\"config-file\")\n * config.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileText = name => Param.fileText(Param.argumentKind, name);\n/**\n * Creates a positional argument that reads a file and parses its content.\n *\n * **Details**\n *\n * The parser is chosen from the explicit `format` option or, when omitted, the\n * file extension. The parsed value is `unknown`; use `fileSchema` when the\n * parsed content should also be decoded with a Schema.\n *\n * **Example** (Parsing file content)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const config = Argument.fileParse(\"config\", { format: \"json\" })\n * config.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileParse = (name, options) => Param.fileParse(Param.argumentKind, name, options);\n/**\n * Creates a positional argument that reads and validates file content using a schema.\n *\n * **Example** (Validating file content with a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const ConfigSchema = Schema.Struct({\n *   port: Schema.Number,\n *   host: Schema.String\n * })\n *\n * const config = Argument.fileSchema(\"config\", ConfigSchema)\n * config.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileSchema = (name, schema, options) => Param.fileSchema(Param.argumentKind, name, schema, options);\n/**\n * Creates an empty sentinel argument that always fails to parse.\n *\n * **Example** (Creating a sentinel argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * // Used as a placeholder or default in combinators\n * const noArg = Argument.none\n * noArg.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const none = /*#__PURE__*/Param.none(Param.argumentKind);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Makes a positional argument optional.\n *\n * **Example** (Making an argument optional)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const optionalVersion = Argument.string(\"version\").pipe(Argument.optional)\n * optionalVersion.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const optional = arg => Param.optional(arg);\n/**\n * Adds a description to a positional argument.\n *\n * **Example** (Adding an argument description)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const filename = Argument.string(\"filename\").pipe(\n *   Argument.withDescription(\"The input file to process\")\n * )\n * filename.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => Param.withDescription(self, description));\n/**\n * Provides a default value for a positional argument.\n *\n * **Example** (Providing a default value)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const port = Argument.integer(\"port\").pipe(Argument.withDefault(8080))\n * port.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withDefault = Param.withDefault;\n/**\n * Adds a fallback config that is loaded when a required argument is missing.\n *\n * **Example** (Loading a fallback config)\n *\n * ```ts import.meta.vitest\n * import { Config } from \"effect\"\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const repository = Argument.string(\"repository\").pipe(\n *   Argument.withFallbackConfig(Config.string(\"REPOSITORY\"))\n * )\n * repository.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => Param.withFallbackConfig(self, config));\n/**\n * Adds a fallback prompt that is shown when a required argument is missing.\n *\n * **Example** (Showing a fallback prompt)\n *\n * ```ts import.meta.vitest\n * import { Argument, Prompt } from \"effect/unstable/cli\"\n *\n * const filename = Argument.string(\"filename\").pipe(\n *   Argument.withFallbackPrompt(Prompt.text({ message: \"Filename\" }))\n * )\n * filename.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => Param.withFallbackPrompt(self, prompt));\n/**\n * Creates a variadic positional argument that accepts multiple values.\n *\n * **Example** (Accepting multiple values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * // Accept any number of files\n * const anyFiles = Argument.string(\"files\").pipe(Argument.variadic)\n *\n * // Accept at least 1 file\n * const atLeastOneFile = Argument.string(\"files\").pipe(\n *   Argument.variadic({ min: 1 })\n * )\n *\n * // Accept between 1 and 5 files\n * const limitedFiles = Argument.string(\"files\").pipe(\n *   Argument.variadic({ min: 1, max: 5 })\n * )\n *\n * const kinds = [anyFiles.kind, atLeastOneFile.kind, limitedFiles.kind] // => [\"argument\", \"argument\", \"argument\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const variadic = /*#__PURE__*/dual(args => Param.isParam(args[0]), (self, options) => Param.variadic(self, options));\n/**\n * Transforms the parsed value of a positional argument.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const port = Argument.integer(\"port\").pipe(\n *   Argument.map((p) => ({ port: p, url: `http://localhost:${p}` }))\n * )\n * port.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => Param.map(self, f));\n/**\n * Transforms the parsed value of a positional argument using an effectful function.\n *\n * **Example** (Validating values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument, CliError } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const files = Argument.string(\"files\").pipe(\n *   Argument.mapEffect((file) =>\n *     file.endsWith(\".txt\")\n *       ? Effect.succeed(file)\n *       : Effect.fail(\n *         new CliError.UserError({\n *           cause: new Error(\"Only .txt files allowed\")\n *         })\n *       )\n *   )\n * )\n *\n * const [, value] = await Effect.runPromise(\n *   files.parse({ arguments: [\"notes.txt\"], flags: {} }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"notes.txt\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => Param.mapEffect(self, f));\n/**\n * Transforms the parsed value of a positional argument using a function that may throw.\n *\n * **Example** (Mapping values that may throw)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const json = Argument.string(\"data\").pipe(\n *   Argument.mapTryCatch(\n *     (str) => JSON.parse(str),\n *     (error) =>\n *       `Invalid JSON: ${error instanceof Error ? error.message : String(error)}`\n *   )\n * )\n *\n * const [, value] = await Effect.runPromise(\n *   json.parse({ arguments: ['{\"enabled\":true}'], flags: {} }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => Param.mapTryCatch(self, f, onError));\n/**\n * Creates a variadic argument that requires at least n values.\n *\n * **Example** (Requiring a minimum number of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const files = Argument.string(\"files\").pipe(Argument.atLeast(1))\n * files.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => Param.atLeast(self, min));\n/**\n * Creates a variadic argument that accepts at most n values.\n *\n * **Example** (Limiting the maximum number of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const files = Argument.string(\"files\").pipe(Argument.atMost(5))\n * files.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => Param.atMost(self, max));\n/**\n * Creates a variadic argument that accepts between min and max values.\n *\n * **Example** (Requiring a range of values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const files = Argument.string(\"files\").pipe(Argument.between(1, 5))\n * files.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => Param.between(self, min, max));\n/**\n * Validates parsed values against a Schema.\n *\n * **Example** (Validating parsed values with a schema)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const input = Argument.string(\"input\").pipe(\n *   Argument.withSchema(Schema.NonEmptyString)\n * )\n * input.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => Param.withSchema(self, schema));\n/**\n * Creates a positional choice argument with custom value mapping.\n *\n * **Example** (Mapping choices to values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const logLevel = Argument.choiceWithValue(\"level\", [\n *   [\"debug\", 0],\n *   [\"info\", 1],\n *   [\"warn\", 2],\n *   [\"error\", 3]\n * ])\n * logLevel.kind // => \"argument\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choiceWithValue = (name, choices) => Param.choiceWithValue(Param.argumentKind, name, choices);\n// -------------------------------------------------------------------------------------\n// metadata\n// -------------------------------------------------------------------------------------\n/**\n * Sets a custom metavar (placeholder name) for the argument in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should provide.\n * For example, `<FILE>` shows `FILE` as the metavar.\n *\n * **Example** (Setting a metavar)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const port = Argument.integer(\"port\").pipe(\n *   Argument.withMetavar(\"PORT\")\n * )\n * port.kind // => \"argument\"\n * ```\n *\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => Param.withMetavar(self, metavar));\n/**\n * Filters parsed values, failing with a custom error message if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const positiveInt = Argument.integer(\"count\").pipe(\n *   Argument.filter(\n *     (n) => n > 0,\n *     (n) => `Expected positive integer, got ${n}`\n *   )\n * )\n * positiveInt.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => Param.filter(self, predicate, onFalse));\n/**\n * Filters and transforms parsed values, failing with a custom error message\n * if the filter function returns None.\n *\n * **Example** (Filtering and mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const positiveInt = Argument.integer(\"count\").pipe(\n *   Argument.filterMap(\n *     (n) => n > 0 ? Option.some(n) : Option.none(),\n *     (n) => `Expected positive integer, got ${n}`\n *   )\n * )\n * positiveInt.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, f, onNone) => Param.filterMap(self, f, onNone));\n/**\n * Provides a fallback argument to use if this argument fails to parse.\n *\n * **Example** (Providing a fallback argument)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const value = Argument.integer(\"value\").pipe(\n *   Argument.orElse(() => Argument.string(\"value\"))\n * )\n * value.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => Param.orElse(self, that));\n/**\n * Provides a fallback argument, wrapping results in Result to distinguish which succeeded.\n *\n * **Example** (Returning which fallback succeeded)\n *\n * ```ts import.meta.vitest\n * import { Argument } from \"effect/unstable/cli\"\n *\n * const source = Argument.file(\"source\").pipe(\n *   Argument.orElseResult(() => Argument.string(\"url\"))\n * )\n * // Returns Result<string, string>\n * source.kind // => \"argument\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => Param.orElseResult(self, that));\n//# sourceMappingURL=Argument.js.map","import { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\n/**\n * Context reference for the current console service in the Effect system, allowing access to the active console implementation from within the Effect context.\n *\n * **When to use**\n *\n * Use when you need an effect to run against a provided console implementation,\n * such as tests or alternate runtimes, rather than the default console.\n *\n * **Details**\n *\n * When no override is provided, the reference resolves to `globalThis.console`.\n *\n * **Example** (Accessing the current console)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   log: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Console.consoleWith((console) =>\n *   Effect.sync(() => {\n *     console.log(\"Hello from current console!\")\n *   })\n * )\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"Hello from current console!\"]\n * ```\n *\n * @see {@link consoleWith} for using the current console service inside an effect\n *\n * @category services\n * @since 2.0.0\n */\nexport const Console = effect.ConsoleRef;\n/**\n * Creates an Effect that provides access to the current console service and lets you perform operations with it within an Effect context.\n *\n * **Example** (Accessing the current console service)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   log: (...args: ReadonlyArray<unknown>) => messages.push(...args),\n *   error: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Console.consoleWith((console) =>\n *   Effect.sync(() => {\n *     console.log(\"Hello, world!\")\n *     console.error(\"This is an error message\")\n *   })\n * )\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"Hello, world!\", \"This is an error message\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const consoleWith = f => core.withFiber(fiber => f(fiber.getRef(Console)));\n/**\n * Writes the supplied assertion message to the console as an error when `condition` is false; when `condition` is true, no console output is produced.\n *\n * **Example** (Logging failed assertions)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const errors: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   assert: (condition: boolean, ...args: ReadonlyArray<unknown>) => {\n *     if (!condition) errors.push(...args)\n *   }\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.assert(2 + 2 === 4, \"Math is working correctly\")\n *   yield* Console.assert(2 + 2 === 5, \"This will be logged as an error\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * errors // => [\"This will be logged as an error\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const assert = (condition, ...args) => consoleWith(console => effect.sync(() => {\n  console.assert(condition, ...args);\n}));\n/**\n * Runs the current console service's clear operation.\n *\n * **When to use**\n *\n * Use to request that the active console implementation clear its visible\n * output.\n *\n * **Gotchas**\n *\n * The clearing behavior depends on the active console implementation and host\n * environment.\n *\n * **Example** (Clearing console output)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   log: (message: string) => operations.push(`log:${message}`),\n *   clear: () => operations.push(\"clear\")\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.log(\"This will be cleared\")\n *   yield* Console.clear\n *   yield* Console.log(\"This appears after clearing\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"log:This will be cleared\", \"clear\", \"log:This appears after clearing\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const clear = /*#__PURE__*/consoleWith(console => effect.sync(() => {\n  console.clear();\n}));\n/**\n * Logs and increments the counter associated with `label`, using the console's default counter when no label is provided.\n *\n * **Example** (Counting repeated calls)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const counters = new Map<string, number>()\n * const messages: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   count: (label = \"default\") => {\n *     const count = (counters.get(label) ?? 0) + 1\n *     counters.set(label, count)\n *     messages.push(`${label}: ${count}`)\n *   }\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.count(\"my-counter\")\n *   yield* Console.count(\"my-counter\")\n *   yield* Console.count()\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"my-counter: 1\", \"my-counter: 2\", \"default: 1\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const count = label => consoleWith(console => effect.sync(() => {\n  console.count(label);\n}));\n/**\n * Resets the counter associated with the specified label back to zero.\n *\n * **Example** (Resetting a counter)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const counters = new Map<string, number>()\n * const messages: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   count: (label = \"default\") => {\n *     const count = (counters.get(label) ?? 0) + 1\n *     counters.set(label, count)\n *     messages.push(`${label}: ${count}`)\n *   },\n *   countReset: (label = \"default\") => counters.set(label, 0)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.count(\"my-counter\")\n *   yield* Console.count(\"my-counter\")\n *   yield* Console.countReset(\"my-counter\")\n *   yield* Console.count(\"my-counter\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"my-counter: 1\", \"my-counter: 2\", \"my-counter: 1\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const countReset = label => consoleWith(console => effect.sync(() => {\n  console.countReset(label);\n}));\n/**\n * Writes a debug message through the current `Console` service.\n *\n * **Details**\n *\n * The arguments are passed to the service's `debug` method when the returned\n * Effect is executed. Any filtering behavior depends on the active console\n * implementation.\n *\n * **Example** (Writing debug messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   debug: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.debug(\"Debug info:\", { userId: 123, action: \"login\" })\n *   yield* Console.debug(\"Processing step\", 1, \"of\", 5)\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [[\"Debug info:\", { userId: 123, action: \"login\" }], [\"Processing step\", 1, \"of\", 5]]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const debug = (...args) => consoleWith(console => effect.sync(() => {\n  console.debug(...args);\n}));\n/**\n * Displays an interactive list of the properties of the specified object, optionally using console-specific inspection options for debugging complex data structures.\n *\n * **Example** (Inspecting an object)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const inspected: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   dir: (item: unknown, options?: unknown) => inspected.push([item, options])\n * })\n * const program = Effect.gen(function*() {\n *   const obj = { name: \"John\", age: 30, nested: { city: \"New York\" } }\n *   yield* Console.dir(obj)\n *   yield* Console.dir(obj, { depth: 2 })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   [{ name: \"John\", age: 30, nested: { city: \"New York\" } }, undefined],\n *   [{ name: \"John\", age: 30, nested: { city: \"New York\" } }, { depth: 2 }]\n * ]\n * inspected // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const dir = (item, options) => consoleWith(console => effect.sync(() => {\n  console.dir(item, options);\n}));\n/**\n * Displays an interactive tree of descendant XML or HTML elements, which is particularly useful for inspecting DOM elements in browser environments.\n *\n * **Example** (Inspecting XML-like data)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   dirxml: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.dirxml(\"<user id=\\\"1\\\">Ada</user>\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"<user id=\\\"1\\\">Ada</user>\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const dirxml = (...args) => consoleWith(console => effect.sync(() => {\n  console.dirxml(...args);\n}));\n/**\n * Writes an error-level message to the console, typically displayed with error\n * styling by the active console implementation.\n *\n * **Example** (Writing error messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   error: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.error(\"Something went wrong!\")\n *   yield* Console.error(\"Error details:\", {\n *     code: 500,\n *     message: \"Internal Server Error\"\n *   })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   [\"Something went wrong!\"],\n *   [\"Error details:\", { code: 500, message: \"Internal Server Error\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const error = (...args) => consoleWith(console => effect.sync(() => {\n  console.error(...args);\n}));\n/**\n * Creates a scoped console group, optionally collapsed and labeled, and closes it automatically when the Effect scope is finalized.\n *\n * **Example** (Grouping scoped output)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   group: (label?: string) => operations.push(`group:${label}`),\n *   groupEnd: () => operations.push(\"groupEnd\"),\n *   log: (message: string) => operations.push(`log:${message}`)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Effect.scoped(\n *     Effect.gen(function*() {\n *       yield* Console.group({ label: \"User Processing\" })\n *       yield* Console.log(\"Loading user data...\")\n *       yield* Console.log(\"Validating user...\")\n *       yield* Console.log(\"User processed successfully\")\n *     })\n *   )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   \"group:User Processing\",\n *   \"log:Loading user data...\",\n *   \"log:Validating user...\",\n *   \"log:User processed successfully\",\n *   \"groupEnd\"\n * ]\n * operations // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const group = options => consoleWith(console => effect.acquireRelease(effect.sync(() => {\n  if (options?.collapsed) {\n    console.groupCollapsed(options.label);\n  } else {\n    console.group(options?.label);\n  }\n}), () => effect.sync(() => {\n  console.groupEnd();\n})));\n/**\n * Writes an informational message to the console, typically displayed with info\n * styling by the active console implementation.\n *\n * **Example** (Writing informational messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   info: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.info(\"Application started successfully\")\n *   yield* Console.info(\"Server configuration:\", {\n *     port: 3000,\n *     env: \"development\"\n *   })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   [\"Application started successfully\"],\n *   [\"Server configuration:\", { port: 3000, env: \"development\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const info = (...args) => consoleWith(console => effect.sync(() => {\n  console.info(...args);\n}));\n/**\n * Logs a general-purpose message to the console.\n *\n * **Example** (Writing log messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   log: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.log(\"Hello, world!\")\n *   yield* Console.log(\"User data:\", { name: \"John\", age: 30 })\n *   yield* Console.log(\"Processing\", 42, \"items\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   [\"Hello, world!\"],\n *   [\"User data:\", { name: \"John\", age: 30 }],\n *   [\"Processing\", 42, \"items\"]\n * ]\n * messages // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const log = (...args) => consoleWith(console => effect.sync(() => {\n  console.log(...args);\n}));\n/**\n * Displays tabular data as a formatted table in the console, optionally limited to selected properties.\n *\n * **Example** (Displaying tabular data)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const calls: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   table: (data: ReadonlyArray<unknown>, properties?: ReadonlyArray<string>) => {\n *     calls.push({ rows: data.length, properties })\n *   }\n * })\n *\n * const program = Effect.gen(function*() {\n *   const users = [\n *     { name: \"John\", age: 30, city: \"New York\" },\n *     { name: \"Jane\", age: 25, city: \"London\" },\n *     { name: \"Bob\", age: 35, city: \"Paris\" }\n *   ]\n *   yield* Console.table(users)\n *   yield* Console.table(users, [\"name\", \"age\"]) // Only show specific columns\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * calls // => [{ rows: 3, properties: undefined }, { rows: 3, properties: [\"name\", \"age\"] }]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const table = (tabularData, properties) => consoleWith(console => effect.sync(() => {\n  console.table(tabularData, properties);\n}));\n/**\n * Starts a scoped timer for `label` and automatically ends it when the Effect scope is finalized.\n *\n * **Example** (Timing scoped work)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   time: (label?: string) => operations.push(`start:${label}`),\n *   timeEnd: (label?: string) => operations.push(`end:${label}`),\n *   log: (message: string) => operations.push(`log:${message}`)\n * })\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.scoped(\n *     Effect.gen(function*() {\n *       yield* Console.time(\"operation-timer\")\n *       yield* Console.log(\"Operation completed\")\n *       // Timer ends automatically when scope closes\n *     })\n *   )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"start:operation-timer\", \"log:Operation completed\", \"end:operation-timer\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const time = label => consoleWith(console => effect.acquireRelease(effect.sync(() => {\n  console.time(label);\n}), () => effect.sync(() => {\n  console.timeEnd(label);\n})));\n/**\n * Logs the elapsed time for an existing timer without stopping it, allowing progress reports for long-running operations.\n *\n * **Example** (Logging timer progress)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   time: (label?: string) => operations.push([\"start\", label]),\n *   timeLog: (label?: string, ...args: ReadonlyArray<unknown>) => operations.push([\"log\", label, ...args]),\n *   timeEnd: (label?: string) => operations.push([\"end\", label])\n * })\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.scoped(\n *     Effect.gen(function*() {\n *       yield* Console.time(\"long-operation\")\n *       yield* Console.timeLog(\"long-operation\", \"Halfway done\")\n *       // Timer ends when scope closes\n *     })\n *   )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [[\"start\", \"long-operation\"], [\"log\", \"long-operation\", \"Halfway done\"], [\"end\", \"long-operation\"]]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const timeLog = (label, ...args) => consoleWith(console => effect.sync(() => {\n  console.timeLog(label, ...args);\n}));\n/**\n * Writes the current stack trace to the console to show how the current point in\n * the code was reached.\n *\n * **Example** (Writing stack traces)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const traces: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   trace: (...args: ReadonlyArray<unknown>) => traces.push(args)\n * })\n *\n * const program = Effect.gen(function*() {\n *   yield* Console.trace(\"Debug trace point\")\n *   yield* Console.trace(\"Function call:\", { functionName: \"processData\" })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * traces // => [[\"Debug trace point\"], [\"Function call:\", { functionName: \"processData\" }]]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const trace = (...args) => consoleWith(console => effect.sync(() => {\n  console.trace(...args);\n}));\n/**\n * Writes a warning-level message to the console, typically displayed with\n * warning styling by the active console implementation.\n *\n * **Example** (Writing warning messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   warn: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.warn(\"This feature is deprecated\")\n *   yield* Console.warn(\"Performance warning:\", {\n *     slowQuery: \"SELECT * FROM large_table\"\n *   })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   [\"This feature is deprecated\"],\n *   [\"Performance warning:\", { slowQuery: \"SELECT * FROM large_table\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const warn = (...args) => consoleWith(console => effect.sync(() => {\n  console.warn(...args);\n}));\n/**\n * Runs an Effect inside an optionally labeled or collapsed console group, starting the group before execution and ending it after the Effect completes.\n *\n * **Example** (Wrapping an effect in a group)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   group: (label?: string) => operations.push(`group:${label}`),\n *   groupEnd: () => operations.push(\"groupEnd\"),\n *   log: (message: string) => operations.push(`log:${message}`)\n * })\n * const program = Effect.gen(function*() {\n *   yield* Console.withGroup(\n *     Effect.gen(function*() {\n *       yield* Console.log(\"Step 1: Initialize\")\n *       yield* Console.log(\"Step 2: Process\")\n *       yield* Console.log(\"Step 3: Complete\")\n *     }),\n *     { label: \"Processing Steps\", collapsed: false }\n *   )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   \"group:Processing Steps\",\n *   \"log:Step 1: Initialize\",\n *   \"log:Step 2: Process\",\n *   \"log:Step 3: Complete\",\n *   \"groupEnd\"\n * ]\n * operations // => expected\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const withGroup = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, options) => consoleWith(console => effect.acquireUseRelease(effect.sync(() => {\n  if (options?.collapsed) {\n    console.groupCollapsed(options.label);\n  } else {\n    console.group(options?.label);\n  }\n}), () => self, () => effect.sync(() => {\n  console.groupEnd();\n}))));\n/**\n * Runs an Effect with a console timer, starting the timer before execution and ending it after the Effect completes.\n *\n * **Example** (Timing an effect)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   time: (label?: string) => operations.push(`start:${label}`),\n *   timeEnd: (label?: string) => operations.push(`end:${label}`),\n *   log: (message: string) => operations.push(`log:${message}`)\n * })\n *\n * const program = Effect.gen(function*() {\n *   yield* Console.withTime(\n *     Effect.gen(function*() {\n *       yield* Console.log(\"Operation completed\")\n *     }),\n *     \"my-operation\"\n *   )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"start:my-operation\", \"log:Operation completed\", \"end:my-operation\"]\n * ```\n *\n * @category accessors\n * @since 2.0.0\n */\nexport const withTime = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, label) => consoleWith(console => effect.acquireUseRelease(effect.sync(() => {\n  console.time(label);\n}), () => self, () => effect.sync(() => {\n  console.timeEnd(label);\n}))));\n//# sourceMappingURL=Console.js.map","/**\n * Formats CLI help and errors as text.\n *\n * This module turns help documents, CLI errors, grouped errors, and version\n * information into strings. It does not write those strings to the terminal\n * itself. It includes the `Formatter` interface, the formatter service, a layer\n * for custom formatters, and the default formatter with configurable color\n * support.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\n/**\n * Service reference for the CLI output formatter. Provides a default implementation\n * that can be overridden for custom formatting or testing.\n *\n * **Example** (Accessing the output formatter)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliOutput } from \"effect/unstable/cli\"\n *\n * // Access the formatter service\n * const program = Effect.gen(function*() {\n *   const formatter = yield* CliOutput.Formatter\n *\n *   // Format version information\n *   return formatter.formatVersion(\"my-cli\", \"2.1.0\")\n * })\n *\n * // Run with default formatter\n * await Effect.runPromise(program.pipe(\n *   Effect.provide(CliOutput.layer(CliOutput.defaultFormatter({ colors: false })))\n * )) // => \"my-cli v2.1.0\"\n * ```\n *\n * @category services\n * @since 4.0.0\n */\nexport const Formatter = /*#__PURE__*/Context.Reference(\"effect/cli/CliOutput\", {\n  defaultValue: () => defaultFormatter()\n});\n/**\n * Creates a Layer that provides a custom Formatter implementation.\n *\n * **Example** (Providing a custom formatter)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { CliOutput } from \"effect/unstable/cli\"\n *\n * // Create a custom formatter without colors\n * const noColorFormatter = CliOutput.defaultFormatter({ colors: false })\n * const NoColorLayer = CliOutput.layer(noColorFormatter)\n *\n * // Create a program that uses the custom formatter\n * const program = Effect.gen(function*() {\n *   const formatter = yield* CliOutput.Formatter\n *   return formatter.formatVersion(\"my-cli\", \"1.0.0\")\n * }).pipe(\n *   Effect.provide(NoColorLayer)\n * )\n *\n * await Effect.runPromise(program) // => \"my-cli v1.0.0\"\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = formatter => Layer.succeed(Formatter)(formatter);\nconst escapeControlCharacters = text =>\n// oxlint-disable-next-line no-control-regex\ntext.replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]/g, character => `\\\\x${character.charCodeAt(0).toString(16).padStart(2, \"0\")}`);\n/**\n * Creates a default formatter with configurable options.\n *\n * **Example** (Creating default formatters)\n *\n * ```ts import.meta.vitest\n * import { CliError, CliOutput } from \"effect/unstable/cli\"\n *\n * // Create a formatter without colors for tests or CI environments\n * const noColorFormatter = CliOutput.defaultFormatter({ colors: false })\n *\n * // Create a formatter with colors forced on\n * const colorFormatter = CliOutput.defaultFormatter({ colors: true })\n *\n * // Auto-detect colors based on terminal support (default behavior)\n * const autoFormatter = CliOutput.defaultFormatter()\n *\n * const error = new CliError.InvalidValue({\n *   option: \"foo\",\n *   value: \"bar\",\n *   expected: \"baz\",\n *   kind: \"flag\"\n * })\n *\n * noColorFormatter.formatError(error).includes(\"Invalid value\") // => true\n * colorFormatter.formatVersion(\"my-tool\", \"1.2.3\").includes(\"my-tool\") // => true\n * autoFormatter.formatVersion(\"my-tool\", \"1.2.3\").includes(\"1.2.3\") // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const defaultFormatter = options => {\n  const globalProcess = globalThis.process;\n  const hasProcess = typeof globalProcess === \"object\" && globalProcess !== null;\n  const useColor = options?.colors !== undefined ? options.colors\n  // Auto-detect based on environment\n  : hasProcess && typeof globalProcess.stdout === \"object\" && globalProcess.stdout !== null && globalProcess.stdout.isTTY === true && globalProcess.env?.NO_COLOR !== \"1\";\n  // Color palette using ANSI escape codes\n  const colors = useColor ? {\n    bold: text => `\\x1b[1m${text}\\x1b[0m`,\n    dim: text => `\\x1b[2m${text}\\x1b[0m`,\n    cyan: text => `\\x1b[36m${text}\\x1b[0m`,\n    green: text => `\\x1b[32m${text}\\x1b[0m`,\n    blue: text => `\\x1b[34m${text}\\x1b[0m`,\n    yellow: text => `\\x1b[33m${text}\\x1b[0m`,\n    magenta: text => `\\x1b[35m${text}\\x1b[0m`\n  } : {\n    bold: text => text,\n    dim: text => text,\n    cyan: text => text,\n    green: text => text,\n    blue: text => text,\n    yellow: text => text,\n    magenta: text => text\n  };\n  const reset = useColor ? \"\\x1b[0m\" : \"\";\n  const red = useColor ? \"\\x1b[31m\" : \"\";\n  const bold = useColor ? \"\\x1b[1m\" : \"\";\n  return {\n    formatHelpDoc: doc => formatHelpDocImpl(doc, colors),\n    formatCliError: error => escapeControlCharacters(error.message),\n    formatError: error => {\n      return `\\n${bold}${red}ERROR${reset}\\n  ${escapeControlCharacters(error.message)}${reset}`;\n    },\n    formatErrors: errors => {\n      if (errors.length === 0) return \"\";\n      if (errors.length === 1) {\n        return `\\n${bold}${red}ERROR${reset}\\n  ${escapeControlCharacters(errors[0].message)}${reset}`;\n      }\n      // Group errors by _tag\n      const grouped = new Map();\n      for (const error of errors) {\n        const tag = error._tag ?? \"Error\";\n        const group = grouped.get(tag) ?? [];\n        group.push(error);\n        grouped.set(tag, group);\n      }\n      const sections = [];\n      sections.push(`\\n${bold}${red}ERRORS${reset}`);\n      for (const [, group] of grouped) {\n        for (const error of group) {\n          sections.push(`  ${escapeControlCharacters(error.message)}${reset}`);\n        }\n      }\n      return sections.join(\"\\n\");\n    },\n    formatVersion: (name, version) => `${colors.bold(name)} ${colors.dim(\"v\")}${colors.bold(version)}`\n  };\n};\n/**\n * Strips ANSI escape codes from a string to calculate visual width.\n * @internal\n */\nconst stripAnsi = text => {\n  // oxlint-disable-next-line no-control-regex\n  return text.replace(/\\u001B\\[[0-9;]*m/g, \"\");\n};\n/**\n * Gets the visual length of a string (excluding ANSI codes).\n * @internal\n */\nconst visualLength = text => stripAnsi(text).length;\n/**\n * Helper function to pad strings to a specified width.\n * @internal\n */\nconst pad = (s, width) => {\n  const actualLength = visualLength(s);\n  const padding = Math.max(0, width - actualLength);\n  return s + \" \".repeat(padding);\n};\n/**\n * Renders a table with aligned columns.\n * @internal\n */\nconst renderTable = (rows, widthCap) => {\n  const maxColumn = Math.max(...rows.map(r => visualLength(r.left))) + 4;\n  const col = widthCap === undefined ? maxColumn : Math.min(maxColumn, widthCap);\n  return rows.map(({\n    left,\n    right\n  }) => `  ${pad(left, col)}${right}`).join(\"\\n\");\n};\nconst formatSubcommandName = (name, alias) => alias ? `${name}, ${alias}` : name;\n/**\n * Internal implementation of help formatting that accepts configurable color functions.\n * @internal\n */\nconst formatHelpDocImpl = (doc, colors) => {\n  const sections = [];\n  // Description section\n  if (doc.description) {\n    sections.push(colors.bold(\"DESCRIPTION\"));\n    sections.push(`  ${doc.description}`);\n    sections.push(\"\");\n  }\n  // Usage section\n  sections.push(colors.bold(\"USAGE\"));\n  sections.push(`  ${colors.cyan(doc.usage)}`);\n  sections.push(\"\");\n  // Arguments section\n  if (doc.args && doc.args.length > 0) {\n    sections.push(colors.bold(\"ARGUMENTS\"));\n    const argRows = doc.args.map(arg => {\n      let name = arg.name;\n      if (arg.variadic) {\n        name += \"...\";\n      }\n      const coloredName = colors.green(name);\n      const coloredType = colors.dim(arg.type);\n      const nameType = `${coloredName} ${coloredType}`;\n      const optionalSuffix = arg.required ? \"\" : colors.dim(\" (optional)\");\n      const description = Option.getOrElse(arg.description, () => \"\") + optionalSuffix;\n      return {\n        left: nameType,\n        right: description\n      };\n    });\n    sections.push(renderTable(argRows, 25));\n    sections.push(\"\");\n  }\n  // Flags section\n  if (doc.flags.length > 0) {\n    sections.push(colors.bold(\"FLAGS\"));\n    const flagRows = doc.flags.map(flag => {\n      const names = [];\n      // Add main name with -- prefix first\n      names.push(colors.green(`--${flag.name}`));\n      // Add aliases after (like -f) to match expected ordering\n      for (const alias of flag.aliases) {\n        names.push(colors.green(alias));\n      }\n      const namesPart = names.join(\", \");\n      const typePart = flag.type !== \"boolean\" ? ` ${colors.dim(flag.type)}` : \"\";\n      return {\n        left: namesPart + typePart,\n        right: Option.getOrElse(flag.description, () => \"\")\n      };\n    });\n    sections.push(renderTable(flagRows));\n    sections.push(\"\");\n  }\n  // Global Flags section\n  if (doc.globalFlags && doc.globalFlags.length > 0) {\n    sections.push(colors.bold(\"GLOBAL FLAGS\"));\n    const globalFlagRows = doc.globalFlags.map(flag => {\n      const names = [];\n      // Add main name with -- prefix first\n      names.push(colors.green(`--${flag.name}`));\n      // Add aliases after (like -f) to match expected ordering\n      for (const alias of flag.aliases) {\n        names.push(colors.green(alias));\n      }\n      const namesPart = names.join(\", \");\n      const typePart = flag.type !== \"boolean\" ? ` ${colors.dim(flag.type)}` : \"\";\n      return {\n        left: namesPart + typePart,\n        right: Option.getOrElse(flag.description, () => \"\")\n      };\n    });\n    sections.push(renderTable(globalFlagRows));\n    sections.push(\"\");\n  }\n  // Subcommands section\n  if (doc.subcommands && doc.subcommands.length > 0) {\n    const ungrouped = doc.subcommands.find(group => group.group === undefined);\n    if (ungrouped) {\n      sections.push(colors.bold(\"SUBCOMMANDS\"));\n      sections.push(renderTable(ungrouped.commands.map(sub => ({\n        left: colors.cyan(formatSubcommandName(sub.name, sub.alias)),\n        right: sub.shortDescription ?? sub.description\n      })), 20));\n      if (doc.subcommands.length > 1) {\n        sections.push(\"\");\n      }\n    }\n    for (const group of doc.subcommands) {\n      if (group.group === undefined) continue;\n      sections.push(colors.bold(`${group.group}:`));\n      sections.push(renderTable(group.commands.map(sub => ({\n        left: colors.cyan(formatSubcommandName(sub.name, sub.alias)),\n        right: sub.shortDescription ?? sub.description\n      })), 20));\n      sections.push(\"\");\n    }\n  }\n  // Examples section\n  if (doc.examples && doc.examples.length > 0) {\n    sections.push(colors.bold(\"EXAMPLES\"));\n    let first = true;\n    let previousHadDescription = false;\n    for (const example of doc.examples) {\n      if (example.description) {\n        if (!first) sections.push(\"\");\n        sections.push(`  ${colors.dim(`# ${example.description}`)}`);\n      } else if (previousHadDescription) {\n        sections.push(\"\");\n      }\n      sections.push(`  ${colors.cyan(example.command)}`);\n      first = false;\n      previousHadDescription = !!example.description;\n    }\n    sections.push(\"\");\n  }\n  // Remove trailing empty line if present\n  if (sections[sections.length - 1] === \"\") {\n    sections.pop();\n  }\n  return sections.join(\"\\n\");\n};\n//# sourceMappingURL=CliOutput.js.map","// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeForBash = s => s.replace(/'/g, \"'\\\\''\");\nconst sanitizeFunctionName = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\nconst flagNamesForWordlist = flag => {\n  const names = [`--${flag.name}`];\n  for (const alias of flag.aliases) {\n    names.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n  }\n  if (flag.type._tag === \"Boolean\") {\n    names.push(`--no-${flag.name}`);\n  }\n  return names;\n};\n/**\n * Build an associative array mapping each flag form to a group index.\n * At completion time, if any form in a group appears in COMP_WORDS,\n * all forms in that group are removed from the candidate list.\n */\nconst buildFlagGroupDeclarations = (flags, lines) => {\n  if (flags.length === 0) return;\n  lines.push(`  # Build used-flag filter`);\n  lines.push(`  local -A _flag_groups`);\n  let groupIdx = 0;\n  for (const flag of flags) {\n    const forms = flagNamesForWordlist(flag);\n    for (const form of forms) {\n      lines.push(`  _flag_groups[${form}]=${groupIdx}`);\n    }\n    groupIdx++;\n  }\n  lines.push(`  local -A _used_groups`);\n  lines.push(`  for ((i = 1; i < cword; i++)); do`);\n  lines.push(`    local _g=\"\\${_flag_groups[\\${words[i]}]:-}\"`);\n  lines.push(`    [[ -n \"$_g\" ]] && _used_groups[$_g]=1`);\n  lines.push(`  done`);\n  lines.push(`  local _filtered_flags=\"\"`);\n  lines.push(`  for _f in ${flags.flatMap(flagNamesForWordlist).join(\" \")}; do`);\n  lines.push(`    local _g=\"\\${_flag_groups[$_f]:-}\"`);\n  lines.push(`    [[ -z \"$_g\" || -z \"\\${_used_groups[$_g]:-}\" ]] && _filtered_flags+=\" $_f\"`);\n  lines.push(`  done`);\n  lines.push(``);\n};\nconst flagValueCompletion = type => {\n  switch (type._tag) {\n    case \"Boolean\":\n      return undefined;\n    case \"Choice\":\n      return `COMPREPLY=( $(compgen -W '${type.values.join(\" \")}' -- \"$cur\") )`;\n    case \"Path\":\n      if (type.pathType === \"directory\") return `COMPREPLY=( $(compgen -d -- \"$cur\") )`;\n      return `COMPREPLY=( $(compgen -f -- \"$cur\") )`;\n    default:\n      return undefined;\n  }\n};\nconst argCompletion = type => {\n  switch (type._tag) {\n    case \"Choice\":\n      return `COMPREPLY=( $(compgen -W '${type.values.join(\" \")}' -- \"$cur\") )`;\n    case \"Path\":\n      if (type.pathType === \"directory\") return `COMPREPLY=( $(compgen -d -- \"$cur\") )`;\n      return `COMPREPLY=( $(compgen -f -- \"$cur\") )`;\n    default:\n      return undefined;\n  }\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateFunction = (descriptor, parentPath, lines) => {\n  const currentPath = [...parentPath, descriptor.name];\n  const funcName = `_${currentPath.map(sanitizeFunctionName).join(\"_\")}`;\n  lines.push(`${funcName}()`);\n  lines.push(`{`);\n  lines.push(`  local cur prev words cword`);\n  lines.push(`  _init_completion || return`);\n  lines.push(``);\n  // Build flag-value dispatch\n  const flagsWithValues = descriptor.flags.filter(f => f.type._tag !== \"Boolean\");\n  if (flagsWithValues.length > 0) {\n    lines.push(`  # Flag value completions`);\n    lines.push(`  case \"$prev\" in`);\n    for (const flag of flagsWithValues) {\n      const longNames = [`--${flag.name}`];\n      for (const alias of flag.aliases) {\n        longNames.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n      }\n      const completion = flagValueCompletion(flag.type);\n      if (completion) {\n        lines.push(`    ${longNames.join(\"|\")})`);\n        lines.push(`      ${completion}`);\n        lines.push(`      return`);\n        lines.push(`      ;;`);\n      }\n    }\n    lines.push(`  esac`);\n    lines.push(``);\n  }\n  // Subcommand dispatch\n  if (descriptor.subcommands.length > 0) {\n    lines.push(`  # Subcommand dispatch`);\n    lines.push(`  local i cmd`);\n    lines.push(`  for ((i = 1; i < cword; i++)); do`);\n    lines.push(`    case \"\\${words[i]}\" in`);\n    for (const sub of descriptor.subcommands) {\n      const subFuncName = `_${[...currentPath, sub.name].map(sanitizeFunctionName).join(\"_\")}`;\n      lines.push(`      ${sub.name})`);\n      lines.push(`        ${subFuncName}`);\n      lines.push(`        return`);\n      lines.push(`        ;;`);\n    }\n    lines.push(`    esac`);\n    lines.push(`  done`);\n    lines.push(``);\n  }\n  // Filter already-used flags (entire alias group removed when any form is used)\n  buildFlagGroupDeclarations(descriptor.flags, lines);\n  if (descriptor.flags.length > 0 || descriptor.subcommands.length > 0) {\n    lines.push(`  # Complete flags (filtered) and subcommands`);\n    lines.push(`  if [[ \"$cur\" == -* ]]; then`);\n    if (descriptor.flags.length > 0) {\n      lines.push(`    COMPREPLY=( $(compgen -W \"$_filtered_flags\" -- \"$cur\") )`);\n    }\n    lines.push(`    return`);\n    lines.push(`  fi`);\n    lines.push(``);\n  }\n  // Positional argument completion\n  const argsWithCompletions = descriptor.arguments.filter(a => argCompletion(a.type) !== undefined);\n  if (argsWithCompletions.length > 0) {\n    lines.push(`  # Positional argument completions`);\n    for (const arg of argsWithCompletions) {\n      const comp = argCompletion(arg.type);\n      lines.push(`  ${comp}`);\n      lines.push(`  return`);\n    }\n  } else if (descriptor.subcommands.length > 0) {\n    const subNames = descriptor.subcommands.map(s => s.name);\n    lines.push(`  COMPREPLY=( $(compgen -W '${subNames.join(\" \")}' -- \"$cur\") )`);\n  }\n  lines.push(`}`);\n  lines.push(``);\n  // Recurse into subcommands\n  for (const sub of descriptor.subcommands) {\n    generateFunction(sub, currentPath, lines);\n  }\n};\n/** @internal */\nexport const generate = (executableName, descriptor) => {\n  const lines = [];\n  const safeName = sanitizeFunctionName(executableName);\n  lines.push(`###-begin-${escapeForBash(executableName)}-completions-###`);\n  lines.push(`#`);\n  lines.push(`# Static completion script for Bash`);\n  lines.push(`#`);\n  lines.push(`# Installation:`);\n  lines.push(`#   ${escapeForBash(executableName)} --completions bash >> ~/.bashrc`);\n  lines.push(`#`);\n  lines.push(``);\n  // Inline minimal _init_completion fallback for environments without\n  // bash-completion installed. The real _init_completion handles edge cases\n  // (= in options, redirections, etc.) but this covers the common path.\n  lines.push(`if ! type _init_completion &>/dev/null; then`);\n  lines.push(`  _init_completion()`);\n  lines.push(`  {`);\n  lines.push(`    COMPREPLY=()`);\n  lines.push(`    cur=\"\\${COMP_WORDS[COMP_CWORD]}\"`);\n  lines.push(`    prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"`);\n  lines.push(`    words=(\"\\${COMP_WORDS[@]}\")`);\n  lines.push(`    cword=$COMP_CWORD`);\n  lines.push(`  }`);\n  lines.push(`fi`);\n  lines.push(``);\n  generateFunction(descriptor, [], lines);\n  lines.push(`complete -F _${safeName} ${escapeForBash(executableName)}`);\n  lines.push(`###-end-${escapeForBash(executableName)}-completions-###`);\n  return lines.join(\"\\n\");\n};\n//# sourceMappingURL=bash.js.map","// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeFishString = s => s.replace(/'/g, \"\\\\'\");\n/**\n * Build a Fish condition that checks the current subcommand context.\n *\n * For root-level completions with subcommands: `__fish_use_subcommand`\n * For nested commands: verify the parent subcommand is active AND none of its\n * child subcommands have been entered yet.\n */\nconst subcommandCondition = (parentPath, childSubcommandNames) => {\n  if (parentPath.length === 0) {\n    if (childSubcommandNames.length > 0) {\n      return `__fish_use_subcommand`;\n    }\n    return ``;\n  }\n  const parent = parentPath[parentPath.length - 1];\n  if (childSubcommandNames.length > 0) {\n    // Show only when parent is active but no child subcommand has been entered\n    return `__fish_seen_subcommand_from ${parent}; and not __fish_seen_subcommand_from ${childSubcommandNames.join(\" \")}`;\n  }\n  return `__fish_seen_subcommand_from ${parent}`;\n};\n/**\n * Build a __fish_contains_opt condition that checks whether any form of this\n * flag has already been typed. Returns the condition string without wrapping\n * quotes (the caller adds those).\n */\nconst flagContainsOptCondition = flag => {\n  const optArgs = [];\n  for (const alias of flag.aliases) {\n    if (alias.length === 1) {\n      optArgs.push(`-s ${alias}`);\n    }\n  }\n  // Long names (fish __fish_contains_opt uses bare words for long opts)\n  optArgs.push(flag.name);\n  for (const alias of flag.aliases) {\n    if (alias.length > 1) {\n      optArgs.push(alias);\n    }\n  }\n  if (flag.type._tag === \"Boolean\") {\n    optArgs.push(`no-${flag.name}`);\n  }\n  return `not __fish_contains_opt ${optArgs.join(\" \")}`;\n};\nconst flagCompletionArgs = flag => {\n  const args = [`-l ${flag.name}`];\n  for (const alias of flag.aliases) {\n    if (alias.length === 1) {\n      args.push(`-s ${alias}`);\n    } else {\n      args.push(`-l ${alias}`);\n    }\n  }\n  if (flag.description) {\n    args.push(`-d '${escapeFishString(flag.description)}'`);\n  }\n  const valueArgs = flagValueArgs(flag.type);\n  if (valueArgs) {\n    args.push(valueArgs);\n  }\n  return args;\n};\nconst flagValueArgs = type => {\n  switch (type._tag) {\n    case \"Boolean\":\n      return undefined;\n    case \"Choice\":\n      return `-r -f -a '${type.values.join(\" \")}'`;\n    case \"Path\":\n      if (type.pathType === \"directory\") return `-r -F`;\n      return `-r -F`;\n    default:\n      // -r: requires a value, -f: don't fall back to file completion\n      return `-r -f`;\n  }\n};\nconst argValueArgs = type => {\n  switch (type._tag) {\n    case \"Choice\":\n      return `-r -f -a '${type.values.join(\" \")}'`;\n    case \"Path\":\n      return `-r -F`;\n    default:\n      return undefined;\n  }\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateCompletions = (executableName, descriptor, parentPath, lines) => {\n  const allSubNames = descriptor.subcommands.map(s => s.name);\n  const condition = subcommandCondition(parentPath, allSubNames);\n  const conditionArg = condition ? `-n '${condition}'` : ``;\n  // Suppress default file completion unless the command has path-type\n  // positional arguments. Without this, fish falls back to listing files\n  // even when only flags are valid.\n  const hasPathArgs = descriptor.arguments.some(a => a.type._tag === \"Path\");\n  if (!hasPathArgs) {\n    const parts = [`complete -c ${executableName}`];\n    if (conditionArg) parts.push(conditionArg);\n    parts.push(`-f`);\n    lines.push(parts.join(\" \"));\n  }\n  // Subcommand completions\n  for (const sub of descriptor.subcommands) {\n    const parts = [`complete -c ${executableName}`];\n    if (conditionArg) parts.push(conditionArg);\n    parts.push(`-f -a '${escapeFishString(sub.name)}'`);\n    if (sub.description) {\n      parts.push(`-d '${escapeFishString(sub.description)}'`);\n    }\n    lines.push(parts.join(\" \"));\n  }\n  // Flag completions\n  for (const flag of descriptor.flags) {\n    // Only apply __fish_contains_opt dedup for boolean flags. For value-taking\n    // flags, the dedup condition would suppress the entry while fish is waiting\n    // for a value (e.g. typing `--env <TAB>` wouldn't show choices).\n    const isBoolean = flag.type._tag === \"Boolean\";\n    const flagCondition = isBoolean ? condition ? `${condition}; and ${flagContainsOptCondition(flag)}` : flagContainsOptCondition(flag) : condition;\n    const flagCondArg = flagCondition ? `-n '${flagCondition}'` : ``;\n    const parts = [`complete -c ${executableName}`];\n    if (flagCondArg) parts.push(flagCondArg);\n    parts.push(...flagCompletionArgs(flag));\n    lines.push(parts.join(\" \"));\n    // Boolean negation\n    if (isBoolean) {\n      const negParts = [`complete -c ${executableName}`];\n      if (flagCondArg) negParts.push(flagCondArg);\n      negParts.push(`-l no-${flag.name}`);\n      if (flag.description) {\n        negParts.push(`-d '${escapeFishString(`Disable ${flag.name}`)}'`);\n      }\n      lines.push(negParts.join(\" \"));\n    }\n  }\n  // Flags as -a entries for bare <TAB> visibility.\n  // Fish only shows -l/-s entries when the current word starts with -, so\n  // without this, flags are invisible on bare <TAB>. Guarded to only show\n  // when NOT already typing an option (avoids duplication with -l/-s above)\n  // and hidden once a flag has been used (__fish_contains_opt).\n  if (descriptor.flags.length > 0) {\n    const notDash = `not string match -q -- \"-*\" (commandline -ct)`;\n    const bareBase = condition ? `${condition}; and ${notDash}` : notDash;\n    for (const flag of descriptor.flags) {\n      const bareCondition = `${bareBase}; and ${flagContainsOptCondition(flag)}`;\n      const isBoolean = flag.type._tag === \"Boolean\";\n      const parts = [`complete -c ${executableName}`];\n      parts.push(`-n '${bareCondition}'`);\n      parts.push(`-f -a '--${flag.name}'`);\n      if (flag.description) {\n        parts.push(`-d '${escapeFishString(flag.description)}'`);\n      }\n      lines.push(parts.join(\" \"));\n      if (isBoolean) {\n        const negParts = [`complete -c ${executableName}`];\n        negParts.push(`-n '${bareCondition}'`);\n        negParts.push(`-f -a '--no-${flag.name}'`);\n        if (flag.description) {\n          negParts.push(`-d '${escapeFishString(`Disable ${flag.name}`)}'`);\n        }\n        lines.push(negParts.join(\" \"));\n      }\n    }\n  }\n  // Argument completions (type hints only)\n  for (const arg of descriptor.arguments) {\n    const valueArg = argValueArgs(arg.type);\n    if (valueArg) {\n      const parts = [`complete -c ${executableName}`];\n      if (conditionArg) parts.push(conditionArg);\n      parts.push(valueArg);\n      if (arg.description) {\n        parts.push(`-d '${escapeFishString(arg.description)}'`);\n      }\n      lines.push(parts.join(\" \"));\n    }\n  }\n  // Recurse into subcommands\n  for (const sub of descriptor.subcommands) {\n    generateCompletions(executableName, sub, [...parentPath, sub.name], lines);\n  }\n};\n/** @internal */\nexport const generate = (executableName, descriptor) => {\n  const lines = [];\n  lines.push(`###-begin-${executableName}-completions-###`);\n  lines.push(`#`);\n  lines.push(`# Static completion script for Fish`);\n  lines.push(`#`);\n  lines.push(`# Installation:`);\n  lines.push(`#   ${executableName} --completions fish > ~/.config/fish/completions/${executableName}.fish`);\n  lines.push(`#`);\n  lines.push(``);\n  generateCompletions(executableName, descriptor, [], lines);\n  lines.push(``);\n  lines.push(`###-end-${executableName}-completions-###`);\n  return lines.join(\"\\n\");\n};\n//# sourceMappingURL=fish.js.map","// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst escapeZsh = s => s.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"'\\\\''\").replace(/:/g, \"\\\\:\");\nconst sanitize = s => s.replace(/[^a-zA-Z0-9_]/g, \"_\");\n/**\n * All forms of a flag (--name, -alias, --no-name) for the exclusion group.\n */\nconst allForms = flag => {\n  const forms = [`--${flag.name}`];\n  for (const alias of flag.aliases) {\n    forms.push(alias.length === 1 ? `-${alias}` : `--${alias}`);\n  }\n  if (flag.type._tag === \"Boolean\") {\n    forms.push(`--no-${flag.name}`);\n  }\n  return forms;\n};\nconst valueAction = type => {\n  switch (type._tag) {\n    case \"Boolean\":\n      return \"\";\n    case \"Choice\":\n      return `:value:(${type.values.join(\" \")})`;\n    case \"Path\":\n      return type.pathType === \"directory\" ? `:directory:_directories` : `:file:_files`;\n    case \"Integer\":\n      return `:integer:`;\n    case \"Float\":\n      return `:float:`;\n    case \"Date\":\n      return `:date:`;\n    default:\n      return `:value:`;\n  }\n};\nconst argAction = type => {\n  switch (type._tag) {\n    case \"Choice\":\n      return `(${type.values.join(\" \")})`;\n    case \"Path\":\n      return type.pathType === \"directory\" ? `_directories` : `_files`;\n    default:\n      return ``;\n  }\n};\n/**\n * Produce _arguments optspecs for a single flag. Each spec is a complete,\n * single-quoted string — no brace expansion, no line continuations.\n */\nconst flagSpecs = flag => {\n  const specs = [];\n  const desc = flag.description ? `[${escapeZsh(flag.description)}]` : \"\";\n  const action = valueAction(flag.type);\n  const excl = `(${allForms(flag).join(\" \")})`;\n  // Primary long name\n  specs.push(`'${excl}--${flag.name}${desc}${action}'`);\n  // Aliases\n  for (const alias of flag.aliases) {\n    const prefix = alias.length === 1 ? \"-\" : \"--\";\n    specs.push(`'${excl}${prefix}${alias}${desc}${action}'`);\n  }\n  // Boolean negation\n  if (flag.type._tag === \"Boolean\") {\n    const negDesc = flag.description ? `[${escapeZsh(`Disable ${flag.name}`)}]` : \"\";\n    specs.push(`'${excl}--no-${flag.name}${negDesc}'`);\n  }\n  return specs;\n};\nconst argSpec = arg => {\n  const desc = arg.description ? escapeZsh(arg.description) : arg.name;\n  const action = argAction(arg.type);\n  const prefix = arg.variadic ? \"*\" : \"\";\n  return `'${prefix}:${desc}:${action}'`;\n};\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\nconst generateFunction = (descriptor, parentPath, lines) => {\n  const currentPath = [...parentPath, descriptor.name];\n  const funcName = `_${currentPath.map(sanitize).join(\"_\")}`;\n  lines.push(`${funcName}() {`);\n  if (descriptor.subcommands.length > 0) {\n    // _arguments -C requires these locals for the state machine\n    lines.push(`  local context state state_descr line`);\n    lines.push(`  typeset -A opt_args`);\n    lines.push(``);\n    // Subcommand list\n    lines.push(`  local -a commands`);\n    lines.push(`  commands=(`);\n    for (const sub of descriptor.subcommands) {\n      const desc = sub.description ? escapeZsh(sub.description) : \"\";\n      lines.push(`    '${sub.name}:${desc}'`);\n    }\n    lines.push(`  )`);\n    lines.push(``);\n    // Build specs array to avoid brace expansion / line continuation issues\n    lines.push(`  local -a specs`);\n    lines.push(`  specs=(`);\n    for (const flag of descriptor.flags) {\n      for (const spec of flagSpecs(flag)) {\n        lines.push(`    ${spec}`);\n      }\n    }\n    for (const arg of descriptor.arguments) {\n      lines.push(`    ${argSpec(arg)}`);\n    }\n    lines.push(`    '1:command:->command'`);\n    lines.push(`    '*::arg:->args'`);\n    lines.push(`  )`);\n    lines.push(``);\n    lines.push(`  _arguments -C \"\\${specs[@]}\"`);\n    lines.push(``);\n    // State dispatch\n    lines.push(`  case \"$state\" in`);\n    lines.push(`    command)`);\n    lines.push(`      _describe -t commands 'commands' commands`);\n    lines.push(`      ;;`);\n    lines.push(`    args)`);\n    lines.push(`      case \"$words[1]\" in`);\n    for (const sub of descriptor.subcommands) {\n      const subFunc = `_${[...currentPath, sub.name].map(sanitize).join(\"_\")}`;\n      lines.push(`        ${sub.name})`);\n      lines.push(`          ${subFunc}`);\n      lines.push(`          ;;`);\n    }\n    lines.push(`      esac`);\n    lines.push(`      ;;`);\n    lines.push(`  esac`);\n  } else {\n    // Leaf command — no subcommands\n    const allSpecs = [];\n    for (const flag of descriptor.flags) {\n      allSpecs.push(...flagSpecs(flag));\n    }\n    for (const arg of descriptor.arguments) {\n      allSpecs.push(argSpec(arg));\n    }\n    if (allSpecs.length > 0) {\n      lines.push(`  local -a specs`);\n      lines.push(`  specs=(`);\n      for (const spec of allSpecs) {\n        lines.push(`    ${spec}`);\n      }\n      lines.push(`  )`);\n      lines.push(`  _arguments \"\\${specs[@]}\"`);\n    }\n  }\n  lines.push(`}`);\n  lines.push(``);\n  for (const sub of descriptor.subcommands) {\n    generateFunction(sub, currentPath, lines);\n  }\n};\n/** @internal */\nexport const generate = (executableName, descriptor) => {\n  const lines = [];\n  const safeName = sanitize(executableName);\n  lines.push(`#compdef ${executableName}`);\n  lines.push(`###-begin-${executableName}-completions-###`);\n  lines.push(`#`);\n  lines.push(`# Static completion script for Zsh`);\n  lines.push(`#`);\n  lines.push(`# Installation:`);\n  lines.push(`#   ${executableName} --completions zsh > ~/.zsh/completions/_${executableName}`);\n  lines.push(`#   then add ~/.zsh/completions to your fpath`);\n  lines.push(`#`);\n  lines.push(``);\n  generateFunction(descriptor, [], lines);\n  lines.push(`# Handle both direct invocation and autoload`);\n  lines.push(`if [[ \"\\${zsh_eval_context[-1]}\" == \"loadautofunc\" ]]; then`);\n  lines.push(`  _${safeName} \"$@\"`);\n  lines.push(`else`);\n  lines.push(`  compdef _${safeName} ${executableName}`);\n  lines.push(`fi`);\n  lines.push(`###-end-${executableName}-completions-###`);\n  return lines.join(\"\\n\");\n};\n//# sourceMappingURL=zsh.js.map","/**\n * The `Completions` module turns a plain description of an Effect CLI command\n * tree into shell completion scripts for Bash, Zsh, and Fish. It is the\n * low-level script generation surface used by the unstable CLI package and by\n * the built-in completions global flag.\n *\n * @since 4.0.0\n */\nimport * as Bash from \"./internal/completions/bash.js\";\nimport * as Fish from \"./internal/completions/fish.js\";\nimport * as Zsh from \"./internal/completions/zsh.js\";\n/**\n * Generates a shell completion script for a command descriptor.\n *\n * **When to use**\n *\n * Use when you need an installable completion script from an existing\n * `CommandDescriptor`.\n *\n * **Details**\n *\n * Dispatches by `shell` to Bash, Zsh, or Fish generation and returns a static\n * script string for `executableName`.\n *\n * @see {@link Shell} for supported shell names\n * @see {@link CommandDescriptor} for the command shape used by completion generation\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const generate = (executableName, shell, descriptor) => {\n  switch (shell) {\n    case \"bash\":\n      return Bash.generate(executableName, descriptor);\n    case \"zsh\":\n      return Zsh.generate(executableName, descriptor);\n    case \"fish\":\n      return Fish.generate(executableName, descriptor);\n  }\n};\n//# sourceMappingURL=Completions.js.map","import { dual } from \"../../Function.js\";\nimport * as Param from \"./Param.js\";\n// -------------------------------------------------------------------------------------\n// constructors\n// -------------------------------------------------------------------------------------\n/**\n * Creates a string flag that accepts text input.\n *\n * **Example** (Creating string flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const nameFlag = Flag.string(\"name\")\n * // Usage: --name \"John Doe\"\n * nameFlag.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const string = name => Param.string(Param.flagKind, name);\n/**\n * Creates a boolean flag that can be enabled or disabled.\n *\n * **Example** (Creating boolean flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const verboseFlag = Flag.boolean(\"verbose\")\n * // Usage: --verbose (true) or --no-verbose (false)\n * verboseFlag.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const boolean = name => Param.boolean(Param.flagKind, name);\n/**\n * Creates an integer flag that accepts whole number input.\n *\n * **Example** (Creating integer flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const portFlag = Flag.integer(\"port\")\n * // Usage: --port 8080\n * portFlag.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const integer = name => Param.integer(Param.flagKind, name);\n/**\n * Creates a float flag that accepts decimal number input.\n *\n * **Example** (Creating float flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const rateFlag = Flag.float(\"rate\")\n * // Usage: --rate 3.14\n * rateFlag.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const float = name => Param.float(Param.flagKind, name);\n/**\n * Creates a date flag that accepts date input in ISO format.\n *\n * **Example** (Creating date flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const startDateFlag = Flag.date(\"start-date\")\n * // Usage: --start-date 2023-12-25\n * startDateFlag.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const date = name => Param.date(Param.flagKind, name);\n/**\n * Constructs option parameters that represent a choice between several inputs.\n * Each tuple maps a string flag value to an associated typed value.\n *\n * **Example** (Creating flag choices with values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // simple enum like choice mapping directly to string union\n * const color = Flag.choice(\"color\", [\"red\", \"green\", \"blue\"])\n *\n * // choice with custom value mapping\n * const logLevel = Flag.choiceWithValue(\"log-level\", [\n *   [\"debug\", \"Debug\" as const],\n *   [\"info\", \"Info\" as const],\n *   [\"error\", \"Error\" as const]\n * ])\n * const kinds = [color.kind, logLevel.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choiceWithValue = (name, choices) => Param.choiceWithValue(Param.flagKind, name, choices);\n/**\n * Creates a flag that accepts one of the provided string choices and returns\n * the selected string.\n *\n * **When to use**\n *\n * Use when you need to define a named CLI flag with fixed string choices and no\n * custom value mapping.\n *\n * **Gotchas**\n *\n * An empty choices array compiles, but no input value can parse successfully.\n *\n * @see {@link choiceWithValue} for mapping accepted strings to different typed values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const choice = (name, choices) => Param.choice(Param.flagKind, name, choices);\n/**\n * Creates a path flag that accepts file system path input with validation options.\n *\n * **Example** (Creating path flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Basic path flag\n * const pathFlag = Flag.path(\"config-path\")\n *\n * // File-only path that must exist\n * const fileFlag = Flag.path(\"input-file\", {\n *   pathType: \"file\",\n *   mustExist: true\n * })\n *\n * // Directory path with custom type name\n * const dirFlag = Flag.path(\"output-dir\", {\n *   pathType: \"directory\",\n *   typeName: \"OUTPUT_DIRECTORY\"\n * })\n * const kinds = [pathFlag.kind, fileFlag.kind, dirFlag.kind] // => [\"flag\", \"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const path = (name, options) => Param.path(Param.flagKind, name, options);\n/**\n * Creates a file path flag that accepts file paths with optional existence validation.\n *\n * **Example** (Creating file flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Basic file flag\n * const inputFlag = Flag.file(\"input\")\n * // Usage: --input ./data.json\n *\n * // File that must exist\n * const configFlag = Flag.file(\"config\", { mustExist: true })\n * // Usage: --config ./config.yaml (file must exist)\n * const kinds = [inputFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (name, options) => Param.file(Param.flagKind, name, options);\n/**\n * Creates a directory path flag that accepts directory paths with optional existence validation.\n *\n * **Example** (Creating directory flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Basic directory flag\n * const outputFlag = Flag.directory(\"output\")\n * // Usage: --output ./build\n *\n * // Directory that must exist\n * const sourceFlag = Flag.directory(\"source\", { mustExist: true })\n * // Usage: --source ./src (directory must exist)\n * const kinds = [outputFlag.kind, sourceFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const directory = (name, options) => Param.directory(Param.flagKind, name, options);\n/**\n * Creates a string flag whose parsed value is wrapped in `Redacted.Redacted` so\n * stringification and logging redact the value.\n *\n * **Gotchas**\n *\n * Values supplied on the command line may still be visible to the operating\n * system or shell history.\n *\n * **Example** (Creating redacted flags)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Redacted, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const passwordFlag = Flag.redacted(\"password\")\n *\n * const program = Effect.gen(function*() {\n *   const [, password] = yield* passwordFlag.parse({\n *     arguments: [],\n *     flags: { \"password\": [\"abc123\"] }\n *   })\n *   return Redacted.value(password).length\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => 6\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const redacted = name => Param.redacted(Param.flagKind, name);\n/**\n * Creates a flag that reads and returns file content as a string.\n *\n * **Example** (Reading file text)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const config = Flag.fileText(\"config-file\")\n * // --config-file ./app.json will read the file content\n * config.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileText = name => Param.fileText(Param.flagKind, name);\n/**\n * Creates a flag that reads and parses the content of the specified file.\n *\n * **Details**\n *\n * The parser that is utilized will depend on the specified `format`, or the\n * extension of the file passed on the command-line if no `format` is specified.\n *\n * **Example** (Parsing file contents)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Will use the extension of the file passed on the command line to determine\n * // the parser to use\n * const config = Flag.fileParse(\"config\")\n *\n * // Will use the JSON parser\n * const jsonConfig = Flag.fileParse(\"json-config\", { format: \"json\" })\n * const kinds = [config.kind, jsonConfig.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileParse = (name, options) => Param.fileParse(Param.flagKind, name, options);\n/**\n * Creates a flag that reads and validates file content using the specified\n * schema.\n *\n * **Example** (Validating file contents)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const ConfigSchema = Schema.Struct({\n *   port: Schema.Number,\n *   host: Schema.String\n * })\n *\n * const config = Flag.fileSchema(\"config\", ConfigSchema, { format: \"json\" })\n * config.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fileSchema = (name, schema, options) => Param.fileSchema(Param.flagKind, name, schema, options);\n/**\n * Creates a flag that parses key=value pairs.\n *\n * **When to use**\n *\n * Use when you need a CLI flag that accepts one or more `key=value`\n * configuration entries.\n *\n * **Details**\n *\n * Requires at least one key=value pair. Multiple pairs are merged into a single\n * record.\n *\n * **Example** (Parsing key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const env = Flag.keyValuePair(\"env\")\n * // --env FOO=bar --env BAZ=qux will parse to { FOO: \"bar\", BAZ: \"qux\" }\n * env.kind // => \"flag\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const keyValuePair = name => Param.keyValuePair(Param.flagKind, name);\n/**\n * Creates an empty sentinel flag that always fails to parse.\n * This is useful for creating placeholder flags or for combinators.\n *\n * **Example** (Creating sentinel flags)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const makeValueFlag = (includeValue: boolean) =>\n *   includeValue ? Flag.string(\"value\") : Flag.none\n *\n * makeValueFlag(true) === Flag.none // => false\n * makeValueFlag(false) === Flag.none // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const none = /*#__PURE__*/Param.none(Param.flagKind);\n// -------------------------------------------------------------------------------------\n// combinators\n// -------------------------------------------------------------------------------------\n/**\n * Adds an alias to a flag, allowing it to be referenced by multiple names.\n *\n * **Example** (Adding flag aliases)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Flag can be used as both --verbose and -v\n * const verboseFlag = Flag.boolean(\"verbose\").pipe(\n *   Flag.withAlias(\"v\")\n * )\n *\n * // Multiple aliases can be chained\n * const helpFlag = Flag.boolean(\"help\").pipe(\n *   Flag.withAlias(\"h\"),\n *   Flag.withAlias(\"?\")\n * )\n * const kinds = [verboseFlag.kind, helpFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category aliasing\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => Param.withAlias(self, alias));\n/**\n * Adds a description to a flag for help documentation.\n *\n * **Example** (Adding help descriptions)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const portFlag = Flag.integer(\"port\").pipe(\n *   Flag.withDescription(\"The port number to listen on\")\n * )\n *\n * const configFlag = Flag.file(\"config\").pipe(\n *   Flag.withDescription(\"Path to the configuration file\")\n * )\n * const kinds = [portFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category metadata\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => Param.withDescription(self, description));\n// -------------------------------------------------------------------------------------\n// metadata\n// -------------------------------------------------------------------------------------\n/**\n * Sets a custom metavar (placeholder name) for the flag in help documentation.\n *\n * **Details**\n *\n * The metavar is displayed in usage text to indicate what value the user should\n * provide. For example, `--output FILE` shows `FILE` as the metavar.\n *\n * **Example** (Setting metavars)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const databaseFlag = Flag.string(\"database-url\").pipe(\n *   Flag.withMetavar(\"URL\"),\n *   Flag.withDescription(\"Database connection URL\")\n * )\n * // In help: --database-url URL\n *\n * const timeoutFlag = Flag.integer(\"timeout\").pipe(\n *   Flag.withMetavar(\"SECONDS\")\n * )\n * // In help: --timeout SECONDS\n * const kinds = [databaseFlag.kind, timeoutFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category metadata\n * @since 4.0.0\n */\nexport const withMetavar = /*#__PURE__*/dual(2, (self, metavar) => Param.withMetavar(self, metavar));\n/**\n * Hides a flag from generated help output and shell completions while keeping\n * it fully parseable on the command line.\n *\n * **When to use**\n *\n * Use when experimental or internal flags should be accepted but not advertised, such as\n * `--experimental-foo`, debug toggles, or escape hatches that are not yet committed to the\n * public CLI surface.\n *\n * **Example** (Hiding a flag from help)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Flag still parses --experimental-foo, but it does not appear in --help.\n * const experimental = Flag.boolean(\"experimental-foo\").pipe(\n *   Flag.withHidden\n * )\n * experimental.kind // => \"flag\"\n * ```\n *\n * @category metadata\n * @since 4.0.0\n */\nexport const withHidden = self => Param.withHidden(self);\n/**\n * Makes a flag optional, returning an Option type that can be None if not provided.\n *\n * **Example** (Making flags optional)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Option, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const optionalPort = Flag.optional(Flag.integer(\"port\"))\n *\n * const program = Effect.gen(function*() {\n *   const [, port] = yield* optionalPort.parse({\n *     arguments: [],\n *     flags: { \"port\": [\"4000\"] }\n *   })\n *   return port\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => Option.some(4000)\n * ```\n *\n * @category optionality\n * @since 4.0.0\n */\nexport const optional = param => Param.optional(param);\n/**\n * Provides a default value for a flag when it's not specified.\n *\n * **Example** (Providing default values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const portFlag = Flag.integer(\"port\").pipe(\n *   Flag.withDefault(8080)\n * )\n * // If --port is not provided, defaults to 8080\n *\n * const hostFlag = Flag.string(\"host\").pipe(\n *   Flag.withDefault(\"localhost\")\n * )\n * // If --host is not provided, defaults to \"localhost\"\n * const kinds = [portFlag.kind, hostFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category optionality\n * @since 4.0.0\n */\nexport const withDefault = Param.withDefault;\n/**\n * Adds a fallback config that is loaded when a required flag is missing.\n *\n * **Example** (Falling back to config)\n *\n * ```ts import.meta.vitest\n * import { Config } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const verbose = Flag.boolean(\"verbose\").pipe(\n *   Flag.withFallbackConfig(Config.boolean(\"VERBOSE\"))\n * )\n * verbose.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackConfig = /*#__PURE__*/dual(2, (self, config) => Param.withFallbackConfig(self, config));\n/**\n * Adds a fallback prompt that is shown when a required flag is missing.\n *\n * **Example** (Falling back to prompts)\n *\n * ```ts import.meta.vitest\n * import { Flag, Prompt } from \"effect/unstable/cli\"\n *\n * const name = Flag.string(\"name\").pipe(\n *   Flag.withFallbackPrompt(Prompt.text({ message: \"Name\" }))\n * )\n * name.kind // => \"flag\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withFallbackPrompt = /*#__PURE__*/dual(2, (self, prompt) => Param.withFallbackPrompt(self, prompt));\n/**\n * Transforms the parsed value of a flag using a mapping function.\n *\n * **Example** (Mapping parsed values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Convert string to uppercase\n * const nameFlag = Flag.string(\"name\").pipe(\n *   Flag.map((name) => name.toUpperCase())\n * )\n *\n * // Convert port to URL\n * const urlFlag = Flag.integer(\"port\").pipe(\n *   Flag.map((port) => `http://localhost:${port}`)\n * )\n * const kinds = [nameFlag.kind, urlFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => Param.map(self, f));\n/**\n * Transforms the parsed value using an Effect that can perform IO operations.\n *\n * **Example** (Mapping parsed values effectfully)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const upperName = Flag.string(\"name\").pipe(\n *   Flag.mapEffect((name) => Effect.succeed(name.toUpperCase()))\n * )\n *\n * const [, value] = await Effect.runPromise(\n *   upperName.parse({\n *     arguments: [],\n *     flags: { name: [\"alice\"] }\n *   }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => \"ALICE\"\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapEffect = /*#__PURE__*/dual(2, (self, f) => Param.mapEffect(self, f));\n/**\n * Transforms the parsed value using a function that might throw, with error handling.\n *\n * **Example** (Mapping thrown errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * // Parse JSON string with error handling\n * const jsonFlag = Flag.string(\"config\").pipe(\n *   Flag.mapTryCatch(\n *     (json) => JSON.parse(json),\n *     (error) => `Invalid JSON: ${error}`\n *   )\n * )\n *\n * // Parse URL with error handling\n * const urlFlag = Flag.string(\"url\").pipe(\n *   Flag.mapTryCatch(\n *     (url) => new URL(url),\n *     (error) => `Invalid URL: ${error}`\n *   )\n * )\n *\n * const [, value] = await Effect.runPromise(\n *   jsonFlag.parse({\n *     arguments: [],\n *     flags: { config: ['{\"enabled\":true}'] }\n *   }).pipe(Effect.provide(CliTestLayer))\n * )\n * value // => { enabled: true }\n * ```\n *\n * @category mapping\n * @since 4.0.0\n */\nexport const mapTryCatch = /*#__PURE__*/dual(3, (self, f, onError) => Param.mapTryCatch(self, f, onError));\n/**\n * Ensures a flag is specified at least a minimum number of times.\n *\n * **Example** (Requiring repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const sourceFlag = Flag.atLeast(Flag.file(\"source\"), 2)\n * // Requires at least 2 source files\n * // Usage: --source file1.ts --source file2.ts\n *\n * const tagFlag = Flag.string(\"tag\").pipe(\n *   Flag.atLeast(1)\n * )\n * // Requires at least 1 tag\n * const kinds = [sourceFlag.kind, tagFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const atLeast = /*#__PURE__*/dual(2, (self, min) => Param.atLeast(self, min));\n/**\n * Ensures a flag is specified at most a maximum number of times.\n *\n * **Example** (Limiting repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const warningFlag = Flag.atMost(Flag.string(\"warning\"), 3)\n * // Allows up to 3 warning flags\n * // Usage: --warning w1 --warning w2 --warning w3\n *\n * const debugFlag = Flag.string(\"debug\").pipe(\n *   Flag.atMost(1)\n * )\n * // Allows at most 1 debug flag\n * const kinds = [warningFlag.kind, debugFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const atMost = /*#__PURE__*/dual(2, (self, max) => Param.atMost(self, max));\n/**\n * Ensures a flag is specified between a minimum and maximum number of times.\n *\n * **Example** (Bounding repeated values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const hostFlag = Flag.between(Flag.string(\"host\"), 1, 3)\n * // Requires 1-3 host flags\n * // Usage: --host host1 --host host2\n *\n * const excludeFlag = Flag.string(\"exclude\").pipe(\n *   Flag.between(0, 5)\n * )\n * // Allows 0-5 exclude patterns\n * const kinds = [hostFlag.kind, excludeFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category repetition\n * @since 4.0.0\n */\nexport const between = /*#__PURE__*/dual(3, (self, min, max) => Param.between(self, min, max));\n/**\n * Transforms and filters a flag value, failing with a custom error if the transformation returns None.\n *\n * **Example** (Filtering and transforming values)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Parse positive integers only\n * const positiveInt = Flag.integer(\"count\").pipe(\n *   Flag.filterMap(\n *     (n) => n > 0 ? Option.some(n) : Option.none(),\n *     (n) => `Expected positive integer, got ${n}`\n *   )\n * )\n *\n * // Parse valid email addresses\n * const emailFlag = Flag.string(\"email\").pipe(\n *   Flag.filterMap(\n *     (email) => email.includes(\"@\") ? Option.some(email) : Option.none(),\n *     (email) => `Invalid email address: ${email}`\n *   )\n * )\n * const kinds = [positiveInt.kind, emailFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(3, (self, f, onNone) => Param.filterMap(self, f, onNone));\n/**\n * Filters a flag value based on a predicate, failing with a custom error if the predicate returns false.\n *\n * **Example** (Filtering parsed values)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Ensure port is in valid range\n * const portFlag = Flag.integer(\"port\").pipe(\n *   Flag.filter(\n *     (port) => port >= 1 && port <= 65535,\n *     (port) => `Port ${port} is out of range (1-65535)`\n *   )\n * )\n *\n * // Ensure non-empty string\n * const nameFlag = Flag.string(\"name\").pipe(\n *   Flag.filter(\n *     (name) => name.trim().length > 0,\n *     () => \"Name cannot be empty\"\n *   )\n * )\n * const kinds = [portFlag.kind, nameFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category filtering\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(3, (self, predicate, onFalse) => Param.filter(self, predicate, onFalse));\n/**\n * Provides an alternative flag if the first one fails to parse.\n *\n * **Example** (Falling back to another flag)\n *\n * ```ts import.meta.vitest\n * import { Flag } from \"effect/unstable/cli\"\n *\n * // Try parsing as integer, fallback to string\n * const valueFlag = Flag.orElse(\n *   Flag.integer(\"value\"),\n *   () => Flag.string(\"value\")\n * )\n *\n * // Multiple input sources with fallback\n * const configFlag = Flag.orElse(\n *   Flag.file(\"config\"),\n *   () => Flag.string(\"config-url\")\n * )\n * const kinds = [valueFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category alternatives\n * @since 4.0.0\n */\nexport const orElse = /*#__PURE__*/dual(2, (self, that) => Param.orElse(self, that));\n/**\n * Tries to parse with the first flag, then the second, returning a Result that indicates which succeeded.\n *\n * **Example** (Returning fallback results)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Result, Stdio, Terminal } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const sourceFlag = Flag.orElseResult(\n *   Flag.string(\"source\"),\n *   () => Flag.string(\"source-url\")\n * )\n *\n * const program = Effect.gen(function*() {\n *   const [, source] = yield* sourceFlag.parse({\n *     arguments: [],\n *     flags: { \"source-url\": [\"https://example.com\"] }\n *   })\n *   return source\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer))) // => Result.fail(\"https://example.com\")\n * ```\n *\n * @category alternatives\n * @since 4.0.0\n */\nexport const orElseResult = /*#__PURE__*/dual(2, (self, that) => Param.orElseResult(self, that));\n/**\n * Validates and transforms a flag value using a Schema codec.\n *\n * **Example** (Validating with schemas)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Flag } from \"effect/unstable/cli\"\n *\n * const isEmail = Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/, {\n *   message: \"Must be a valid email address\"\n * })\n *\n * // Parse and validate email with custom schema\n * const EmailSchema = Schema.String.pipe(\n *   Schema.check(isEmail)\n * )\n *\n * const emailFlag = Flag.string(\"email\").pipe(\n *   Flag.withSchema(EmailSchema)\n * )\n *\n * // Parse JSON configuration with schema validation\n * const ConfigSchema = Schema.Struct({\n *   port: Schema.Number,\n *   host: Schema.String,\n *   ssl: Schema.optional(Schema.Boolean)\n * }).pipe(Schema.fromJsonString)\n *\n * const configFlag = Flag.string(\"config\").pipe(\n *   Flag.withSchema(ConfigSchema)\n * )\n * const kinds = [emailFlag.kind, configFlag.kind] // => [\"flag\", \"flag\"]\n * ```\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const withSchema = /*#__PURE__*/dual(2, (self, schema) => Param.withSchema(self, schema));\n//# sourceMappingURL=Flag.js.map","/**\n * Config Internal\n * ================\n *\n * The processed internal representation of a Command.Config declaration.\n * Separates the user's declared config shape from the flat parsing representation.\n *\n * Key concepts:\n * - ConfigInternal: The full processed form (flags, arguments, tree)\n * - ConfigInternal.Tree: Maps declaration keys to nodes\n * - ConfigInternal.Node: Param reference, Array, or Nested subtree\n *\n * Example transformation from Command.Config to Command.Config.Internal:\n *\n * ```ts\n * // User declares:\n * const config = {\n *   verbose: Flag.boolean(\"verbose\"),\n *   server: {\n *     host: Flag.string(\"host\"),\n *     port: Flag.integer(\"port\")\n *   },\n *   files: Argument.string(\"files\").pipe(Argument.variadic)\n * }\n *\n * // Becomes Config.Internal:\n * {\n *   arguments: [filesParam],           // Flat array of arguments\n *   flags: [verboseParam, hostParam, portParam],  // Flat array of flags\n *   orderedParams: [verboseParam, hostParam, portParam, filesParam],\n *   tree: {                            // Preserves nested structure\n *     verbose: { _tag: \"Param\", index: 0 },\n *     server: {\n *       _tag: \"Nested\",\n *       tree: {\n *         host: { _tag: \"Param\", index: 1 },\n *         port: { _tag: \"Param\", index: 2 }\n *       }\n *     },\n *     files: { _tag: \"Param\", index: 3 }\n *   }\n * }\n * ```\n *\n * This separation allows:\n * 1. Flat iteration over all params for parsing/validation\n * 2. Reconstruction of original nested shape for handler input\n */\nimport * as InternalRecord from \"../../../internal/record.js\";\nimport * as Param from \"../Param.js\";\n/* ========================================================================== */\n/* Type ID                                                                    */\n/* ========================================================================== */\nconst ConfigInternalTypeId = \"~effect/cli/Command/Config/Internal\";\n/**\n * Parses a Command.Config into a ConfigInternal.\n *\n * Walks the config structure and:\n * 1. Extracts all Params into flat arrays (flags, arguments, orderedParams)\n * 2. Builds a tree that remembers the original nested structure\n * 3. Assigns each Param an index to link parsed values back\n *\n * @internal\n */\nexport const parseConfig = config => {\n  const orderedParams = [];\n  const flags = [];\n  const args = [];\n  function parse(config) {\n    const tree = Object.create(null);\n    for (const key of Object.keys(config)) {\n      tree[key] = parseValue(config[key]);\n    }\n    return tree;\n  }\n  function parseValue(value) {\n    if (Array.isArray(value)) {\n      return {\n        _tag: \"Array\",\n        children: value.map(v => parseValue(v))\n      };\n    } else if (Param.isParam(value)) {\n      const index = orderedParams.length;\n      orderedParams.push(value);\n      if (value.kind === \"argument\") {\n        args.push(value);\n      } else {\n        flags.push(value);\n      }\n      return {\n        _tag: \"Param\",\n        index\n      };\n    } else {\n      return {\n        _tag: \"Nested\",\n        tree: parse(value)\n      };\n    }\n  }\n  return {\n    [ConfigInternalTypeId]: ConfigInternalTypeId,\n    flags,\n    arguments: args,\n    orderedParams,\n    tree: parse(config)\n  };\n};\n/** @internal */\nexport const emptyConfig = /*#__PURE__*/parseConfig({});\nconst shiftNodeIndexes = (node, offset) => {\n  switch (node._tag) {\n    case \"Param\":\n      return {\n        _tag: \"Param\",\n        index: node.index + offset\n      };\n    case \"Array\":\n      return {\n        _tag: \"Array\",\n        children: node.children.map(child => shiftNodeIndexes(child, offset))\n      };\n    case \"Nested\":\n      return {\n        _tag: \"Nested\",\n        tree: shiftTreeIndexes(node.tree, offset)\n      };\n  }\n};\nconst shiftTreeIndexes = (tree, offset) => {\n  const output = Object.create(null);\n  for (const key of Object.keys(tree)) {\n    output[key] = shiftNodeIndexes(tree[key], offset);\n  }\n  return output;\n};\n/** @internal */\nexport const mergeConfig = (left, right) => {\n  const offset = left.orderedParams.length;\n  return {\n    [ConfigInternalTypeId]: ConfigInternalTypeId,\n    flags: [...left.flags, ...right.flags],\n    arguments: [...left.arguments, ...right.arguments],\n    orderedParams: [...left.orderedParams, ...right.orderedParams],\n    tree: Object.assign(Object.create(null), left.tree, shiftTreeIndexes(right.tree, offset))\n  };\n};\n/* ========================================================================== */\n/* Reconstruction                                                             */\n/* ========================================================================== */\n/**\n * Reconstructs the original nested config shape from parsed values.\n *\n * Uses the tree as a blueprint to place each parsed value back into\n * its original position in the nested structure.\n *\n * @internal\n */\nexport const reconstructTree = (tree, results) => {\n  const output = {};\n  for (const key of Object.keys(tree)) {\n    InternalRecord.assignProperty(output, key, nodeValue(tree[key]));\n  }\n  return output;\n  function nodeValue(node) {\n    switch (node._tag) {\n      case \"Param\":\n        return results[node.index];\n      case \"Array\":\n        return node.children.map(child => nodeValue(child));\n      case \"Nested\":\n        return reconstructTree(node.tree, results);\n    }\n  }\n};\n//# sourceMappingURL=config.js.map","/**\n * Command Implementation\n * ======================\n *\n * Internal implementation details for CLI commands.\n * Public API is in ../Command.ts\n */\nimport * as Arr from \"../../../Array.js\";\nimport * as Context from \"../../../Context.js\";\nimport * as Effect from \"../../../Effect.js\";\nimport * as Effectable from \"../../../Effectable.js\";\nimport * as Option from \"../../../Option.js\";\nimport * as Predicate from \"../../../Predicate.js\";\nimport * as CliError from \"../CliError.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport { emptyConfig, reconstructTree } from \"./config.js\";\n/* ========================================================================== */\n/* Type ID                                                                    */\n/* ========================================================================== */\nexport const TypeId = \"~effect/cli/Command\";\n/* ========================================================================== */\n/* Casting                                                                    */\n/* ========================================================================== */\n/**\n * Casts a Command to its internal implementation.\n * For use by internal modules that need access to config, parse, handle, etc.\n */\nexport const toImpl = self => self;\n/* ========================================================================== */\n/* Proto                                                                      */\n/* ========================================================================== */\nexport const Proto = {\n  ... /*#__PURE__*/Effectable.Prototype({\n    label: \"Command\",\n    evaluate() {\n      return toImpl(this).service;\n    }\n  })\n};\n/* ========================================================================== */\n/* Constructor                                                                */\n/* ========================================================================== */\n/**\n * Internal command constructor. Only accepts already-parsed ConfigInternal.\n */\nexport const makeCommand = options => {\n  const config = options.config;\n  const contextConfig = options.contextConfig ?? emptyConfig;\n  const service = options.service ?? Context.Service(`${TypeId}/${options.name}`);\n  const annotations = options.annotations ?? Context.empty();\n  const globalFlags = options.globalFlags ?? [];\n  const subcommands = options.subcommands ?? [];\n  const handle = (input, commandPath) => Predicate.isNotUndefined(options.handle) ? options.handle(input, commandPath) : Effect.fail(new CliError.ShowHelp({\n    commandPath,\n    errors: []\n  }));\n  const parse = options.parse ?? makeParser(config);\n  const parseContext = options.parseContext ?? makeParser(contextConfig, {\n    allowLeftovers: true\n  });\n  const buildHelpDoc = commandPath => {\n    const args = [];\n    const flags = [];\n    for (const arg of config.arguments) {\n      const singles = Param.extractSingleParams(arg);\n      const metadata = Param.getParamMetadata(arg);\n      for (const single of singles) {\n        args.push({\n          name: single.name,\n          type: single.typeName ?? Primitive.getTypeName(single.primitiveType),\n          description: single.description,\n          required: !metadata.isOptional,\n          variadic: metadata.isVariadic\n        });\n      }\n    }\n    let usage = commandPath.length > 0 ? commandPath.join(\" \") : options.name;\n    // Only render `<subcommand>` in usage when at least one visible subcommand\n    // exists; an all-hidden subcommand tree should look like a leaf command.\n    if (subcommands.some(group => group.commands.some(c => !c.hidden))) {\n      usage += \" <subcommand>\";\n    }\n    usage += \" [flags]\";\n    for (const arg of args) {\n      const argName = arg.variadic ? `<${arg.name}...>` : `<${arg.name}>`;\n      usage += ` ${arg.required ? argName : `[${argName}]`}`;\n    }\n    for (const option of config.flags) {\n      const singles = Param.extractSingleParams(option);\n      for (const single of singles) {\n        // Hidden flags still parse on the command line but are omitted from\n        // generated --help output.\n        if (single.hidden) continue;\n        flags.push(toFlagDoc(single));\n      }\n    }\n    const subcommandDocs = [];\n    for (const group of subcommands) {\n      // Hidden subcommands still parse on the command line but are omitted\n      // from --help. Drop the whole group when nothing visible remains so we\n      // don't render an empty heading.\n      const visible = group.commands.filter(c => !c.hidden);\n      if (visible.length === 0) continue;\n      subcommandDocs.push({\n        group: group.group,\n        commands: Arr.map(visible, subcommand => ({\n          name: subcommand.name,\n          alias: subcommand.alias,\n          shortDescription: subcommand.shortDescription,\n          description: subcommand.description ?? \"\"\n        }))\n      });\n    }\n    const examples = options.examples ?? [];\n    return {\n      description: options.description ?? \"\",\n      usage,\n      flags,\n      annotations,\n      ...(args.length > 0 && {\n        args\n      }),\n      ...(subcommandDocs.length > 0 && {\n        subcommands: subcommandDocs\n      }),\n      ...(examples.length > 0 && {\n        examples\n      })\n    };\n  };\n  return Object.assign(Object.create(Proto), {\n    [TypeId]: TypeId,\n    name: options.name,\n    examples: options.examples ?? [],\n    annotations,\n    globalFlags,\n    subcommands,\n    hidden: options.hidden ?? false,\n    config,\n    contextConfig,\n    service,\n    parse,\n    parseContext,\n    handle,\n    buildHelpDoc,\n    ...(Predicate.isNotUndefined(options.description) ? {\n      description: options.description\n    } : {}),\n    ...(Predicate.isNotUndefined(options.shortDescription) ? {\n      shortDescription: options.shortDescription\n    } : {}),\n    ...(Predicate.isNotUndefined(options.alias) ? {\n      alias: options.alias\n    } : {})\n  });\n};\n/* ========================================================================== */\n/* Helpers                                                                    */\n/* ========================================================================== */\n/**\n * Converts a single flag param into a FlagDoc for help display.\n */\nexport const toFlagDoc = single => {\n  const formattedAliases = single.aliases.map(alias => alias.length === 1 ? `-${alias}` : `--${alias}`);\n  return {\n    name: single.name,\n    aliases: formattedAliases,\n    type: single.typeName ?? Primitive.getTypeName(single.primitiveType),\n    description: appendChoiceKeys(single.description, Primitive.getChoiceKeys(single.primitiveType)),\n    required: single.primitiveType._tag !== \"Boolean\"\n  };\n};\nconst appendChoiceKeys = (description, choiceKeys) => {\n  if (choiceKeys === undefined || choiceKeys.length === 0) {\n    return description;\n  }\n  const choiceSuffix = `(choices: ${choiceKeys.join(\", \")})`;\n  return Option.match(description, {\n    onNone: () => Option.some(choiceSuffix),\n    onSome: value => Option.some(`${value} ${choiceSuffix}`)\n  });\n};\n/**\n * Creates a parser for a given config. Used as the default for both `parse`\n * and `parseContext`, and also by `withSharedFlags` to avoid constructing a\n * full throwaway command.\n */\nexport const makeParser = (cfg, options) => Effect.fnUntraced(function* (input) {\n  const parsedArgs = {\n    flags: input.flags,\n    arguments: input.arguments\n  };\n  const [remainingArguments, values] = yield* parseParams(parsedArgs, cfg.orderedParams);\n  if (options?.allowLeftovers !== true && remainingArguments.length > 0) {\n    return yield* new CliError.UnexpectedArgument({\n      arguments: remainingArguments\n    });\n  }\n  return reconstructTree(cfg.tree, values);\n});\n/**\n * Parses param values from parsed command arguments into their typed\n * representations.\n */\nconst parseParams = /*#__PURE__*/Effect.fnUntraced(function* (parsedArgs, params) {\n  const results = [];\n  let currentArguments = parsedArgs.arguments;\n  for (const option of params) {\n    const [remainingArguments, parsed] = yield* option.parse({\n      flags: parsedArgs.flags,\n      arguments: currentArguments\n    });\n    results.push(parsed);\n    currentArguments = remainingArguments;\n  }\n  return [currentArguments, results];\n});\n/**\n * Checks that inherited parent context flags do not reuse names declared by\n * child command flags.\n *\n * When `contextConfig` is supplied, it is used as the inherited flag set;\n * otherwise the parent's current context config is checked.\n */\nexport const checkForDuplicateFlags = (parent, subcommands, options) => {\n  const parentImpl = toImpl(parent);\n  const parentOptionNames = new Set();\n  const extractNames = flags => {\n    for (const option of flags) {\n      const singles = Param.extractSingleParams(option);\n      for (const single of singles) {\n        parentOptionNames.add(single.name);\n      }\n    }\n  };\n  extractNames((options?.contextConfig ?? parentImpl.contextConfig).flags);\n  for (const subcommand of subcommands) {\n    const subImpl = toImpl(subcommand);\n    for (const option of subImpl.config.flags) {\n      const singles = Param.extractSingleParams(option);\n      for (const single of singles) {\n        if (parentOptionNames.has(single.name)) {\n          throw new CliError.DuplicateOption({\n            option: single.name,\n            parentCommand: parent.name,\n            childCommand: subcommand.name\n          });\n        }\n      }\n    }\n  }\n};\n//# sourceMappingURL=command.js.map","/**\n * CommandDescriptor — pure-data representation of a command tree for\n * shell completion generation.\n *\n * @internal\n */\nimport * as Option from \"../../../../Option.js\";\nimport * as Param from \"../../Param.js\";\nimport * as Primitive from \"../../Primitive.js\";\nimport { toImpl } from \"../command.js\";\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\nconst toFlagType = single => {\n  const tag = single.primitiveType._tag;\n  switch (tag) {\n    case \"Boolean\":\n      return {\n        _tag: \"Boolean\"\n      };\n    case \"Integer\":\n      return {\n        _tag: \"Integer\"\n      };\n    case \"Float\":\n      return {\n        _tag: \"Float\"\n      };\n    case \"Date\":\n      return {\n        _tag: \"Date\"\n      };\n    case \"Choice\":\n      {\n        const keys = Primitive.getChoiceKeys(single.primitiveType);\n        return {\n          _tag: \"Choice\",\n          values: keys ?? []\n        };\n      }\n    case \"Path\":\n      {\n        const typeName = single.typeName;\n        const pathType = typeName === \"file\" ? \"file\" : typeName === \"directory\" ? \"directory\" : \"either\";\n        return {\n          _tag: \"Path\",\n          pathType\n        };\n      }\n    default:\n      return {\n        _tag: \"String\"\n      };\n  }\n};\nconst toArgumentType = single => {\n  const tag = single.primitiveType._tag;\n  switch (tag) {\n    case \"Integer\":\n      return {\n        _tag: \"Integer\"\n      };\n    case \"Float\":\n      return {\n        _tag: \"Float\"\n      };\n    case \"Date\":\n      return {\n        _tag: \"Date\"\n      };\n    case \"Choice\":\n      {\n        const keys = Primitive.getChoiceKeys(single.primitiveType);\n        return {\n          _tag: \"Choice\",\n          values: keys ?? []\n        };\n      }\n    case \"Path\":\n      {\n        const typeName = single.typeName;\n        const pathType = typeName === \"file\" ? \"file\" : typeName === \"directory\" ? \"directory\" : \"either\";\n        return {\n          _tag: \"Path\",\n          pathType\n        };\n      }\n    default:\n      return {\n        _tag: \"String\"\n      };\n  }\n};\n// ---------------------------------------------------------------------------\n// Extraction\n// ---------------------------------------------------------------------------\n/** @internal */\nexport const fromCommand = cmd => {\n  const impl = toImpl(cmd);\n  const config = impl.config;\n  const flags = [];\n  for (const flag of config.flags) {\n    const singles = Param.extractSingleParams(flag);\n    for (const single of singles) {\n      if (single.kind !== \"flag\") continue;\n      // Omit hidden flags from completion scripts so tab-completion in the\n      // shell does not advertise flags that are absent from --help.\n      if (single.hidden) continue;\n      flags.push({\n        name: single.name,\n        aliases: single.aliases,\n        description: Option.getOrUndefined(single.description),\n        type: toFlagType(single)\n      });\n    }\n  }\n  const args = [];\n  for (const arg of config.arguments) {\n    const singles = Param.extractSingleParams(arg);\n    const metadata = Param.getParamMetadata(arg);\n    for (const single of singles) {\n      if (single.kind !== \"argument\") continue;\n      args.push({\n        name: single.name,\n        description: Option.getOrUndefined(single.description),\n        required: !metadata.isOptional,\n        variadic: metadata.isVariadic,\n        type: toArgumentType(single)\n      });\n    }\n  }\n  const subcommands = [];\n  for (const group of cmd.subcommands) {\n    for (const subcommand of group.commands) {\n      // Omit hidden subcommands from completion scripts so tab-completion in\n      // the shell does not advertise commands that are absent from --help.\n      if (subcommand.hidden) continue;\n      subcommands.push(fromCommand(subcommand));\n    }\n  }\n  return {\n    name: cmd.name,\n    description: cmd.shortDescription ?? cmd.description,\n    flags,\n    arguments: args,\n    subcommands\n  };\n};\n//# sourceMappingURL=descriptor.js.map","/**\n * Help Documentation\n * ================\n *\n * Internal helpers for generating help documentation.\n * Extracted from command.ts to avoid circular dependencies.\n */\nimport * as Effect from \"../../../Effect.js\";\nimport * as Param from \"../Param.js\";\nimport { toFlagDoc, toImpl } from \"./command.js\";\nconst dedupeGlobalFlags = flags => {\n  const seen = new Set();\n  const deduped = [];\n  for (const flag of flags) {\n    if (seen.has(flag)) {\n      continue;\n    }\n    seen.add(flag);\n    deduped.push(flag);\n  }\n  return deduped;\n};\n/**\n * Returns the resolved command lineage for the provided path.\n * Includes the root command as the first element.\n */\nexport const getCommandsForCommandPath = (command, commandPath) => {\n  const commands = [command];\n  let currentCommand = command;\n  for (let i = 1; i < commandPath.length; i++) {\n    const subcommandName = commandPath[i];\n    let subcommand = undefined;\n    for (const group of currentCommand.subcommands) {\n      subcommand = group.commands.find(sub => sub.name === subcommandName);\n      if (subcommand) {\n        break;\n      }\n    }\n    if (!subcommand) {\n      break;\n    }\n    commands.push(subcommand);\n    currentCommand = subcommand;\n  }\n  return commands;\n};\n/**\n * Returns active global flags for a command path.\n * Built-ins are prepended and declarations are collected root -> leaf.\n */\nexport const getGlobalFlagsForCommandPath = (command, commandPath, builtIns) => {\n  const commands = getCommandsForCommandPath(command, commandPath);\n  const declared = commands.flatMap(current => toImpl(current).globalFlags);\n  return dedupeGlobalFlags([...builtIns, ...declared]);\n};\nconst collectDeclaredGlobalFlags = command => {\n  const collected = [];\n  const visit = current => {\n    const impl = toImpl(current);\n    for (const flag of impl.globalFlags) {\n      collected.push(flag);\n    }\n    for (const group of current.subcommands) {\n      for (const subcommand of group.commands) {\n        visit(subcommand);\n      }\n    }\n  };\n  visit(command);\n  return dedupeGlobalFlags(collected);\n};\nconst getSharedFlagsForCommandPath = (commands, currentFlags) => {\n  if (commands.length <= 1) {\n    return [];\n  }\n  const seen = new Set(currentFlags.map(flag => flag.name));\n  const sharedFlags = [];\n  for (const ancestor of commands.slice(0, -1)) {\n    const ancestorImpl = toImpl(ancestor);\n    for (const flag of ancestorImpl.contextConfig.flags) {\n      const singles = Param.extractSingleParams(flag);\n      for (const single of singles) {\n        if (seen.has(single.name)) {\n          continue;\n        }\n        // Hidden ancestor flags are excluded from the shared-flags section\n        // of subcommand help, the same way they're excluded from the owning\n        // command's own help output.\n        if (single.hidden) {\n          continue;\n        }\n        seen.add(single.name);\n        sharedFlags.push(toFlagDoc(single));\n      }\n    }\n  }\n  return sharedFlags;\n};\n/**\n * Returns all global flags declared in a command tree.\n * Built-ins are prepended and command declarations are deduplicated by identity.\n */\nexport const getGlobalFlagsForCommandTree = (command, builtIns) => dedupeGlobalFlags([...builtIns, ...collectDeclaredGlobalFlags(command)]);\n/**\n * Helper function to get help documentation for a specific command path.\n * Navigates through the command hierarchy to find the right command.\n * Reads active global flags for the path and includes them in the help doc.\n */\nexport const getHelpForCommandPath = (command, commandPath, builtIns) => Effect.gen(function* () {\n  const commands = getCommandsForCommandPath(command, commandPath);\n  const currentCommand = commands.length > 0 ? commands[commands.length - 1] : command;\n  const baseDoc = toImpl(currentCommand).buildHelpDoc(commandPath);\n  const sharedFlags = getSharedFlagsForCommandPath(commands, baseDoc.flags);\n  const flags = getGlobalFlagsForCommandPath(command, commandPath, builtIns);\n  const globalFlagDocs = [];\n  for (const flag of flags) {\n    const singles = Param.extractSingleParams(flag.flag);\n    for (const single of singles) {\n      // Same rule as command-local flags: hidden globals are still parsed\n      // and still trigger their handlers, they just don't appear under\n      // \"GLOBAL FLAGS\" in --help.\n      if (single.hidden) continue;\n      globalFlagDocs.push({\n        ...toFlagDoc(single),\n        required: false\n      });\n    }\n  }\n  return {\n    ...baseDoc,\n    flags: [...sharedFlags, ...baseDoc.flags],\n    globalFlags: globalFlagDocs\n  };\n});\n//# sourceMappingURL=help.js.map","/**\n * Global flags for Effect CLI command trees. Global flags are parsed outside a\n * single command's local flags and can apply to a command and its descendants.\n *\n * This module defines two kinds of global flags: action flags, which run an\n * effect and stop normal command execution, and setting flags, which provide a\n * parsed value to the command handler through the Effect context. It also\n * defines the built-in help, version, wizard, shell-completion, and log-level flags\n * used by `Command.run` and `Command.runWith`.\n *\n * @since 4.0.0\n */\nimport * as Console from \"../../Console.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Option from \"../../Option.js\";\nimport * as CliOutput from \"./CliOutput.js\";\nimport * as Completions_ from \"./Completions.js\";\nimport * as Flag from \"./Flag.js\";\nimport * as CommandDescriptor from \"./internal/completions/descriptor.js\";\nimport * as HelpInternal from \"./internal/help.js\";\n/* ========================================================================== */\n/* Constructors                                                               */\n/* ========================================================================== */\n/**\n * Creates an Action flag that performs a side effect and exits.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const action = options => ({\n  _tag: \"Action\",\n  flag: options.flag,\n  run: options.run\n});\n/**\n * Creates a Setting flag that configures the command handler's environment.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const setting = id => options => {\n  settingIdCounter += 1;\n  const ref = Context.Service(`effect/unstable/cli/GlobalFlag/${id}/${settingIdCounter}`);\n  return Object.assign(ref, {\n    _tag: \"Setting\",\n    id,\n    flag: options.flag\n  });\n};\nlet settingIdCounter = 0;\n/* ========================================================================== */\n/* Built-in Flag References                                                   */\n/* ========================================================================== */\n/**\n * Defines the `--help` / `-h` global flag, which shows help documentation for the\n * active command path.\n *\n * @see {@link BuiltIns} for the default list containing this flag\n * @see {@link action} for defining custom action global flags\n *\n * @category references\n * @since 4.0.0\n */\nexport const Help = /*#__PURE__*/action({\n  flag: /*#__PURE__*/Flag.boolean(\"help\").pipe(/*#__PURE__*/Flag.withAlias(\"h\"), /*#__PURE__*/Flag.withDescription(\"Show help information\")),\n  run: /*#__PURE__*/Effect.fnUntraced(function* (_, {\n    builtIns,\n    command,\n    commandPath\n  }) {\n    const formatter = yield* CliOutput.Formatter;\n    const helpDoc = yield* HelpInternal.getHelpForCommandPath(command, commandPath, builtIns);\n    yield* Console.log(formatter.formatHelpDoc(helpDoc));\n  })\n});\n/**\n * Defines the global action flag for showing command version information.\n *\n * **When to use**\n *\n * Use to add a built-in `--version / -v` flag to a command runner.\n *\n * @category references\n * @since 4.0.0\n */\nexport const Version = /*#__PURE__*/action({\n  flag: /*#__PURE__*/Flag.boolean(\"version\").pipe(/*#__PURE__*/Flag.withAlias(\"v\"), /*#__PURE__*/Flag.withDescription(\"Show version information\")),\n  run: /*#__PURE__*/Effect.fnUntraced(function* (_, {\n    command,\n    version\n  }) {\n    const formatter = yield* CliOutput.Formatter;\n    yield* Console.log(formatter.formatVersion(command.name, version));\n  })\n});\n/**\n * Defines the global action flag for starting interactive wizard mode.\n *\n * **Details**\n *\n * `Command.run` and `Command.runWith` handle this action specially so the\n * generated arguments can be passed back through the command parser.\n *\n * @category references\n * @since 4.0.0\n */\nexport const Wizard = /*#__PURE__*/action({\n  flag: /*#__PURE__*/Flag.boolean(\"wizard\").pipe(/*#__PURE__*/Flag.withDescription(\"Start wizard mode for a command\")),\n  run: () => Effect.void\n});\n/**\n * Defines the `--completions` global flag, which prints a shell completion script for\n * the given shell.\n *\n * **Details**\n *\n * Accepted values are `bash`, `zsh`, `fish`, and `sh`; `sh` is normalized to\n * `bash`.\n *\n * @category references\n * @since 4.0.0\n */\nexport const Completions = /*#__PURE__*/action({\n  flag: /*#__PURE__*/Flag.choice(\"completions\", [\"bash\", \"zsh\", \"fish\", \"sh\"]).pipe(Flag.optional, /*#__PURE__*/Flag.map(v => Option.map(v, s => s === \"sh\" ? \"bash\" : s)), /*#__PURE__*/Flag.withMetavar(\"<bash|zsh|fish|sh>\"), /*#__PURE__*/Flag.withDescription(\"Print shell completion script\")),\n  run: /*#__PURE__*/Effect.fnUntraced(function* (shell, {\n    command\n  }) {\n    if (Option.isNone(shell)) return;\n    const descriptor = CommandDescriptor.fromCommand(command);\n    yield* Console.log(Completions_.generate(command.name, shell.value, descriptor));\n  })\n});\n/**\n * Defines the global setting flag for command log level.\n *\n * **When to use**\n *\n * Use to add a built-in `--log-level` option that configures the minimum log\n * level for the command.\n *\n * @category references\n * @since 4.0.0\n */\nexport const LogLevel = /*#__PURE__*/setting(\"log-level\")({\n  flag: /*#__PURE__*/Flag.choiceWithValue(\"log-level\", [[\"all\", \"All\"], [\"trace\", \"Trace\"], [\"debug\", \"Debug\"], [\"info\", \"Info\"], [\"warn\", \"Warn\"], [\"warning\", \"Warn\"], [\"error\", \"Error\"], [\"fatal\", \"Fatal\"], [\"none\", \"None\"]]).pipe(Flag.optional, /*#__PURE__*/Flag.withDescription(\"Sets the minimum log level\"), /*#__PURE__*/Flag.withMetavar(\"<all|trace|debug|info|warn|warning|error|fatal|none>\"))\n});\n/* ========================================================================== */\n/* References                                                                 */\n/* ========================================================================== */\n/**\n * Built-in global flags in default precedence order.\n *\n * **When to use**\n *\n * Use when extending or inspecting the default global-flag set that\n * `Command.runWith` prepends before user-defined global flags.\n *\n * **Details**\n *\n * The built-ins are `Help`, `Version`, `Wizard`, `Completions`, and `LogLevel`.\n * `Command.runWith` prepends these built-ins when collecting and parsing global\n * flags.\n *\n * **Gotchas**\n *\n * Action flags are processed in active flag order and the first present action\n * exits, so this array controls built-in action precedence.\n *\n * @see {@link Help} for the help action flag\n * @see {@link Version} for the version action flag\n * @see {@link Completions} for the shell-completions action flag\n * @see {@link LogLevel} for the built-in log-level setting flag\n *\n * @category references\n * @since 4.0.0\n */\nexport const BuiltIns = [Help, Version, Wizard, Completions, LogLevel];\n//# sourceMappingURL=GlobalFlag.js.map","/**\n * Configuration for Effect CLI command execution.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as GlobalFlag from \"./GlobalFlag.js\";\n/**\n * Context reference for configuration shared by CLI parsing, help generation,\n * and command execution.\n *\n * **When to use**\n *\n * Use when you need to customize runner-wide CLI behavior, such as which\n * built-in global flags are available.\n *\n * @category services\n * @since 4.0.0\n */\nexport class CliConfig extends /*#__PURE__*/Context.Reference(\"effect/unstable/cli/CliConfig\", {\n  defaultValue: () => defaults\n}) {}\n/**\n * Default CLI configuration containing every built-in global flag.\n *\n * @category defaults\n * @since 4.0.0\n */\nexport const defaults = {\n  builtIns: GlobalFlag.BuiltIns\n};\n/**\n * Creates CLI configuration by merging the provided options over `defaults`.\n *\n * **When to use**\n *\n * Use when you need a configuration value to provide directly through the\n * `CliConfig` context reference.\n *\n * @see {@link layer} for providing configuration as a layer\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => ({\n  ...defaults,\n  ...options\n});\n/**\n * Creates a layer that provides CLI configuration merged over `defaults`.\n *\n * **When to use**\n *\n * Use when wiring customized CLI behavior into an application layer.\n *\n * @see {@link make} for creating a configuration value directly\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.succeed(CliConfig, make(options));\n//# sourceMappingURL=CliConfig.js.map","/** @internal */\nexport function lex(argv) {\n  const endIndex = argv.indexOf(\"--\");\n  if (endIndex === -1) {\n    // No -- delimiter, lex everything normally\n    return {\n      tokens: lexTokens(argv),\n      trailingOperands: []\n    };\n  }\n  // Split at -- delimiter\n  return {\n    tokens: lexTokens(argv.slice(0, endIndex)),\n    trailingOperands: argv.slice(endIndex + 1)\n  };\n}\nconst lexTokens = args => {\n  const tokens = [];\n  for (const arg of args) {\n    if (!arg.startsWith(\"-\")) {\n      tokens.push({\n        _tag: \"Value\",\n        value: arg\n      });\n    } else if (arg.startsWith(\"--\")) {\n      const equalIndex = arg.indexOf(\"=\");\n      if (equalIndex !== -1) {\n        const name = arg.slice(2, equalIndex);\n        const value = arg.slice(equalIndex + 1);\n        tokens.push({\n          _tag: \"LongOption\",\n          name,\n          raw: arg,\n          value\n        });\n      } else {\n        tokens.push({\n          _tag: \"LongOption\",\n          name: arg.slice(2),\n          raw: arg\n        });\n      }\n    } else if (arg.length > 1) {\n      const flags = arg.slice(1);\n      const equalIndex = flags.indexOf(\"=\");\n      if (equalIndex !== -1) {\n        const flag = flags.slice(0, equalIndex);\n        const value = flags.slice(equalIndex + 1);\n        tokens.push({\n          _tag: \"ShortOption\",\n          flag,\n          raw: `-${flag}`,\n          value\n        });\n      } else {\n        for (const ch of flags) {\n          tokens.push({\n            _tag: \"ShortOption\",\n            flag: ch,\n            raw: `-${ch}`\n          });\n        }\n      }\n    } else {\n      tokens.push({\n        _tag: \"Value\",\n        value: arg\n      });\n    }\n  }\n  return tokens;\n};\n//# sourceMappingURL=lexer.js.map","/**\n * Simple Levenshtein distance implementation (small N, no perf worries)\n */\nconst levenshtein = (a, b) => {\n  const m = a.length;\n  const n = b.length;\n  const dp = Array.from({\n    length: m + 1\n  }, () => new Array(n + 1).fill(0));\n  for (let i = 0; i <= m; i++) dp[i][0] = i;\n  for (let j = 0; j <= n; j++) dp[0][j] = j;\n  for (let i = 1; i <= m; i++) {\n    for (let j = 1; j <= n; j++) {\n      const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n      dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);\n    }\n  }\n  return dp[m][n];\n};\n/**\n * Return suggestions with minimum distance found, up to distance 2.\n *\n * @internal\n */\nexport const suggest = (input, candidates) => {\n  const distances = candidates.map(c => [levenshtein(input, c), c]).filter(([d]) => d <= 2) // Stricter threshold\n  .sort(([a], [b]) => a - b);\n  if (distances.length === 0) return [];\n  // Only return suggestions with the minimum distance found\n  const minDistance = distances[0][0];\n  return distances.filter(([d]) => d === minDistance).map(([, c]) => c);\n};\n//# sourceMappingURL=auto-suggest.js.map","/**\n * Parsing Pipeline for CLI Commands\n * ==================================\n *\n * The parser transforms raw argv tokens into structured command input through\n * three main phases:\n *\n * 1. **Lexer** (external): Converts argv strings into typed tokens\n *    - LongOption: --name or --name=value\n *    - ShortOption: -n or -n=value (also handles -abc as three flags)\n *    - Value: positional arguments\n *\n * 2. **Built-in Extraction**: Peels off built-in flags (help/version/completions)\n *    before command-specific parsing begins.\n *\n * 3. **Command Parsing**: Recursively processes command levels:\n *    - Collects flags defined at this level\n *    - Detects subcommand from first value token\n *    - Forwards remaining tokens to child command\n *\n * Key Behaviors\n * -------------\n * - Inherited parent flags may appear before OR after the subcommand name (npm-style)\n * - Only the first Value token can open a subcommand\n * - Errors accumulate rather than throwing exceptions\n */\nimport * as Effect from \"../../../Effect.js\";\nimport * as Option from \"../../../Option.js\";\nimport * as CliError from \"../CliError.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport { suggest } from \"./auto-suggest.js\";\nimport { toImpl } from \"./command.js\";\n/* ========================================================================== */\n/* Public API                                                                 */\n/* ========================================================================== */\n/** @internal */\nexport const getCommandPath = parsedInput => Option.match(parsedInput.subcommand, {\n  onNone: () => [],\n  onSome: subcommand => [subcommand.name, ...getCommandPath(subcommand.parsedInput)]\n});\n/** @internal */\nexport const parseArgs = (lexResult, command, commandPath = []) => Effect.gen(function* () {\n  const {\n    tokens,\n    trailingOperands: afterEndOfOptions\n  } = lexResult;\n  const newCommandPath = [...commandPath, command.name];\n  const commandImpl = toImpl(command);\n  const singles = commandImpl.config.flags.flatMap(Param.extractSingleParams);\n  const flagParams = singles.filter(Param.isFlagParam);\n  const flagRegistry = createFlagRegistry(flagParams);\n  const inheritedSingles = commandImpl.contextConfig.flags.flatMap(Param.extractSingleParams);\n  const inheritedFlagParams = inheritedSingles.filter(Param.isFlagParam);\n  const inheritedFlagRegistry = createFlagRegistry(inheritedFlagParams);\n  const inheritedNames = new Set(inheritedFlagParams.map(param => param.name));\n  const context = {\n    command,\n    commandPath: newCommandPath,\n    flagRegistry,\n    inheritedFlagRegistry,\n    localFlagNames: flagParams.filter(param => !inheritedNames.has(param.name)).map(param => param.name)\n  };\n  const result = scanCommandLevel(tokens, context);\n  if (result._tag === \"Leaf\") {\n    return {\n      flags: result.flags,\n      arguments: [...result.arguments, ...afterEndOfOptions],\n      subcommand: Option.none(),\n      ...(result.errors.length > 0 && {\n        errors: result.errors\n      })\n    };\n  }\n  const subLex = {\n    tokens: result.childTokens,\n    trailingOperands: afterEndOfOptions\n  };\n  const subParsed = yield* parseArgs(subLex, result.sub, newCommandPath);\n  const allErrors = [...result.errors, ...(subParsed.errors ?? [])];\n  return {\n    flags: result.flags,\n    arguments: [],\n    subcommand: Option.some({\n      name: result.sub.name,\n      parsedInput: subParsed\n    }),\n    ...(allErrors.length > 0 && {\n      errors: allErrors\n    })\n  };\n});\nconst makeCursor = tokens => {\n  let i = 0;\n  return {\n    peek: () => tokens[i],\n    take: () => tokens[i++],\n    rest: () => tokens.slice(i)\n  };\n};\n/* ========================================================================== */\n/* Flag Registry                                                              */\n/* ========================================================================== */\n/**\n * Creates a registry for O(1) flag lookup by name or alias.\n * @internal\n */\nexport const createFlagRegistry = params => {\n  const index = new Map();\n  for (const param of params) {\n    if (index.has(param.name)) {\n      throw new Error(`Duplicate flag name \"${param.name}\" in command definition`);\n    }\n    index.set(param.name, param);\n    for (const alias of param.aliases) {\n      if (index.has(alias)) {\n        throw new Error(`Duplicate flag/alias \"${alias}\" in command definition (conflicts with \"${index.get(alias).name}\")`);\n      }\n      index.set(alias, param);\n    }\n  }\n  return {\n    params,\n    index\n  };\n};\nconst buildSubcommandIndex = subcommands => {\n  const index = new Map();\n  const setKey = (key, command) => {\n    const existing = index.get(key);\n    if (existing && existing !== command) {\n      throw new Error(`Duplicate subcommand name/alias \"${key}\" in command definition (conflicts with \"${existing.name}\")`);\n    }\n    index.set(key, command);\n  };\n  for (const group of subcommands) {\n    for (const subcommand of group.commands) {\n      setKey(subcommand.name, subcommand);\n      if (subcommand.alias && subcommand.alias !== subcommand.name) {\n        setKey(subcommand.alias, subcommand);\n      }\n    }\n  }\n  return index;\n};\n/* ========================================================================== */\n/* Flag Accumulator                                                           */\n/* ========================================================================== */\n/** Creates an empty flag map with all known flag names initialized to [].\n * @internal\n */\nexport const createEmptyFlagMap = params => Object.fromEntries(params.map(p => [p.name, []]));\n/**\n * Creates a mutable accumulator for collecting flag values.\n * Pre-initializes empty arrays for all known flags.\n */\nconst createFlagAccumulator = params => {\n  const map = createEmptyFlagMap(params);\n  return {\n    add: (name, raw) => {\n      if (raw !== undefined) map[name].push(raw);\n    },\n    merge: from => {\n      for (const key in from) {\n        const values = from[key];\n        if (values?.length) {\n          for (let i = 0; i < values.length; i++) {\n            map[key].push(values[i]);\n          }\n        }\n      }\n    },\n    snapshot: () => map\n  };\n};\nconst isFlagToken = t => t._tag === \"LongOption\" || t._tag === \"ShortOption\";\nconst getFlagName = t => t._tag === \"LongOption\" ? t.name : t.flag;\nconst resolveFlag = (token, registry) => {\n  const tokenName = getFlagName(token);\n  const direct = registry.index.get(tokenName);\n  if (direct && direct.name === tokenName) {\n    return {\n      param: direct,\n      negated: false\n    };\n  }\n  if (token._tag === \"LongOption\" && token.name.startsWith(\"no-\")) {\n    const canonicalName = token.name.slice(3);\n    const param = registry.index.get(canonicalName);\n    if (param && param.name === canonicalName && Primitive.isBoolean(param.primitiveType)) {\n      return {\n        param,\n        negated: true\n      };\n    }\n  }\n  if (direct) {\n    return {\n      param: direct,\n      negated: false\n    };\n  }\n  return undefined;\n};\nconst invalidNegatedFlagValue = (token, spec, value) => new CliError.InvalidValue({\n  option: spec.name,\n  value,\n  expected: `omit the value and use ${token.raw} by itself to set --${spec.name} to false`,\n  kind: \"flag\"\n});\nconst missingFlagValue = spec => {\n  const choices = Primitive.getChoiceKeys(spec.primitiveType);\n  return new CliError.InvalidValue({\n    option: spec.name,\n    value: \"\",\n    expected: choices === undefined ? spec.typeName ?? Primitive.getTypeName(spec.primitiveType) : choices.join(\" | \"),\n    kind: \"flag\"\n  });\n};\n/**\n * Checks whether a token is a boolean literal value.\n * Recognizes: true/false, yes/no, on/off, 1/0\n */\nconst asBooleanLiteral = token => token?._tag === \"Value\" && (Primitive.isTrueValue(token.value) || Primitive.isFalseValue(token.value)) ? token.value : undefined;\n/* ========================================================================== */\n/* Flag Value Consumption                                                     */\n/* ========================================================================== */\n/**\n * Reads a flag's value from the token stream.\n *\n * Value resolution order:\n * 1. Inline value: --flag=value or -f=value\n * 2. Boolean special case: implicit \"true\" or explicit boolean literal\n * 3. Next token: consume following Value token if present\n */\nconst consumeFlagValue = (cursor, token, spec, negated = false) => {\n  const consumed = consumeFlagValueWithTokens(cursor, token, spec, negated);\n  switch (consumed._tag) {\n    case \"Value\":\n      return {\n        _tag: \"Value\",\n        value: consumed.value\n      };\n    case \"Error\":\n      return {\n        _tag: \"Error\",\n        error: consumed.error\n      };\n  }\n};\nconst consumeFlagValueWithTokens = (cursor, token, spec, negated = false) => {\n  // Inline value has highest priority\n  if (negated) {\n    if (token.value !== undefined) {\n      return {\n        _tag: \"Error\",\n        error: invalidNegatedFlagValue(token, spec, token.value),\n        tokens: []\n      };\n    }\n    const literal = asBooleanLiteral(cursor.peek());\n    if (literal !== undefined) {\n      const literalToken = cursor.take();\n      return {\n        _tag: \"Error\",\n        error: invalidNegatedFlagValue(token, spec, literal),\n        tokens: literalToken === undefined ? [] : [literalToken]\n      };\n    }\n    return {\n      _tag: \"Value\",\n      value: \"false\",\n      tokens: []\n    };\n  }\n  if (token.value !== undefined) {\n    return {\n      _tag: \"Value\",\n      value: token.value,\n      tokens: []\n    };\n  }\n  // Boolean flags: check for explicit literal or default to \"true\"\n  if (Primitive.isBoolean(spec.primitiveType)) {\n    const literal = asBooleanLiteral(cursor.peek());\n    const literalToken = literal !== undefined ? cursor.take() : undefined;\n    return {\n      _tag: \"Value\",\n      value: literal ?? \"true\",\n      tokens: literalToken === undefined ? [] : [literalToken]\n    };\n  }\n  // Non-boolean: try to consume next Value token\n  const next = cursor.peek();\n  if (next?._tag === \"Value\") {\n    const valueToken = cursor.take();\n    return {\n      _tag: \"Value\",\n      value: next.value,\n      tokens: valueToken === undefined ? [] : [valueToken]\n    };\n  }\n  return {\n    _tag: \"Error\",\n    error: missingFlagValue(spec),\n    tokens: []\n  };\n};\n/**\n * Consumes known flags from a token stream.\n * Unrecognized tokens are passed through to remainder.\n * Used for both global flag extraction and npm-style parent flag collection.\n * @internal\n */\nexport const consumeKnownFlags = (tokens, registry) => {\n  const flagMap = createEmptyFlagMap(registry.params);\n  const remainder = [];\n  const errors = [];\n  const cursor = makeCursor(tokens);\n  for (let t = cursor.take(); t; t = cursor.take()) {\n    if (!isFlagToken(t)) {\n      remainder.push(t);\n      continue;\n    }\n    const resolved = resolveFlag(t, registry);\n    if (!resolved) {\n      remainder.push(t);\n      continue;\n    }\n    const consumed = consumeFlagValue(cursor, t, resolved.param, resolved.negated);\n    if (consumed._tag === \"Error\") {\n      errors.push(consumed.error);\n      continue;\n    }\n    if (consumed.value !== undefined) {\n      flagMap[resolved.param.name].push(consumed.value);\n    }\n  }\n  return {\n    flagMap,\n    remainder,\n    errors\n  };\n};\nconst extractFlagParams = command => {\n  const commandImpl = toImpl(command);\n  const singles = commandImpl.config.flags.flatMap(Param.extractSingleParams);\n  return singles.filter(Param.isFlagParam);\n};\nconst extractContextFlagParams = command => {\n  const commandImpl = toImpl(command);\n  const singles = commandImpl.contextConfig.flags.flatMap(Param.extractSingleParams);\n  return singles.filter(Param.isFlagParam);\n};\nconst resolveFromRegistries = (token, registries) => {\n  for (const registry of registries) {\n    const resolved = resolveFlag(token, registry);\n    if (resolved !== undefined) {\n      return resolved;\n    }\n  }\n  return undefined;\n};\nconst preserveFlag = (remainder, cursor, token, resolved) => {\n  remainder.push(token);\n  const consumed = consumeFlagValueWithTokens(cursor, token, resolved.param, resolved.negated);\n  remainder.push(...consumed.tokens);\n};\nconst localFlagWouldPrecedeSubcommand = (token, remainingTokens, resolved, subIndex, registries) => {\n  const cursor = makeCursor(remainingTokens);\n  consumeFlagValueWithTokens(cursor, token, resolved.param, resolved.negated);\n  for (let token = cursor.take(); token; token = cursor.take()) {\n    if (isFlagToken(token)) {\n      const known = resolveFromRegistries(token, registries);\n      if (known !== undefined) {\n        consumeFlagValueWithTokens(cursor, token, known.param, known.negated);\n      }\n      continue;\n    }\n    if (token._tag === \"Value\") {\n      return subIndex.has(token.value);\n    }\n  }\n  return false;\n};\n/**\n * Consumes global flags while walking the command tree.\n *\n * Command-local flags take precedence over global flags at the selected command\n * level. This lets commands reuse a global flag name, for example a subcommand\n * with its own `--version <value>` flag overriding the built-in global\n * `--version` action.\n * @internal\n */\nexport const consumeGlobalFlags = (tokens, command, registry) => {\n  const flagMap = createEmptyFlagMap(registry.params);\n  const errors = [];\n  const consumeLevel = (tokens, command, ignoredRegistries) => {\n    const localRegistry = createFlagRegistry(extractFlagParams(command));\n    const inheritedRegistry = createFlagRegistry(extractContextFlagParams(command));\n    const subIndex = buildSubcommandIndex(command.subcommands);\n    const cursor = makeCursor(tokens);\n    const remainder = [];\n    let awaitingFirstValue = true;\n    for (let token = cursor.take(); token; token = cursor.take()) {\n      if (isFlagToken(token)) {\n        const ignored = resolveFromRegistries(token, ignoredRegistries);\n        if (ignored !== undefined) {\n          preserveFlag(remainder, cursor, token, ignored);\n          continue;\n        }\n        const inherited = resolveFlag(token, inheritedRegistry);\n        if (inherited !== undefined) {\n          preserveFlag(remainder, cursor, token, inherited);\n          continue;\n        }\n        const local = resolveFlag(token, localRegistry);\n        const global = resolveFlag(token, registry);\n        if (local !== undefined) {\n          if (global === undefined || !awaitingFirstValue || !localFlagWouldPrecedeSubcommand(token, cursor.rest(), local, subIndex, [localRegistry, inheritedRegistry, registry])) {\n            preserveFlag(remainder, cursor, token, local);\n            continue;\n          }\n        }\n        if (global !== undefined) {\n          const consumed = consumeFlagValueWithTokens(cursor, token, global.param, global.negated);\n          if (consumed._tag === \"Error\") {\n            errors.push(consumed.error);\n            continue;\n          }\n          if (consumed.value !== undefined) {\n            flagMap[global.param.name].push(consumed.value);\n          }\n          continue;\n        }\n        remainder.push(token);\n        continue;\n      }\n      if (token._tag === \"Value\" && awaitingFirstValue) {\n        const sub = subIndex.get(token.value);\n        if (sub !== undefined) {\n          remainder.push(token);\n          remainder.push(...consumeLevel(cursor.rest(), sub, [...ignoredRegistries, inheritedRegistry]));\n          return remainder;\n        }\n        awaitingFirstValue = false;\n      }\n      remainder.push(token);\n    }\n    return remainder;\n  };\n  return {\n    flagMap,\n    remainder: consumeLevel(tokens, command, []),\n    errors\n  };\n};\n/* ========================================================================== */\n/* Error Creation                                                             */\n/* ========================================================================== */\nconst createUnrecognizedFlagError = (token, params, commandPath) => {\n  const printable = token._tag === \"LongOption\" ? `--${token.name}` : `-${token.flag}`;\n  const validNames = [];\n  for (const p of params) {\n    // Exclude hidden flags so a near-miss typo cannot reveal a flag name\n    // that was intentionally kept out of --help.\n    if (p.hidden) continue;\n    validNames.push(p.name);\n    if (Primitive.isBoolean(p.primitiveType)) {\n      validNames.push(`no-${p.name}`);\n    }\n    for (const alias of p.aliases) {\n      validNames.push(alias);\n    }\n  }\n  const suggestions = suggest(getFlagName(token), validNames).map(n => n.length === 1 ? `-${n}` : `--${n}`);\n  return new CliError.UnrecognizedOption({\n    option: printable,\n    suggestions,\n    command: commandPath\n  });\n};\n/* ========================================================================== */\n/* Parse State                                                                */\n/* ========================================================================== */\nconst createParseState = registry => ({\n  flags: createFlagAccumulator(registry.params),\n  arguments: [],\n  errors: [],\n  mode: {\n    _tag: \"AwaitingFirstValue\"\n  }\n});\nconst toLeafResult = state => ({\n  _tag: \"Leaf\",\n  flags: state.flags.snapshot(),\n  arguments: state.arguments,\n  errors: state.errors\n});\n/* ========================================================================== */\n/* First Value Resolution                                                     */\n/* ========================================================================== */\n/**\n * Determines how to handle the first value token.\n *\n * If it matches a known subcommand:\n * - Collect inherited parent flags from remaining tokens (npm-style)\n * - Return SubcommandResult with child tokens\n *\n * Otherwise:\n * - Return Argument to treat it as a positional argument\n * - Report error if command expects subcommand but got unknown value\n */\nconst resolveFirstValue = (value, cursor, context, state) => {\n  const {\n    command,\n    commandPath,\n    inheritedFlagRegistry,\n    localFlagNames\n  } = context;\n  const subIndex = buildSubcommandIndex(command.subcommands);\n  const sub = subIndex.get(value);\n  if (sub) {\n    const selectedPath = [...commandPath, sub.name];\n    // Local flags are not inherited by subcommands.\n    const parentFlags = state.flags.snapshot();\n    for (const localFlagName of localFlagNames) {\n      const values = parentFlags[localFlagName];\n      if (values !== undefined && values.length > 0) {\n        state.errors.push(new CliError.UnrecognizedOption({\n          option: `--${localFlagName}`,\n          suggestions: [],\n          command: selectedPath\n        }));\n      }\n    }\n    // npm-style: inherited parent flags can appear after subcommand name\n    const tail = consumeKnownFlags(cursor.rest(), inheritedFlagRegistry);\n    state.flags.merge(tail.flagMap);\n    state.errors.push(...tail.errors);\n    return {\n      _tag: \"Subcommand\",\n      result: {\n        _tag: \"Sub\",\n        flags: state.flags.snapshot(),\n        sub,\n        childTokens: tail.remainder,\n        errors: state.errors\n      }\n    };\n  }\n  // Not a subcommand. Check if this looks like a typo.\n  const expectsArgs = toImpl(command).config.arguments.length > 0;\n  if (!expectsArgs && subIndex.size > 0) {\n    // Exclude hidden subcommands so a typo cannot reveal a subcommand name\n    // that was intentionally kept out of --help. Hidden commands still\n    // resolve via subIndex when invoked by exact name.\n    const visibleKeys = [];\n    for (const [key, sub] of subIndex) {\n      if (!sub.hidden) visibleKeys.push(key);\n    }\n    const suggestions = suggest(value, visibleKeys);\n    state.errors.push(new CliError.UnknownSubcommand({\n      subcommand: value,\n      parent: commandPath,\n      suggestions\n    }));\n  }\n  return {\n    _tag: \"Argument\"\n  };\n};\n/* ========================================================================== */\n/* Token Processing                                                           */\n/* ========================================================================== */\n/**\n * Processes a flag token: looks up in registry, consumes value, records it.\n * Reports unrecognized flags as errors.\n */\nconst processFlag = (token, cursor, context, state) => {\n  const {\n    commandPath,\n    flagRegistry\n  } = context;\n  const resolved = resolveFlag(token, flagRegistry);\n  if (!resolved) {\n    state.errors.push(createUnrecognizedFlagError(token, flagRegistry.params, commandPath));\n    return;\n  }\n  const consumed = consumeFlagValue(cursor, token, resolved.param, resolved.negated);\n  if (consumed._tag === \"Error\") {\n    state.errors.push(consumed.error);\n    return;\n  }\n  state.flags.add(resolved.param.name, consumed.value);\n};\n/**\n * Processes a value token based on current parsing mode.\n *\n * In AwaitingFirstValue mode:\n * - Check if value is a subcommand\n * - If so, return SubcommandResult to exit scanning\n * - If not, switch to CollectingArguments mode\n *\n * In CollectingArguments mode:\n * - Simply add value to arguments list\n */\nconst processValue = (value, cursor, context, state) => {\n  if (state.mode._tag === \"AwaitingFirstValue\") {\n    const result = resolveFirstValue(value, cursor, context, state);\n    if (result._tag === \"Subcommand\") {\n      return result.result;\n    }\n    state.mode = {\n      _tag: \"CollectingArguments\"\n    };\n  }\n  state.arguments.push(value);\n  return undefined;\n};\n/* ========================================================================== */\n/* Command Level Scanning                                                     */\n/* ========================================================================== */\n/**\n * Scans a single command level, processing all tokens.\n *\n * For each token:\n * - Flags: Look up, consume value, record in accumulator\n * - Values: Check for subcommand (first value only), then collect as arguments\n *\n * Returns LeafResult if no subcommand detected, SubcommandResult otherwise.\n */\nconst scanCommandLevel = (tokens, context) => {\n  const cursor = makeCursor(tokens);\n  const state = createParseState(context.flagRegistry);\n  for (let token = cursor.take(); token; token = cursor.take()) {\n    if (isFlagToken(token)) {\n      processFlag(token, cursor, context, state);\n      continue;\n    }\n    if (token._tag === \"Value\") {\n      const subResult = processValue(token.value, cursor, context, state);\n      if (subResult) return subResult;\n    }\n  }\n  return toLeafResult(state);\n};\n//# sourceMappingURL=parser.js.map","import * as Console from \"../../../Console.js\";\nimport * as Effect from \"../../../Effect.js\";\nimport * as Option from \"../../../Option.js\";\nimport * as Redacted from \"../../../Redacted.js\";\nimport * as Param from \"../Param.js\";\nimport * as Primitive from \"../Primitive.js\";\nimport * as Prompt from \"../Prompt.js\";\nimport * as Ansi from \"./ansi.js\";\nimport { toImpl } from \"./command.js\";\nexport const run = /*#__PURE__*/Effect.fnUntraced(function* (command, options) {\n  const commandPath = options?.commandPath ?? [command.name];\n  const selected = getCommandAtPath(command, commandPath);\n  const commandLine = [...(options?.prefix ?? commandPath)];\n  yield* logCurrentCommand(commandLine);\n  yield* promptCommand(selected, commandLine, selected === command ? \"ROOT\" : selected.name);\n  return commandLine;\n});\nconst getCommandAtPath = (command, commandPath) => {\n  let current = command;\n  for (const name of commandPath.slice(1)) {\n    const child = current.subcommands.flatMap(group => group.commands).find(candidate => candidate.name === name || candidate.alias === name);\n    if (child === undefined) {\n      break;\n    }\n    current = child;\n  }\n  return current;\n};\nconst promptCommand = /*#__PURE__*/Effect.fnUntraced(function* (command, commandLine, sectionName) {\n  const impl = toImpl(command);\n  const visibleSubcommands = command.subcommands.flatMap(group => group.commands.filter(child => !child.hidden));\n  const config = visibleSubcommands.length === 0 ? impl.config : impl.contextConfig;\n  if (config.flags.length > 0) {\n    yield* Console.log(renderSection(sectionName, \"FLAGS\"));\n    for (const param of config.flags) {\n      commandLine.push(...(yield* promptParam(param)));\n    }\n    if (config.arguments.length > 0 || visibleSubcommands.length > 0) {\n      yield* logCurrentCommand(commandLine);\n    }\n  }\n  if (config.arguments.length > 0) {\n    yield* Console.log(renderSection(sectionName, \"ARGUMENTS\"));\n    for (const param of config.arguments) {\n      commandLine.push(...(yield* promptParam(param)));\n    }\n    if (visibleSubcommands.length > 0) {\n      yield* logCurrentCommand(commandLine);\n    }\n  }\n  if (visibleSubcommands.length === 0) {\n    return;\n  }\n  const child = yield* Prompt.run(Prompt.select({\n    message: \"Command\",\n    choices: visibleSubcommands.map(command => ({\n      title: command.name,\n      value: command,\n      ...(command.shortDescription !== undefined ? {\n        description: command.shortDescription\n      } : command.description !== undefined ? {\n        description: command.description\n      } : {})\n    }))\n  }));\n  yield* Console.log();\n  commandLine.push(child.name);\n  if (hasWizardSteps(child)) {\n    yield* logCurrentCommand(commandLine);\n  }\n  yield* promptCommand(child, commandLine, child.name);\n});\nconst hasWizardSteps = command => {\n  const hasVisibleSubcommands = command.subcommands.some(group => group.commands.some(child => !child.hidden));\n  return hasVisibleSubcommands || toImpl(command).config.orderedParams.length > 0;\n};\nconst promptParam = /*#__PURE__*/Effect.fnUntraced(function* (param) {\n  const single = Param.getUnderlyingSingleOrThrow(param);\n  const metadata = Param.getParamMetadata(param);\n  if (metadata.isOptional) {\n    const include = yield* Prompt.run(Prompt.confirm({\n      message: `Set ${renderParamLabel(single)}?`,\n      initial: false\n    }));\n    if (!include) {\n      yield* Console.log();\n      return [];\n    }\n  }\n  const count = !metadata.isVariadic ? 1 : yield* Prompt.run(Prompt.integer({\n    message: `${renderParamLabel(single)} count`,\n    default: Option.getOrElse(metadata.variadicMin, () => 0),\n    min: Option.getOrElse(metadata.variadicMin, () => 0),\n    ...(Option.isSome(metadata.variadicMax) ? {\n      max: metadata.variadicMax.value\n    } : {})\n  }));\n  const values = [];\n  for (let i = 0; i < count; i++) {\n    values.push(yield* promptSingle(single));\n  }\n  const parsed = single.kind === Param.flagKind ? {\n    flags: {\n      [single.name]: values\n    },\n    arguments: []\n  } : {\n    flags: {},\n    arguments: values\n  };\n  yield* param.parse(parsed);\n  yield* Console.log();\n  if (single.kind === Param.argumentKind) {\n    return values;\n  }\n  return values.flatMap(value => [`--${single.name}`, value]);\n});\nconst promptSingle = single => {\n  const message = renderParamMessage(single);\n  switch (single.primitiveType._tag) {\n    case \"Boolean\":\n      return Effect.map(Prompt.run(Prompt.confirm({\n        message,\n        label: {\n          confirm: \"true\",\n          deny: \"false\"\n        },\n        placeholder: {\n          defaultConfirm: \"(T/f)\",\n          defaultDeny: \"(t/F)\"\n        }\n      })), String);\n    case \"Choice\":\n      {\n        const choices = Primitive.getChoiceKeys(single.primitiveType) ?? [];\n        return Prompt.run(Prompt.select({\n          message,\n          choices: choices.map(choice => ({\n            title: choice,\n            value: choice\n          }))\n        }));\n      }\n    case \"Date\":\n      return Effect.map(Prompt.run(Prompt.date({\n        message\n      })), date => date.toISOString());\n    case \"Float\":\n      return Effect.map(Prompt.run(Prompt.float({\n        message\n      })), String);\n    case \"Integer\":\n      return Effect.map(Prompt.run(Prompt.integer({\n        message\n      })), String);\n    case \"Redacted\":\n      return Effect.map(Prompt.run(Prompt.password({\n        message\n      })), Redacted.value);\n    default:\n      return Prompt.run(Prompt.text({\n        message\n      }));\n  }\n};\nconst formatName = single => single.kind === Param.flagKind ? `--${single.name}` : single.name;\nconst renderParamMessage = single => renderParamLabel(single);\nconst renderParamLabel = single => {\n  const description = Option.getOrUndefined(single.description)?.trim();\n  const label = single.kind === Param.flagKind && description !== undefined && description.length <= 32 ? description : humanize(single.name);\n  return single.kind === Param.flagKind ? `${label} (${formatName(single)})` : label;\n};\nconst humanize = name => {\n  const words = name.split(/[-_]+/).filter(word => word.length > 0);\n  if (words.length === 0) return name;\n  return [words[0][0].toUpperCase() + words[0].slice(1), ...words.slice(1)].join(\" \");\n};\nconst logCurrentCommand = commandLine => Console.log(renderCommandBlock(\"Current command\", commandLine, Ansi.magenta));\nconst renderSection = (commandName, section) => `${Ansi.annotate(commandName.toUpperCase(), Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(\"·\", Ansi.blackBright)} ${Ansi.annotate(section, Ansi.bold, Ansi.white)}`;\nexport const renderIntroduction = (name, version, summary) => {\n  const title = `${Ansi.annotate(name, Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(`v${version}`, Ansi.white)} ${Ansi.annotate(\"· Command wizard\", Ansi.bold, Ansi.white)}`;\n  return [title, ...(summary === undefined || summary.length === 0 ? [] : [summary]), Ansi.annotate(\"Build a command interactively. Press Ctrl+C to cancel.\", Ansi.blackBright), \"\"].join(\"\\n\");\n};\nexport const renderCompletion = commandLine => renderCommandBlock(\"Command ready\", commandLine, Ansi.cyanBright, Ansi.green);\nexport const renderQuit = () => `\\n${Ansi.annotate(\"Wizard cancelled.\", Ansi.red)}`;\nconst renderCommandBlock = (label, commandLine, commandColor, labelColor = Ansi.white) => {\n  const lines = wrapCommand(commandLine);\n  return [Ansi.annotate(label, Ansi.bold, labelColor), ...lines.map(line => Ansi.annotate(line, commandColor)), \"\"].join(\"\\n\");\n};\nconst wrapCommand = commandLine => {\n  const width = 88;\n  const firstIndent = \"  $ \";\n  const continuationIndent = \"    \";\n  const args = commandLine.map(formatShellArg);\n  const lines = [];\n  let current = firstIndent;\n  for (const arg of args) {\n    const separator = current === firstIndent || current === continuationIndent ? \"\" : \" \";\n    if (current.length + separator.length + arg.length > width && current !== firstIndent) {\n      lines.push(`${current} \\\\`);\n      current = `${continuationIndent}${arg}`;\n    } else {\n      current += `${separator}${arg}`;\n    }\n  }\n  if (current !== firstIndent) {\n    lines.push(current);\n  }\n  return lines;\n};\nconst formatShellArg = arg => /^[A-Za-z0-9_./:@%+=,-]+$/.test(arg) ? arg : `'${arg.replaceAll(\"'\", `'\"'\"'`)}'`;\n//# sourceMappingURL=wizard.js.map","import * as Console from \"../../Console.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as References from \"../../References.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Stdio from \"../../Stdio.js\";\nimport * as Terminal from \"../../Terminal.js\";\nimport * as CliConfig from \"./CliConfig.js\";\nimport * as CliError from \"./CliError.js\";\nimport * as CliOutput from \"./CliOutput.js\";\nimport * as GlobalFlag from \"./GlobalFlag.js\";\nimport { checkForDuplicateFlags, makeCommand, makeParser, toImpl, TypeId } from \"./internal/command.js\";\nimport { mergeConfig, parseConfig } from \"./internal/config.js\";\nimport { getGlobalFlagsForCommandPath, getGlobalFlagsForCommandTree, getHelpForCommandPath } from \"./internal/help.js\";\nimport * as Lexer from \"./internal/lexer.js\";\nimport * as Parser from \"./internal/parser.js\";\nimport * as Wizard from \"./internal/wizard.js\";\nimport * as Param from \"./Param.js\";\nimport * as Prompt from \"./Prompt.js\";\n/**\n * Returns `true` if the provided value is a `Command`.\n *\n * **Gotchas**\n *\n * This checks for the `Command` type-id property; it does not validate the full\n * command shape.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isCommand = u => Predicate.hasProperty(u, TypeId);\n/* ========================================================================== */\n/* Constructors                                                               */\n/* ========================================================================== */\n/**\n * Creates a `Command` from a name, an optional configuration, and an optional\n * handler.\n *\n * **Details**\n *\n * Use `withDescription` and related metadata combinators to add help text. The\n * overloads support simple commands, configured commands, and commands with\n * effectful handlers.\n *\n * **Example** (Creating commands)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Argument, Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * // Simple command with no configuration\n * const version = Command.make(\"version\")\n *\n * // Command with simple flags\n * const greet = Command.make(\"greet\", {\n *   name: Flag.string(\"name\"),\n *   count: Flag.integer(\"count\").pipe(Flag.withDefault(1))\n * })\n *\n * // Command with nested configuration\n * const deploy = Command.make(\"deploy\", {\n *   environment: Flag.string(\"env\").pipe(\n *     Flag.withDescription(\"Target environment\")\n *   ),\n *   server: {\n *     host: Flag.string(\"host\").pipe(Flag.withDefault(\"localhost\")),\n *     port: Flag.integer(\"port\").pipe(Flag.withDefault(3000))\n *   },\n *   files: Argument.string(\"files\").pipe(Argument.variadic),\n *   force: Flag.boolean(\"force\").pipe(Flag.withDescription(\"Force deployment\"))\n * })\n *\n * // Command with handler\n * const output: Array<string> = []\n * const deployWithHandler = Command.make(\"deploy\", {\n *   environment: Flag.string(\"env\"),\n *   force: Flag.boolean(\"force\")\n * }, (config) =>\n *   Effect.gen(function*() {\n *     yield* Effect.sync(() => output.push(`Starting deployment to ${config.environment}`))\n *\n *     if (!config.force && config.environment === \"production\") {\n *       return yield* Effect.fail(\"Production deployments require --force flag\")\n *     }\n *\n *     yield* Effect.sync(() => output.push(\"Deployment completed successfully\"))\n *   }))\n *\n * await Effect.runPromise(\n *   Command.runWith(deployWithHandler, { version: \"1.0.0\" })([\n *     \"--env\",\n *     \"staging\",\n *     \"--force\"\n *   ]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Starting deployment to staging\", \"Deployment completed successfully\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (name, config, handler) => {\n  const parsedConfig = parseConfig(config ?? {});\n  return makeCommand({\n    name,\n    config: parsedConfig,\n    ...(Predicate.isNotUndefined(handler) ? {\n      handle: handler\n    } : {})\n  });\n};\n/* ========================================================================== */\n/* Combinators                                                                */\n/* ========================================================================== */\n/**\n * Adds or replaces the handler for a command.\n *\n * **Example** (Adding command handlers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * // Command without initial handler\n * const greet = Command.make(\"greet\", {\n *   name: Flag.string(\"name\")\n * })\n *\n * // Add handler later\n * const output: Array<string> = []\n * const greetWithHandler = greet.pipe(\n *   Command.withHandler((config: { readonly name: string }) =>\n *     Effect.sync(() => output.push(`Hello, ${config.name}!`)).pipe(Effect.asVoid)\n *   )\n * )\n *\n * await Effect.runPromise(\n *   Command.runWith(greetWithHandler, { version: \"1.0.0\" })([\"--name\", \"Alice\"]).pipe(\n *     Effect.provide(CliTestLayer)\n *   )\n * )\n * output // => [\"Hello, Alice!\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withHandler = /*#__PURE__*/dual(2, (self, handler) => makeCommand({\n  ...toImpl(self),\n  handle: handler\n}));\nconst normalizeSubcommandEntries = entries => {\n  const flat = [];\n  const grouped = new Map();\n  const addToGroup = (group, command) => {\n    flat.push(command);\n    const existing = grouped.get(group);\n    if (existing) {\n      existing.push(command);\n    } else {\n      grouped.set(group, [command]);\n    }\n  };\n  for (const entry of entries) {\n    if (isCommand(entry)) {\n      addToGroup(undefined, entry);\n      continue;\n    }\n    for (const command of entry.commands) {\n      addToGroup(entry.group, command);\n    }\n  }\n  const groups = [];\n  const ungroupedCommands = grouped.get(undefined);\n  if (ungroupedCommands && ungroupedCommands.length > 0) {\n    groups.push({\n      group: undefined,\n      commands: ungroupedCommands\n    });\n  }\n  for (const [group, commands] of grouped) {\n    if (group === undefined) {\n      continue;\n    }\n    groups.push({\n      group,\n      commands\n    });\n  }\n  return {\n    flat,\n    groups\n  };\n};\n/**\n * Adds subcommands to a command, creating a hierarchical command structure.\n *\n * **Details**\n *\n * Subcommands can access their parent's parsed configuration by yielding the parent\n * command within their handler. This enables shared parent flags that affect\n * all subcommands.\n *\n * **Example** (Adding subcommands)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * // Parent command with shared flags\n * const git = Command.make(\"git\").pipe(\n *   Command.withSharedFlags({\n *     verbose: Flag.boolean(\"verbose\")\n *   })\n * )\n *\n * // Subcommand that accesses parent config\n * const output: Array<string> = []\n * const clone = Command.make(\"clone\", {\n *   repository: Flag.string(\"repo\")\n * }, (config) =>\n *   Effect.gen(function*() {\n *     const parent = yield* git // Access parent's parsed config\n *     if (parent.verbose) {\n *       yield* Effect.sync(() => output.push(\"Verbose mode enabled\"))\n *     }\n *     yield* Effect.sync(() => output.push(`Cloning ${config.repository}`))\n *   }))\n *\n * const app = git.pipe(Command.withSubcommands([clone]))\n *\n * await Effect.runPromise(\n *   Command.runWith(app, { version: \"1.0.0\" })([\n *     \"--verbose\",\n *     \"clone\",\n *     \"--repo\",\n *     \"github.com/foo/bar\"\n *   ]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Verbose mode enabled\", \"Cloning github.com/foo/bar\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withSubcommands = /*#__PURE__*/dual(2, (self, subcommands) => {\n  const normalized = normalizeSubcommandEntries(subcommands);\n  checkForDuplicateFlags(self, normalized.flat);\n  const impl = toImpl(self);\n  const byName = new Map(normalized.flat.map(s => [s.name, toImpl(s)]));\n  const SubcommandStateSymbol = Symbol(\"effect/cli/SubcommandState\");\n  const parse = Effect.fnUntraced(function* (raw) {\n    if (Option.isNone(raw.subcommand)) {\n      return yield* impl.parse(raw);\n    }\n    const sub = byName.get(raw.subcommand.value.name);\n    if (!sub) {\n      return yield* impl.parse(raw);\n    }\n    const context = yield* impl.parseContext(raw);\n    const result = yield* sub.parse(raw.subcommand.value.parsedInput);\n    return {\n      ...context,\n      [SubcommandStateSymbol]: {\n        name: sub.name,\n        result\n      }\n    };\n  });\n  const handle = Effect.fnUntraced(function* (input, path) {\n    const internal = input;\n    const selectedSubcommand = internal[SubcommandStateSymbol];\n    if (selectedSubcommand) {\n      const child = byName.get(selectedSubcommand.name);\n      if (!child) {\n        return yield* new CliError.ShowHelp({\n          commandPath: path,\n          errors: []\n        });\n      }\n      return yield* child.handle(selectedSubcommand.result, [...path, child.name]).pipe(Effect.provideService(impl.service, input));\n    }\n    return yield* impl.handle(input, path);\n  });\n  return makeCommand({\n    name: impl.name,\n    config: impl.config,\n    contextConfig: impl.contextConfig,\n    description: impl.description,\n    shortDescription: impl.shortDescription,\n    alias: impl.alias,\n    annotations: impl.annotations,\n    globalFlags: impl.globalFlags,\n    examples: impl.examples,\n    service: impl.service,\n    subcommands: normalized.groups,\n    parse,\n    parseContext: impl.parseContext,\n    handle\n  });\n});\n/**\n * Adds flags that are inherited by subcommands.\n *\n * **Details**\n *\n * Shared flags are available to this command's handler and to descendant\n * handlers via `yield* parentCommand`. Shared flags are accepted both before\n * and after a selected subcommand name (npm-style).\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withSharedFlags = /*#__PURE__*/dual(2, (self, sharedFlags) => {\n  const impl = toImpl(self);\n  const sharedConfig = parseConfig(sharedFlags);\n  const mergedConfig = mergeConfig(impl.config, sharedConfig);\n  const mergedContextConfig = mergeConfig(impl.contextConfig, sharedConfig);\n  if (impl.subcommands.length > 0) {\n    const flatSubcommands = impl.subcommands.flatMap(group => group.commands);\n    checkForDuplicateFlags(self, flatSubcommands, {\n      contextConfig: mergedContextConfig\n    });\n  }\n  const parseShared = makeParser(sharedConfig, {\n    allowLeftovers: true\n  });\n  const parse = Effect.fnUntraced(function* (raw) {\n    const base = yield* impl.parse(raw);\n    const shared = yield* parseShared(raw);\n    return {\n      ...base,\n      ...shared\n    };\n  });\n  const parseContext = Effect.fnUntraced(function* (raw) {\n    const base = yield* impl.parseContext(raw);\n    const shared = yield* parseShared(raw);\n    return {\n      ...base,\n      ...shared\n    };\n  });\n  const handle = (input, commandPath) => impl.handle(input, commandPath);\n  return makeCommand({\n    name: impl.name,\n    config: mergedConfig,\n    contextConfig: mergedContextConfig,\n    description: impl.description,\n    shortDescription: impl.shortDescription,\n    alias: impl.alias,\n    annotations: impl.annotations,\n    globalFlags: impl.globalFlags,\n    examples: impl.examples,\n    service: impl.service,\n    subcommands: impl.subcommands,\n    parse,\n    parseContext,\n    handle\n  });\n});\n/**\n * Adds global flags to a command scope.\n *\n * **Details**\n *\n * Declared global flags apply to the command and all of its descendants.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withGlobalFlags = /*#__PURE__*/dual(2, (self, globalFlags) => {\n  const impl = toImpl(self);\n  const next = Array.from(new Set([...impl.globalFlags, ...globalFlags]));\n  return makeCommand({\n    ...impl,\n    globalFlags: next\n  });\n});\n/**\n * Sets the description for a command.\n *\n * **Details**\n *\n * Descriptions provide users with information about what the command does\n * when they view help documentation.\n *\n * **Example** (Setting descriptions)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const output: Array<string> = []\n * const deploy = Command.make(\"deploy\", {\n *   environment: Flag.string(\"env\")\n * }, (config) =>\n *   Effect.gen(function*() {\n *     yield* Effect.sync(() => output.push(`Deploying to ${config.environment}`))\n *   })).pipe(\n *     Command.withDescription(\"Deploy the application to a specified environment\")\n *   )\n *\n * await Effect.runPromise(\n *   Command.runWith(deploy, { version: \"1.0.0\" })([\"--env\", \"staging\"]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Deploying to staging\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withDescription = /*#__PURE__*/dual(2, (self, description) => makeCommand({\n  ...toImpl(self),\n  description\n}));\n/**\n * Sets a short description for a command.\n *\n * **Details**\n *\n * Short descriptions are used when listing subcommands in help output and\n * shell completions. If no short description is provided, the full\n * `description` is used as a fallback.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withShortDescription = /*#__PURE__*/dual(2, (self, shortDescription) => makeCommand({\n  ...toImpl(self),\n  shortDescription\n}));\n/**\n * Sets an alias for a command.\n *\n * **Details**\n *\n * Aliases are accepted as alternate subcommand names during parsing and are\n * shown in help output as `name, alias`.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withAlias = /*#__PURE__*/dual(2, (self, alias) => makeCommand({\n  ...toImpl(self),\n  alias\n}));\n/**\n * Hides a subcommand from parent help output, shell completions, and\n * \"did you mean?\" suggestions while keeping it fully invocable by exact name.\n *\n * **When to use**\n *\n * Use when experimental or internal subcommands should be accepted but not advertised on\n * the public CLI surface.\n *\n * **Example** (Hiding a subcommand)\n *\n * ```ts import.meta.vitest\n * import { Command } from \"effect/unstable/cli\"\n *\n * // `experimental` still runs when invoked as `mycli experimental`,\n * // but it does not appear under SUBCOMMANDS in `mycli --help`.\n * const experimental = Command.make(\"experimental\").pipe(\n *   Command.withHidden\n * )\n *\n * const root = Command.make(\"mycli\").pipe(\n *   Command.withSubcommands([experimental])\n * )\n *\n * root.subcommands[0].commands[0].hidden // => true\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withHidden = self => makeCommand({\n  ...toImpl(self),\n  hidden: true\n});\n/**\n * Adds a custom annotation to a command.\n *\n * **When to use**\n *\n * Use to attach one command-scoped metadata value under a `Context.Key`,\n * especially for consumers such as custom help formatters.\n *\n * **Details**\n *\n * Annotations are stored on the command's annotation context and flow into\n * generated help document annotations.\n *\n * **Gotchas**\n *\n * Adding the same `Context.Key` again replaces the earlier value.\n *\n * @see {@link annotateMerge} for merging an existing annotation context\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const annotate = /*#__PURE__*/dual(3, (self, service, value) => {\n  const impl = toImpl(self);\n  return makeCommand({\n    ...impl,\n    annotations: Context.add(impl.annotations, service, value)\n  });\n});\n/**\n * Merges a Context of annotations into a command.\n *\n * **When to use**\n *\n * Use when you need to attach an already-built `Context.Context` of command\n * annotations.\n *\n * **Details**\n *\n * Merged annotations are stored on the command and exposed through generated\n * help document annotations.\n *\n * **Gotchas**\n *\n * If both contexts contain the same `Context.Key`, the incoming annotations\n * context wins.\n *\n * @see {@link annotate} for adding a single annotation without constructing a `Context`\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const annotateMerge = /*#__PURE__*/dual(2, (self, annotations) => {\n  const impl = toImpl(self);\n  return makeCommand({\n    ...impl,\n    annotations: Context.merge(impl.annotations, annotations)\n  });\n});\n/**\n * Sets usage examples for a command.\n *\n * **Details**\n *\n * Examples are exposed in structured `HelpDoc` data and rendered by the\n * default formatter in an `EXAMPLES` section.\n *\n * **Example** (Adding usage examples)\n *\n * ```ts import.meta.vitest\n * import { Command } from \"effect/unstable/cli\"\n *\n * const login = Command.make(\"login\").pipe(\n *   Command.withExamples([\n *     { command: \"myapp login\", description: \"Log in with browser OAuth\" },\n *     { command: \"myapp login --token sbp_abc123\", description: \"Log in with a token\" }\n *   ])\n * )\n *\n * login.examples.map((example) => example.command) // => [\"myapp login\", \"myapp login --token sbp_abc123\"]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const withExamples = /*#__PURE__*/dual(2, (self, examples) => makeCommand({\n  ...toImpl(self),\n  examples\n}));\n/* ========================================================================== */\n/* Providing Services                                                         */\n/* ========================================================================== */\n// Internal helper: transforms a command's handler while preserving other properties\nconst mapHandler = (self, f) => {\n  const impl = toImpl(self);\n  return makeCommand({\n    ...impl,\n    handle: (input, path) => f(impl.handle(input, path), input)\n  });\n};\n/**\n * Provides the handler of a command with the services produced by a layer\n * that optionally depends on the command-line input to be created.\n *\n * **Example** (Providing command services)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, PlatformError, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const output: Array<string> = []\n * const deploy = Command.make(\"deploy\", {\n *   env: Flag.string(\"env\")\n * }, (config) =>\n *   Effect.gen(function*() {\n *     const fs = yield* FileSystem.FileSystem\n *     yield* Effect.sync(() => output.push(`Using file system for ${config.env}`))\n *   })).pipe(\n *     // Provide FileSystem based on the --env flag\n *     Command.provide((config) =>\n *       config.env === \"local\"\n *         ? FileSystem.layerNoop({})\n *         : FileSystem.layerNoop({\n *           access: () =>\n *             Effect.fail(\n *               PlatformError.badArgument({\n *                 module: \"FileSystem\",\n *                 method: \"access\"\n *               })\n *             )\n *         })\n *     )\n *   )\n *\n * await Effect.runPromise(\n *   Command.runWith(deploy, { version: \"1.0.0\" })([\"--env\", \"local\"]).pipe(Effect.provide(CliTestLayer))\n * )\n * output // => [\"Using file system for local\"]\n * ```\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provide = /*#__PURE__*/dual(args => isCommand(args[0]), (self, layer, options) => mapHandler(self, (handler, input) => Effect.provide(handler, typeof layer === \"function\" ? layer(input) : layer, options)));\n/**\n * Provides the handler of a command with the implementation of a service that\n * optionally depends on the command-line input to be constructed.\n *\n * **When to use**\n *\n * Use when a command handler needs a pure service implementation, optionally\n * derived from the parsed command input.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideSync = /*#__PURE__*/dual(3, (self, service, implementation) => mapHandler(self, (handler, input) => Effect.provideService(handler, service, typeof implementation === \"function\" ? implementation(input) : implementation)));\n/**\n * Provides the handler of a command with the service produced by an effect\n * that optionally depends on the command-line input to be created.\n *\n * **When to use**\n *\n * Use to acquire a service effectfully for each command run, optionally using\n * parsed command input.\n *\n * @see {@link provideSync} for synchronous service acquisition\n * @see {@link provide} for providing an already-available service\n * @see {@link provideEffectDiscard} for running an effect before the handler without providing a service\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideEffect = /*#__PURE__*/dual(3, (self, service, effect) => mapHandler(self, (handler, input) => Effect.provideServiceEffect(handler, service, typeof effect === \"function\" ? effect(input) : effect)));\n/**\n * Allows for execution of an effect, which optionally depends on command-line\n * input to be created, prior to executing the handler of a command.\n *\n * @category providing services\n * @since 4.0.0\n */\nexport const provideEffectDiscard = /*#__PURE__*/dual(2, (self, effect) => mapHandler(self, (handler, input) => Effect.andThen(typeof effect === \"function\" ? effect(input) : effect, handler)));\n/* ========================================================================== */\n/* Execution                                                                  */\n/* ========================================================================== */\n/**\n * Interactively constructs command-line arguments for a command.\n *\n * **Details**\n *\n * The returned arguments include the command name and can be inspected,\n * modified, or passed to another command runner by the caller.\n *\n * **Example** (Constructing command arguments)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const command = Command.make(\"app\")\n * const silentConsole: Console.Console = Object.assign(Object.create(console), {\n *   log: () => {}\n * })\n *\n * const program = Command.wizard(command).pipe(\n *   Effect.provideService(Console.Console, silentConsole),\n *   Effect.provide(CliTestLayer)\n * )\n *\n * await Effect.runPromise(program) // => [\"app\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const wizard = (command, options) => Wizard.run(command, options);\nconst getOutOfScopeGlobalFlagErrors = (allFlags, activeFlags, flagMap, commandPath) => {\n  const activeSet = new Set(activeFlags);\n  const errors = [];\n  const seen = new Set();\n  for (const flag of allFlags) {\n    if (activeSet.has(flag)) {\n      continue;\n    }\n    const singles = Param.extractSingleParams(flag.flag);\n    for (const single of singles) {\n      const entries = flagMap[single.name];\n      if (!entries || entries.length === 0) {\n        continue;\n      }\n      const option = `--${single.name}`;\n      if (seen.has(option)) {\n        continue;\n      }\n      seen.add(option);\n      errors.push(new CliError.UnrecognizedOption({\n        option,\n        suggestions: [],\n        command: commandPath\n      }));\n    }\n  }\n  return errors;\n};\nconst showHelp = (command, error) => Effect.gen(function* () {\n  const {\n    builtIns\n  } = yield* CliConfig.CliConfig;\n  const formatter = yield* CliOutput.Formatter;\n  const helpDoc = yield* getHelpForCommandPath(command, error.commandPath, builtIns);\n  yield* Console.log(formatter.formatHelpDoc(helpDoc));\n  if (error.errors.length > 0) {\n    yield* Console.error(formatter.formatErrors(error.errors));\n  }\n});\n/**\n * Runs a command using the arguments supplied by the `Stdio` service.\n *\n * **When to use**\n *\n * Use when command-line arguments should come from `Stdio` at the application\n * entry point.\n *\n * **Example** (Running commands with standard input)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({\n *     args: Effect.succeed([\"--name\", \"Alice\"])\n *   }),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const output: Array<string> = []\n * const greetCommand = Command.make(\"greet\", {\n *   name: Flag.string(\"name\")\n * }, (config) =>\n *   Effect.gen(function*() {\n *     yield* Effect.sync(() => output.push(`Hello, ${config.name}!`))\n *   }))\n *\n * // Automatically gets args from the Stdio service\n * const program = Command.run(greetCommand, {\n *   version: \"1.0.0\"\n * })\n *\n * await Effect.runPromise(program.pipe(Effect.provide(CliTestLayer)))\n * output // => [\"Hello, Alice!\"]\n * ```\n *\n * @see {@link runWith} for running a command with an explicit argument array\n *\n * @category running\n * @since 4.0.0\n */\nexport const run = /*#__PURE__*/dual(2, (command, config) => Stdio.Stdio.use(({\n  args\n}) => Effect.flatMap(args, args => runWith(command, config)(args))));\n/**\n * Runs a command with explicitly provided arguments instead of using arguments from `Stdio`.\n *\n * **When to use**\n *\n * Use when you need to test CLI applications or programmatically execute\n * commands with specific arguments.\n *\n * **Example** (Running commands with explicit arguments)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Layer, Path, Stdio, Terminal } from \"effect\"\n * import { Command, Flag } from \"effect/unstable/cli\"\n * import { ChildProcessSpawner } from \"effect/unstable/process\"\n *\n * const CliTestLayer = Layer.mergeAll(\n *   FileSystem.layerNoop({}),\n *   Path.layer,\n *   Stdio.layerTest({}),\n *   Layer.succeed(Terminal.Terminal, Terminal.make({\n *     columns: Effect.succeed(80),\n *     rows: Effect.succeed(24),\n *     readInput: Effect.die(\"unused\"),\n *     readLine: Effect.die(\"unused\"),\n *     display: () => Effect.void\n *   })),\n *   Layer.succeed(\n *     ChildProcessSpawner.ChildProcessSpawner,\n *     ChildProcessSpawner.make(() => Effect.die(\"unused\"))\n *   )\n * )\n *\n * const output: Array<string> = []\n * const greet = Command.make(\"greet\", {\n *   name: Flag.string(\"name\"),\n *   count: Flag.integer(\"count\").pipe(Flag.withDefault(1))\n * }, (config) =>\n *   Effect.gen(function*() {\n *     for (let i = 0; i < config.count; i++) {\n *       yield* Effect.sync(() => output.push(`Hello, ${config.name}!`))\n *     }\n *   }))\n *\n * // Test with specific arguments\n * const testProgram = Effect.gen(function*() {\n *   const runCommand = Command.runWith(greet, { version: \"1.0.0\" })\n *\n *   yield* runCommand([\"--name\", \"Alice\", \"--count\", \"2\"])\n * })\n *\n * await Effect.runPromise(testProgram.pipe(Effect.provide(CliTestLayer)))\n * output // => [\"Hello, Alice!\", \"Hello, Alice!\"]\n * ```\n *\n * @category running\n * @since 4.0.0\n */\nexport const runWith = (command, config) => {\n  const commandImpl = toImpl(command);\n  return Effect.fnUntraced(function* (args) {\n    const {\n      builtIns\n    } = yield* CliConfig.CliConfig;\n    const {\n      tokens,\n      trailingOperands\n    } = Lexer.lex(args);\n    // 1. Collect known global flags from the command tree\n    const allFlags = getGlobalFlagsForCommandTree(command, builtIns);\n    // 2. Extract global flag tokens\n    const allFlagParams = allFlags.flatMap(f => Param.extractSingleParams(f.flag));\n    const globalRegistry = Parser.createFlagRegistry(allFlagParams.filter(Param.isFlagParam));\n    const {\n      flagMap,\n      remainder,\n      errors: globalFlagErrors\n    } = Parser.consumeGlobalFlags(tokens, command, globalRegistry);\n    const emptyArgs = {\n      flags: flagMap,\n      arguments: []\n    };\n    // 3. Parse command arguments from remaining tokens\n    const parsedArgs = yield* Parser.parseArgs({\n      tokens: remainder,\n      trailingOperands\n    }, command);\n    const commandPath = [command.name, ...Parser.getCommandPath(parsedArgs)];\n    const handlerCtx = {\n      builtIns,\n      command,\n      commandPath,\n      version: config.version\n    };\n    const activeFlags = getGlobalFlagsForCommandPath(command, commandPath, builtIns);\n    // 4. Reject globals that were passed outside the active command scope\n    const outOfScopeErrors = getOutOfScopeGlobalFlagErrors(allFlags, activeFlags, flagMap, commandPath);\n    if (outOfScopeErrors.length > 0 || globalFlagErrors.length > 0) {\n      const parseErrors = parsedArgs.errors ?? [];\n      return yield* new CliError.ShowHelp({\n        commandPath,\n        errors: [...globalFlagErrors, ...outOfScopeErrors, ...parseErrors]\n      });\n    }\n    // 5. Process action flags — first present action wins, then exit\n    for (const flag of activeFlags) {\n      if (flag._tag !== \"Action\") continue;\n      const singles = Param.extractSingleParams(flag.flag);\n      const hasEntry = singles.some(s => {\n        const entries = flagMap[s.name];\n        return entries !== undefined && entries.length > 0;\n      });\n      if (!hasEntry) continue;\n      const [, value] = yield* flag.flag.parse(emptyArgs);\n      if (flag === GlobalFlag.Wizard) {\n        return yield* Effect.gen(function* () {\n          yield* Console.log(Wizard.renderIntroduction(command.name, config.version, command.description));\n          const prefix = [command.name, ...args.filter(arg => arg !== \"--wizard\" && !arg.startsWith(\"--wizard=\"))];\n          const wizardArgs = yield* Wizard.run(command, {\n            commandPath,\n            prefix\n          });\n          yield* Console.log(Wizard.renderCompletion(wizardArgs));\n          const shouldRun = yield* Prompt.run(Prompt.toggle({\n            message: \"Run this command?\",\n            initial: true,\n            active: \"yes\",\n            inactive: \"no\"\n          }));\n          if (shouldRun) {\n            yield* Console.log();\n            yield* runWith(command, config)(wizardArgs.slice(1));\n          }\n        }).pipe(Effect.catchTag(\"QuitError\", () => Console.log(Wizard.renderQuit())));\n      }\n      yield* flag.run(value, handlerCtx);\n      return;\n    }\n    // 6. Handle parsing errors\n    if (parsedArgs.errors && parsedArgs.errors.length > 0) {\n      return yield* new CliError.ShowHelp({\n        commandPath,\n        errors: parsedArgs.errors\n      });\n    }\n    const parseResult = yield* Effect.result(commandImpl.parse(parsedArgs));\n    if (parseResult._tag === \"Failure\") {\n      return yield* new CliError.ShowHelp({\n        commandPath,\n        errors: [parseResult.failure]\n      });\n    }\n    // 7. Provide setting values\n    let program = commandImpl.handle(parseResult.success, [command.name]);\n    const logLevel = activeFlags.includes(GlobalFlag.LogLevel) ? (yield* GlobalFlag.LogLevel.flag.parse(emptyArgs))[1] : Option.none();\n    program = Effect.provideService(program, GlobalFlag.LogLevel, logLevel);\n    for (const flag of activeFlags) {\n      if (flag._tag !== \"Setting\" || flag === GlobalFlag.LogLevel) continue;\n      const [, value] = yield* flag.flag.parse(emptyArgs);\n      program = Effect.provideService(program, flag, value);\n    }\n    // 8. Apply built-in setting behavior\n    const services = Option.match(logLevel, {\n      onNone: () => Context.empty(),\n      onSome: level => Context.make(References.MinimumLogLevel, level)\n    });\n    // 9. Run command handler with composed context\n    yield* Effect.provideContext(program, services);\n  }, Effect.catchFilter(error => CliError.isCliError(error) && error._tag === \"ShowHelp\" ? Result.succeed(error) : Result.fail(error), error => Effect.andThen(showHelp(command, error), Effect.fail(error))), Effect.catchFilter(e => Terminal.isQuitError(e) ? Result.succeed(e) : Result.fail(e), _ => Effect.interrupt));\n};\n//# sourceMappingURL=Command.js.map","import * as NodeNet from \"node:net\";\n\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Context from \"effect/Context\";\nimport * as Predicate from \"effect/Predicate\";\n\nexport class NetError extends Data.TaggedError(\"NetError\")<{\n  readonly message: string;\n  readonly cause?: unknown;\n}> {}\n\nconst isErrnoExceptionWithCode = (\n  cause: unknown,\n): cause is {\n  readonly code: string;\n} =>\n  Predicate.isObject(cause) &&\n  Predicate.hasProperty(cause, \"code\") &&\n  Predicate.isString(cause.code);\n\nconst closeServer = (server: NodeNet.Server) => {\n  try {\n    server.close();\n  } catch {\n    // Ignore close failures during cleanup.\n  }\n};\n\nexport interface NetServiceShape {\n  /**\n   * Returns true when a TCP server can bind to {host, port}.\n   */\n  readonly canListenOnHost: (port: number, host: string) => Effect.Effect<boolean>;\n\n  /**\n   * Checks loopback availability on both IPv4 and IPv6 localhost addresses.\n   */\n  readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;\n\n  /**\n   * Reserve an ephemeral loopback port and release it immediately.\n   */\n  readonly reserveLoopbackPort: (host?: string) => Effect.Effect<number, NetError>;\n\n  /**\n   * Resolve an available listening port, preferring the provided port first.\n   */\n  readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;\n}\n\n/**\n * NetService - Service tag for startup networking helpers.\n */\nexport class NetService extends Context.Service<NetService, NetServiceShape>()(\n  \"@t3tools/shared/Net/NetService\",\n) {}\n\nexport const make = () => {\n  /**\n   * Returns true when a TCP server can bind to {host, port}.\n   * `EADDRNOTAVAIL` is treated as available so IPv6-absent hosts don't fail\n   * loopback availability checks.\n   */\n  const canListenOnHost = (port: number, host: string): Effect.Effect<boolean> =>\n    Effect.callback<boolean>((resume) => {\n      const server = NodeNet.createServer();\n      let settled = false;\n\n      const settle = (value: boolean) => {\n        if (settled) return;\n        settled = true;\n        resume(Effect.succeed(value));\n      };\n\n      server.unref();\n\n      server.once(\"error\", (cause) => {\n        if (isErrnoExceptionWithCode(cause) && cause.code === \"EADDRNOTAVAIL\") {\n          settle(true);\n          return;\n        }\n        settle(false);\n      });\n\n      server.once(\"listening\", () => {\n        server.close(() => {\n          settle(true);\n        });\n      });\n\n      server.listen({ host, port });\n\n      return Effect.sync(() => {\n        closeServer(server);\n      });\n    });\n\n  const hasListenerOnHost = (port: number, host: string): Effect.Effect<boolean> =>\n    Effect.callback<boolean>((resume) => {\n      const socket = NodeNet.createConnection({ host, port });\n      let settled = false;\n\n      const settle = (value: boolean) => {\n        if (settled) return;\n        settled = true;\n        socket.destroy();\n        resume(Effect.succeed(value));\n      };\n\n      socket.unref();\n      socket.setTimeout(250);\n      socket.once(\"connect\", () => {\n        settle(true);\n      });\n      socket.once(\"error\", () => {\n        settle(false);\n      });\n      socket.once(\"timeout\", () => {\n        settle(false);\n      });\n\n      return Effect.sync(() => {\n        socket.destroy();\n      });\n    });\n\n  const isPortAvailableOnLoopback = (port: number): Effect.Effect<boolean> =>\n    Effect.gen(function* () {\n      const hasListener = yield* Effect.zipWith(\n        hasListenerOnHost(port, \"127.0.0.1\"),\n        hasListenerOnHost(port, \"::1\"),\n        (ipv4, ipv6) => ipv4 || ipv6,\n      );\n      if (hasListener) {\n        return false;\n      }\n\n      return yield* Effect.zipWith(\n        canListenOnHost(port, \"127.0.0.1\"),\n        canListenOnHost(port, \"::1\"),\n        (ipv4, ipv6) => ipv4 && ipv6,\n      );\n    });\n\n  /**\n   * Reserve an ephemeral loopback port and release it immediately.\n   * Returns the reserved port number.\n   */\n  const reserveLoopbackPort = (host = \"127.0.0.1\"): Effect.Effect<number, NetError> =>\n    Effect.callback<number, NetError>((resume) => {\n      const probe = NodeNet.createServer();\n      let settled = false;\n\n      const settle = (effect: Effect.Effect<number, NetError>) => {\n        if (settled) return;\n        settled = true;\n        resume(effect);\n      };\n\n      probe.once(\"error\", (cause) => {\n        settle(Effect.fail(new NetError({ message: \"Failed to reserve loopback port\", cause })));\n      });\n\n      probe.listen(0, host, () => {\n        const address = probe.address();\n        const port = typeof address === \"object\" && address !== null ? address.port : 0;\n        probe.close(() => {\n          if (port > 0) {\n            settle(Effect.succeed(port));\n            return;\n          }\n          settle(Effect.fail(new NetError({ message: \"Failed to reserve loopback port\" })));\n        });\n      });\n\n      return Effect.sync(() => {\n        closeServer(probe);\n      });\n    });\n\n  return {\n    canListenOnHost,\n    isPortAvailableOnLoopback,\n    reserveLoopbackPort,\n    findAvailablePort: (preferred) =>\n      Effect.gen(function* () {\n        if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) {\n          return preferred;\n        }\n        return yield* reserveLoopbackPort();\n      }),\n  } satisfies NetServiceShape;\n};\n\nexport const layer = Layer.sync(NetService, make);\n","","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nexport const TrimmedString = Schema.String.pipe(\n  Schema.decodeTo(\n    Schema.String,\n    SchemaTransformation.transformOrFail({\n      decode: (value) => Effect.succeed(value.trim()),\n      encode: (value) => Effect.succeed(value.trim()),\n    }),\n  ),\n);\nexport const TrimmedNonEmptyString = TrimmedString.check(Schema.isNonEmpty());\n\nexport const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nexport const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nexport const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));\n\nexport const IsoDateTime = Schema.String;\nexport type IsoDateTime = typeof IsoDateTime.Type;\n\n/**\n * Wire codec for server→client arrays whose element unions grow over time\n * (new literal members, new struct variants). Decoding drops elements the\n * current build cannot decode instead of failing the whole payload — a client\n * has to keep decoding configs sent by servers newer than itself, and\n * rejecting the payload would take down the connection over data the client\n * couldn't act on anyway. Encoding is the plain array encoding.\n */\nexport const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) => {\n  const decodeElement = Schema.decodeUnknownOption(element as never);\n  return Schema.Array(Schema.Unknown).pipe(\n    Schema.decodeTo(\n      Schema.Array(element),\n      SchemaTransformation.transform<ReadonlyArray<Element[\"Encoded\"]>, ReadonlyArray<unknown>>({\n        decode: (values) =>\n          values.filter((value) => Option.isSome(decodeElement(value))) as ReadonlyArray<\n            Element[\"Encoded\"]\n          >,\n        encode: (values) => values,\n      }),\n    ),\n  );\n};\n\n/**\n * Construct a branded identifier. Enforces non-empty trimmed strings\n */\nconst makeEntityId = <Brand extends string>(brand: Brand) => {\n  return TrimmedNonEmptyString.pipe(Schema.brand(brand));\n};\n\nexport const ThreadId = makeEntityId(\"ThreadId\");\nexport type ThreadId = typeof ThreadId.Type;\nexport const ProjectId = makeEntityId(\"ProjectId\");\nexport type ProjectId = typeof ProjectId.Type;\nexport const EnvironmentId = makeEntityId(\"EnvironmentId\");\nexport type EnvironmentId = typeof EnvironmentId.Type;\nexport const CommandId = makeEntityId(\"CommandId\");\nexport type CommandId = typeof CommandId.Type;\nexport const EventId = makeEntityId(\"EventId\");\nexport type EventId = typeof EventId.Type;\nexport const MessageId = makeEntityId(\"MessageId\");\nexport type MessageId = typeof MessageId.Type;\nexport const TurnId = makeEntityId(\"TurnId\");\nexport type TurnId = typeof TurnId.Type;\nexport const AuthSessionId = makeEntityId(\"AuthSessionId\");\nexport type AuthSessionId = typeof AuthSessionId.Type;\nexport const RpcClientId = NonNegativeInt.pipe(Schema.brand(\"RpcClientId\"));\nexport type RpcClientId = typeof RpcClientId.Type;\n\nexport const ProviderItemId = makeEntityId(\"ProviderItemId\");\nexport type ProviderItemId = typeof ProviderItemId.Type;\nexport const RuntimeSessionId = makeEntityId(\"RuntimeSessionId\");\nexport type RuntimeSessionId = typeof RuntimeSessionId.Type;\nexport const RuntimeItemId = makeEntityId(\"RuntimeItemId\");\nexport type RuntimeItemId = typeof RuntimeItemId.Type;\nexport const RuntimeRequestId = makeEntityId(\"RuntimeRequestId\");\nexport type RuntimeRequestId = typeof RuntimeRequestId.Type;\nexport const RuntimeTaskId = makeEntityId(\"RuntimeTaskId\");\nexport type RuntimeTaskId = typeof RuntimeTaskId.Type;\nexport const ApprovalRequestId = makeEntityId(\"ApprovalRequestId\");\nexport type ApprovalRequestId = typeof ApprovalRequestId.Type;\nexport const CheckpointRef = makeEntityId(\"CheckpointRef\");\nexport type CheckpointRef = typeof CheckpointRef.Type;\n","/**\n * Provider-instance contracts.\n *\n * Splits the historical \"provider kind\" concept into two:\n *\n *   - `ProviderDriverKind` is the implementation kind selector (e.g. codex,\n *     claudeAgent, a fork's `ollama`, …). It picks which driver package\n *     handles the protocol, the probe, the adapter, and text generation.\n *\n *   - `ProviderInstanceId` is the routing key (a user-defined slug).\n *     Threads, sessions, runtime events, and persisted bindings reference\n *     instance ids — never driver kinds — so a user can configure multiple\n *     instances of the same driver (e.g. `codex_personal` + `codex_work`),\n *     each with independent driver-specific configuration.\n *\n * Forward/backward compatibility invariant\n * ----------------------------------------\n * `ProviderDriverKind` is intentionally an **open** branded slug, not a closed\n * literal union. The server hosts forks, ships in PRs that add drivers, and\n * users frequently roll between branches and forks. Any of those paths can\n * leave `ServerSettings`, persisted thread state, or session bindings\n * referencing a driver that the currently-running build does not know about.\n *\n * The rule: parsing any of those payloads must always succeed, and the\n * runtime is responsible for marking the unknown driver/instance as\n * \"unavailable\" rather than crashing. Built-in drivers shipped by the core\n * product happens to register in a given build is not part of the contract\n * layer. Driver availability is discovered through the runtime registry.\n *\n * Driver-specific configuration is similarly opaque at the contracts layer:\n * drivers live in (or will be extracted to) their own packages and own their\n * config schemas. The contracts package only knows the envelope.\n *\n * @module providerInstance\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst PROVIDER_SLUG_MAX_CHARS = 64;\n/**\n * Slug pattern shared by driver kinds and instance ids — letters, digits,\n * dashes, underscores. The first character must be a letter so slugs remain\n * JS-identifier friendly when used as object keys, log fields, or telemetry\n * attributes. Mixed case is permitted so historical driver kinds (e.g.\n * `claudeAgent`) can be used verbatim during the migration and so external\n * fork authors retain reasonable freedom.\n */\nconst PROVIDER_SLUG_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;\nconst ENVIRONMENT_VARIABLE_NAME_MAX_CHARS = 128;\nconst ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\nconst slugSchema = TrimmedNonEmptyString.check(\n  Schema.isMaxLength(PROVIDER_SLUG_MAX_CHARS),\n  Schema.isPattern(PROVIDER_SLUG_PATTERN),\n);\n\n/**\n * `ProviderDriverKind` — open branded slug naming a driver implementation.\n *\n * Constraints (validated at the schema layer):\n *   - starts with a letter\n *   - only letters, digits, `-`, `_` after the first char\n *   - 1..64 characters\n *\n * Notably **not** validated: that the driver is one we know how to load.\n * That check belongs to the runtime registry, which downgrades unknown\n * drivers gracefully (see module docs).\n */\nexport const ProviderDriverKind = slugSchema.pipe(Schema.brand(\"ProviderDriverKind\"));\nexport type ProviderDriverKind = typeof ProviderDriverKind.Type;\n\nconst isProviderDriverKindValue = Schema.is(ProviderDriverKind);\nexport const isProviderDriverKind = (value: unknown): value is ProviderDriverKind =>\n  isProviderDriverKindValue(value);\n\n/**\n * `ProviderInstanceId` — user-defined routing key for a configured provider\n * instance. Same slug rules as `ProviderDriverKind`; branded separately so the\n * type system cannot confuse the two.\n */\nexport const ProviderInstanceId = slugSchema.pipe(Schema.brand(\"ProviderInstanceId\"));\nexport type ProviderInstanceId = typeof ProviderInstanceId.Type;\n\n/**\n * Lightweight reference identifying which driver implements an instance.\n * Carried alongside `ProviderInstanceId` on wire shapes so consumers can\n * branch on driver behavior (icons, capabilities, presentation) without\n * having to look up the instance in the registry.\n */\nexport const ProviderInstanceRef = Schema.Struct({\n  instanceId: ProviderInstanceId,\n  driver: ProviderDriverKind,\n});\nexport type ProviderInstanceRef = typeof ProviderInstanceRef.Type;\n\nexport const ProviderInstanceEnvironmentVariableName = TrimmedNonEmptyString.check(\n  Schema.isMaxLength(ENVIRONMENT_VARIABLE_NAME_MAX_CHARS),\n  Schema.isPattern(ENVIRONMENT_VARIABLE_NAME_PATTERN),\n);\nexport type ProviderInstanceEnvironmentVariableName =\n  typeof ProviderInstanceEnvironmentVariableName.Type;\n\nexport const ProviderInstanceEnvironmentVariable = Schema.Struct({\n  name: ProviderInstanceEnvironmentVariableName,\n  value: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  sensitive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  valueRedacted: Schema.optionalKey(Schema.Boolean),\n});\nexport type ProviderInstanceEnvironmentVariable = typeof ProviderInstanceEnvironmentVariable.Type;\n\nexport const ProviderInstanceEnvironment = Schema.Array(ProviderInstanceEnvironmentVariable);\nexport type ProviderInstanceEnvironment = typeof ProviderInstanceEnvironment.Type;\n\n/**\n * Envelope shape for a provider instance configuration in `ServerSettings`.\n *\n * `driver` is intentionally accepted as any well-formed slug (see module\n * docs). The driver-specific config payload is left as `Schema.Unknown`;\n * each driver registers its own decoder with the runtime registry, and\n * envelopes for unknown drivers are preserved verbatim so they round-trip\n * across version changes without data loss.\n */\nexport const ProviderInstanceConfig = Schema.Struct({\n  driver: ProviderDriverKind,\n  displayName: Schema.optional(TrimmedNonEmptyString),\n  accentColor: Schema.optional(TrimmedNonEmptyString),\n  environment: Schema.optionalKey(ProviderInstanceEnvironment),\n  enabled: Schema.optionalKey(Schema.Boolean),\n  config: Schema.optionalKey(Schema.Unknown),\n});\nexport type ProviderInstanceConfig = typeof ProviderInstanceConfig.Type;\n\n/**\n * Map shape for `ServerSettings.providerInstances`. Keyed by\n * `ProviderInstanceId`, values are envelopes the registry feeds to drivers.\n */\nexport const ProviderInstanceConfigMap = Schema.Record(ProviderInstanceId, ProviderInstanceConfig);\nexport type ProviderInstanceConfigMap = typeof ProviderInstanceConfigMap.Type;\n\n/**\n * Construct the canonical `ProviderInstanceId` used as a back-compat default\n * for a built-in driver. The legacy single-instance-per-driver world used\n * the driver kind itself as the instance id; preserving that mapping keeps\n * existing persisted threads, bindings, and cache files routable across the\n * migration without rewriting their stored selection payloads.\n */\nexport const defaultInstanceIdForDriver = (driver: ProviderDriverKind): ProviderInstanceId =>\n  ProviderInstanceId.make(driver);\n","import * as Schema from \"effect/Schema\";\n\nimport {\n  AuthSessionId,\n  EnvironmentId,\n  RpcClientId,\n  ThreadId,\n  TrimmedNonEmptyString,\n} from \"./baseSchemas.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\n\nexport const BackgroundBooleanState = Schema.Literals([\"true\", \"false\", \"unknown\"]);\nexport type BackgroundBooleanState = typeof BackgroundBooleanState.Type;\n\nexport const HostPowerThermalState = Schema.Literals([\n  \"unknown\",\n  \"nominal\",\n  \"fair\",\n  \"serious\",\n  \"critical\",\n]);\nexport type HostPowerThermalState = typeof HostPowerThermalState.Type;\n\nexport const HostPowerSource = Schema.Literals([\n  \"unknown\",\n  \"node-macos-shell\",\n  \"node-macos-native\",\n  \"node-linux\",\n  \"node-windows\",\n  \"electron-main\",\n]);\nexport type HostPowerSource = typeof HostPowerSource.Type;\n\nexport const HostPowerSnapshot = Schema.Struct({\n  source: HostPowerSource,\n  idle: BackgroundBooleanState,\n  idleSeconds: Schema.NullOr(Schema.Number),\n  locked: BackgroundBooleanState,\n  suspended: Schema.Boolean,\n  onBattery: BackgroundBooleanState,\n  lowPowerMode: BackgroundBooleanState,\n  thermalState: HostPowerThermalState,\n  stale: Schema.Boolean,\n  updatedAt: Schema.DateTimeUtc,\n});\nexport type HostPowerSnapshot = typeof HostPowerSnapshot.Type;\n\nexport const BackgroundScope = Schema.Union([\n  Schema.Struct({ type: Schema.Literal(\"server-config\") }),\n  Schema.Struct({\n    type: Schema.Literal(\"provider-status\"),\n    instanceId: Schema.optionalKey(ProviderInstanceId),\n  }),\n  Schema.Struct({ type: Schema.Literal(\"vcs-status\"), cwd: Schema.String }),\n  Schema.Struct({ type: Schema.Literal(\"git-refs\"), cwd: Schema.String }),\n  Schema.Struct({ type: Schema.Literal(\"diagnostics\") }),\n  Schema.Struct({ type: Schema.Literal(\"thread\"), threadId: ThreadId }),\n]);\nexport type BackgroundScope = typeof BackgroundScope.Type;\n\nexport const ClientKind = Schema.Literals([\"web\", \"desktop-renderer\", \"mobile\", \"unknown\"]);\nexport type ClientKind = typeof ClientKind.Type;\n\nexport const ClientActivityClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));\nexport type ClientActivityClientId = typeof ClientActivityClientId.Type;\n\nexport const ClientActivityReportInput = Schema.Struct({\n  environmentId: Schema.optionalKey(EnvironmentId),\n  clientId: ClientActivityClientId,\n  clientKind: ClientKind,\n  visible: Schema.Boolean,\n  focused: Schema.Boolean,\n  recentlyInteracted: Schema.Boolean,\n  appState: Schema.optionalKey(Schema.Literals([\"active\", \"inactive\", \"background\", \"unknown\"])),\n  lowPowerMode: Schema.optionalKey(BackgroundBooleanState),\n  batteryState: Schema.optionalKey(Schema.Literals([\"unknown\", \"unplugged\", \"charging\", \"full\"])),\n  networkType: Schema.optionalKey(Schema.String),\n  scopes: Schema.Array(BackgroundScope),\n  ttlMs: Schema.optionalKey(Schema.Number),\n  observedAt: Schema.DateTimeUtc,\n});\nexport type ClientActivityReportInput = typeof ClientActivityReportInput.Type;\n\nexport const ClientActivityLease = Schema.Struct({\n  sessionId: AuthSessionId,\n  rpcClientId: RpcClientId,\n  clientId: ClientActivityClientId,\n  clientKind: ClientKind,\n  visible: Schema.Boolean,\n  focused: Schema.Boolean,\n  recentlyInteracted: Schema.Boolean,\n  appState: Schema.optionalKey(Schema.Literals([\"active\", \"inactive\", \"background\", \"unknown\"])),\n  lowPowerMode: Schema.optionalKey(BackgroundBooleanState),\n  batteryState: Schema.optionalKey(Schema.Literals([\"unknown\", \"unplugged\", \"charging\", \"full\"])),\n  networkType: Schema.optionalKey(Schema.String),\n  scopes: Schema.Array(BackgroundScope),\n  updatedAt: Schema.DateTimeUtc,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type ClientActivityLease = typeof ClientActivityLease.Type;\n\nexport const BackgroundPolicySnapshot = Schema.Struct({\n  hostPower: HostPowerSnapshot,\n  leases: Schema.Array(ClientActivityLease),\n  activeForegroundLeaseCount: Schema.Number,\n  activeScopeKeys: Schema.Array(Schema.String),\n  shouldRunOpportunisticWork: Schema.Boolean,\n  updatedAt: Schema.DateTimeUtc,\n});\nexport type BackgroundPolicySnapshot = typeof BackgroundPolicySnapshot.Type;\n","/**\n * Attaches HTTP API metadata to Effect Schema values.\n *\n * This module is the schema-side bridge for HttpApi endpoint builders,\n * generated clients, and OpenAPI support. It does not define routes or perform\n * IO. Instead, the helpers annotate schemas so the surrounding HTTP API tooling\n * can choose response status codes, content types, body codecs, multipart\n * handling, and no-body response behavior.\n *\n * @since 4.0.0\n */\nimport { constVoid } from \"../../Function.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nimport * as Stream from \"../../Stream.js\";\nimport { hasBody } from \"../http/HttpMethod.js\";\nconst statusCodeByLiteral = {\n  Continue: 100,\n  SwitchingProtocols: 101,\n  Processing: 102,\n  EarlyHints: 103,\n  OK: 200,\n  Ok: 200,\n  Created: 201,\n  Accepted: 202,\n  NonAuthoritativeInformation: 203,\n  NoContent: 204,\n  ResetContent: 205,\n  PartialContent: 206,\n  MultiStatus: 207,\n  AlreadyReported: 208,\n  ImUsed: 226,\n  MultipleChoices: 300,\n  MovedPermanently: 301,\n  Found: 302,\n  SeeOther: 303,\n  NotModified: 304,\n  TemporaryRedirect: 307,\n  PermanentRedirect: 308,\n  BadRequest: 400,\n  Unauthorized: 401,\n  PaymentRequired: 402,\n  Forbidden: 403,\n  NotFound: 404,\n  MethodNotAllowed: 405,\n  NotAcceptable: 406,\n  ProxyAuthenticationRequired: 407,\n  RequestTimeout: 408,\n  Conflict: 409,\n  Gone: 410,\n  LengthRequired: 411,\n  PreconditionFailed: 412,\n  PayloadTooLarge: 413,\n  UriTooLong: 414,\n  UnsupportedMediaType: 415,\n  RangeNotSatisfiable: 416,\n  ExpectationFailed: 417,\n  ImATeapot: 418,\n  MisdirectedRequest: 421,\n  UnprocessableEntity: 422,\n  Locked: 423,\n  FailedDependency: 424,\n  TooEarly: 425,\n  UpgradeRequired: 426,\n  PreconditionRequired: 428,\n  TooManyRequests: 429,\n  RequestHeaderFieldsTooLarge: 431,\n  UnavailableForLegalReasons: 451,\n  InternalServerError: 500,\n  NotImplemented: 501,\n  BadGateway: 502,\n  ServiceUnavailable: 503,\n  GatewayTimeout: 504,\n  HttpVersionNotSupported: 505,\n  VariantAlsoNegotiates: 506,\n  InsufficientStorage: 507,\n  LoopDetected: 508,\n  NotExtended: 510,\n  NetworkAuthenticationRequired: 511\n};\nconst StreamSchemaTypeId = \"~effect/httpapi/HttpApiSchema/Stream\";\nexport function status(code) {\n  const statusCode = typeof code === \"string\" ? statusCodeByLiteral[code] : code;\n  return self => self.annotate({\n    httpApiStatus: statusCode\n  });\n}\n/**\n * Creates a void schema with the given HTTP status code.\n * This is used to represent empty responses with a specific status code.\n *\n * @see {@link NoContent} for the predefined 204 no content schema.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Empty = code => Schema.Void.pipe(status(code));\n/**\n * Schema for empty HTTP responses with status code 204.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const NoContent = /*#__PURE__*/Empty(204);\n/**\n * Schema for empty HTTP responses with status code 201.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Created = /*#__PURE__*/Empty(201);\n/**\n * Schema for empty HTTP responses with status code 202.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Accepted = /*#__PURE__*/Empty(202);\n/**\n * Marks a schema as a no-content response while preserving a decoded client value.\n *\n * **Details**\n *\n * The server encodes the response as `void`; generated clients call `decode` to\n * produce the schema's decoded value when the response has no body.\n *\n * @see {@link NoContent} for a void schema with the status code 204.\n * @see {@link Empty} for creating a void schema with a specific status code.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asNoContent(options) {\n  return self => {\n    return Schema.Void.pipe(Schema.decodeTo(Schema.toType(self), SchemaTransformation.transform({\n      decode: options.decode,\n      encode: constVoid\n    })));\n  };\n}\nconst streamSchema = /*#__PURE__*/Schema.declare(Stream.isStream);\n/**\n * Creates a Server-Sent Events streaming success response schema.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const StreamSse = options => {\n  const events = options.events ?? (options.data === undefined ? undefined : Schema.Struct({\n    id: Schema.UndefinedOr(Schema.String),\n    event: Schema.String,\n    data: Schema.fromJsonString(options.data)\n  }));\n  if (events === undefined) {\n    throw new Error(\"StreamSse requires either an events schema or a data schema\");\n  }\n  return Schema.make(streamSchema.ast, {\n    [StreamSchemaTypeId]: StreamSchemaTypeId,\n    _tag: \"StreamSse\",\n    mode: \"sse\",\n    sseMode: options.events === undefined ? \"data\" : \"events\",\n    contentType: options.contentType ?? defaultStreamContentType(\"sse\"),\n    events,\n    error: options.error ?? Schema.Never\n  });\n};\n/**\n * Creates a streaming `Uint8Array` success response schema.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const StreamUint8Array = options => Schema.make(streamSchema.ast, {\n  [StreamSchemaTypeId]: StreamSchemaTypeId,\n  _tag: \"StreamUint8Array\",\n  mode: \"uint8array\",\n  contentType: options?.contentType ?? defaultStreamContentType(\"uint8array\")\n});\n/** @internal */\nexport const isStreamSchema = u => Schema.isSchema(u) && Predicate.hasProperty(u, StreamSchemaTypeId);\n/** @internal */\nexport const isStreamSse = u => isStreamSchema(u) && u._tag === \"StreamSse\";\n/** @internal */\nexport const isStreamUint8Array = u => isStreamSchema(u) && u._tag === \"StreamUint8Array\";\nfunction defaultStreamContentType(mode) {\n  switch (mode) {\n    case \"sse\":\n      return \"text/event-stream\";\n    case \"uint8array\":\n      return \"application/octet-stream\";\n  }\n}\n/**\n * Runtime brand key used to mark schemas as buffered multipart payloads.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const MultipartTypeId = \"~effect/httpapi/HttpApiSchema/Multipart\";\n/**\n * Marks a schema as a multipart payload.\n *\n * @see {@link asMultipartStream} for a multipart stream payload.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asMultipart(options) {\n  return self => self.pipe(Schema.brand(MultipartTypeId)).annotate({\n    \"~httpApiEncoding\": {\n      _tag: \"Multipart\",\n      mode: \"buffered\",\n      contentType: defaultContentType(\"Multipart\"),\n      limits: options\n    }\n  });\n}\n/**\n * Runtime brand key used to mark schemas as streaming multipart payloads.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const MultipartStreamTypeId = \"~effect/httpapi/HttpApiSchema/MultipartStream\";\n/**\n * Marks a schema as a multipart stream payload.\n *\n * @see {@link asMultipart} for a buffered multipart payload.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asMultipartStream(options) {\n  return self => self.pipe(Schema.brand(MultipartStreamTypeId)).annotate({\n    \"~httpApiEncoding\": {\n      _tag: \"Multipart\",\n      mode: \"stream\",\n      contentType: defaultContentType(\"Multipart\"),\n      limits: options\n    }\n  });\n}\nfunction asNonMultipartEncoding(self, options) {\n  return self.annotate({\n    \"~httpApiEncoding\": {\n      _tag: options._tag,\n      contentType: options.contentType ?? defaultContentType(options._tag)\n    }\n  });\n}\nfunction defaultContentType(_tag) {\n  switch (_tag) {\n    case \"Multipart\":\n      return \"multipart/form-data\";\n    case \"Json\":\n      return \"application/json\";\n    case \"FormUrlEncoded\":\n      return \"application/x-www-form-urlencoded\";\n    case \"Uint8Array\":\n      return \"application/octet-stream\";\n    case \"Text\":\n      return \"text/plain\";\n  }\n}\n/**\n * Marks a schema as a JSON payload / response.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asJson(options) {\n  return self => asNonMultipartEncoding(self, {\n    _tag: \"Json\",\n    ...options\n  });\n}\n/**\n * Marks a schema as an `application/x-www-form-urlencoded` payload or response.\n *\n * **Details**\n *\n * The schema's encoded side must be a record of strings.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asFormUrlEncoded(options) {\n  return self => asNonMultipartEncoding(self, {\n    _tag: \"FormUrlEncoded\",\n    ...options\n  });\n}\n/**\n * Marks a schema as a text payload / response.\n *\n * **Details**\n *\n * The schema encoded side must be a string.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asText(options) {\n  return self => asNonMultipartEncoding(self, {\n    _tag: \"Text\",\n    ...options\n  });\n}\n/**\n * Marks a schema as a binary payload / response.\n *\n * **Details**\n *\n * The schema encoded side must be a `Uint8Array`.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport function asUint8Array(options) {\n  return self => asNonMultipartEncoding(self, {\n    _tag: \"Uint8Array\",\n    ...options\n  });\n}\n/**\n * Returns `true` when a schema AST represents a no-content response.\n *\n * **Details**\n *\n * The check succeeds for direct `void` schemas and schemas whose encoded or\n * transformation target is `void`.\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isNoContent = ast => {\n  if (SchemaAST.isVoid(ast)) return true;\n  const encoded = SchemaAST.toEncoded(ast);\n  if (SchemaAST.isVoid(encoded)) return true;\n  const target = ast.encoding?.[0].to;\n  if (target === undefined) return false;\n  return SchemaAST.isVoid(target);\n};\nconst resolveHttpApiEncoding = /*#__PURE__*/SchemaAST.resolveAt(\"~httpApiEncoding\");\nconst resolveHttpApiStatus = /*#__PURE__*/SchemaAST.resolveAt(\"httpApiStatus\");\nconst defaultJsonEncoding = {\n  _tag: \"Json\",\n  contentType: \"application/json\"\n};\nconst defaultUrlEncodedEncoding = {\n  _tag: \"FormUrlEncoded\",\n  contentType: \"application/x-www-form-urlencoded\"\n};\nfunction getEncoding(ast) {\n  return resolveHttpApiEncoding(ast) ?? defaultJsonEncoding;\n}\n/** @internal */\nexport function getPayloadEncoding(ast, method) {\n  const encoding = resolveHttpApiEncoding(ast);\n  if (encoding) return encoding;\n  return hasBody(method) ? defaultJsonEncoding : defaultUrlEncodedEncoding;\n}\n/** @internal */\nexport function getResponseEncoding(ast) {\n  const out = getEncoding(ast);\n  if (out._tag === \"Multipart\") {\n    throw new Error(\"Multipart is not supported in response\");\n  }\n  return out;\n}\n/** @internal */\nexport function getStatusSuccess(self) {\n  return resolveHttpApiStatus(self) ?? 200;\n}\n/** @internal */\nexport function getStatusStream(self) {\n  return getStatusSuccess(self.ast);\n}\n/** @internal */\nexport function getStatusError(self) {\n  return resolveHttpApiStatus(self) ?? 500;\n}\n//# sourceMappingURL=HttpApiSchema.js.map","import * as Schema from \"effect/Schema\";\nimport * as HttpApiSchema from \"effect/unstable/httpapi/HttpApiSchema\";\n\nimport { AuthSessionId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\n/**\n * Declares the server's overall authentication posture.\n *\n * This is a high-level policy label that tells clients how the environment is\n * expected to be accessed, not a transport detail and not an exhaustive list\n * of every accepted credential.\n *\n * Typical usage:\n * - rendered in auth/pairing UI so the user understands what kind of\n *   environment they are connecting to\n * - used by clients to decide whether silent desktop bootstrap is expected or\n *   whether an explicit pairing flow should be shown\n *\n * Meanings:\n * - `desktop-managed-local`: local desktop-managed environment with narrow\n *   trusted bootstrap, intended to avoid login prompts on the same machine\n * - `loopback-browser`: standalone local server intended for browser pairing on\n *   the same machine\n * - `remote-reachable`: environment intended to be reached from other devices\n *   or networks, where explicit pairing/auth is expected\n * - `unsafe-no-auth`: intentionally unauthenticated mode; this is an explicit\n *   unsafe escape hatch, not a normal deployment mode\n */\nexport const ServerAuthPolicy = Schema.Literals([\n  \"desktop-managed-local\",\n  \"loopback-browser\",\n  \"remote-reachable\",\n  \"unsafe-no-auth\",\n]);\nexport type ServerAuthPolicy = typeof ServerAuthPolicy.Type;\n\n/**\n * A credential type that can be exchanged for a real authenticated session.\n *\n * Bootstrap methods are for establishing trust at the start of a connection or\n * pairing flow. They are not the long-lived credential used for ordinary\n * authenticated HTTP / WebSocket traffic after pairing succeeds.\n *\n * Current methods:\n * - `desktop-bootstrap`: a trusted local desktop handoff, used so the desktop\n *   shell can pair the renderer without a login screen\n * - `one-time-token`: a short-lived pairing token, suitable for manual pairing\n *   flows such as `/pair?token=...`\n */\nexport const ServerAuthBootstrapMethod = Schema.Literals([\"desktop-bootstrap\", \"one-time-token\"]);\nexport type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;\n\n/**\n * A credential type accepted for steady-state authenticated requests after a\n * client has already paired.\n *\n * These methods are used by the server-wide auth layer for privileged HTTP and\n * WebSocket access. They are distinct from bootstrap methods so clients can\n * reason clearly about \"pair first, then use session auth\".\n *\n * Current methods:\n * - `browser-session-cookie`: cookie-backed browser session, used by the web\n *   app after bootstrap/pairing\n * - `bearer-access-token`: scoped token suitable for non-cookie or\n *   non-browser clients\n * - `dpop-access-token`: scoped proof-of-possession token used by managed\n *   relay connections\n */\nexport const ServerAuthSessionMethod = Schema.Literals([\n  \"browser-session-cookie\",\n  \"bearer-access-token\",\n  \"dpop-access-token\",\n]);\nexport type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;\n\nexport const AuthOrchestrationReadScope = \"orchestration:read\" as const;\nexport const AuthOrchestrationOperateScope = \"orchestration:operate\" as const;\nexport const AuthTerminalOperateScope = \"terminal:operate\" as const;\nexport const AuthReviewWriteScope = \"review:write\" as const;\nexport const AuthAccessReadScope = \"access:read\" as const;\nexport const AuthAccessWriteScope = \"access:write\" as const;\nexport const AuthRelayReadScope = \"relay:read\" as const;\nexport const AuthRelayWriteScope = \"relay:write\" as const;\nexport const AuthPortProxyOperateScope = \"port-proxy:operate\" as const;\nexport const AuthEnvironmentScope = Schema.Literals([\n  AuthOrchestrationReadScope,\n  AuthOrchestrationOperateScope,\n  AuthTerminalOperateScope,\n  AuthReviewWriteScope,\n  AuthAccessReadScope,\n  AuthAccessWriteScope,\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n  AuthPortProxyOperateScope,\n]);\nexport type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;\nexport const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);\nexport type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;\n\nexport const AuthStandardClientScopes = [\n  AuthOrchestrationReadScope,\n  AuthOrchestrationOperateScope,\n  AuthTerminalOperateScope,\n  AuthReviewWriteScope,\n  AuthRelayReadScope,\n  AuthPortProxyOperateScope,\n] as const;\nexport const AuthAdministrativeScopes = [\n  ...AuthStandardClientScopes,\n  AuthAccessReadScope,\n  AuthAccessWriteScope,\n  AuthRelayWriteScope,\n] as const;\n\nexport const AuthTokenExchangeGrantType =\n  \"urn:ietf:params:oauth:grant-type:token-exchange\" as const;\nexport const AuthAccessTokenType = \"urn:ietf:params:oauth:token-type:access_token\" as const;\nexport const AuthEnvironmentBootstrapTokenType =\n  \"urn:t3:params:oauth:token-type:environment-bootstrap\" as const;\n\n/**\n * Server-advertised auth capabilities for a specific execution environment.\n *\n * Clients should treat this as the authoritative description of how that\n * environment expects to be paired and how authenticated requests should be\n * made afterward.\n *\n * Field meanings:\n * - `policy`: high-level auth posture for the environment\n * - `bootstrapMethods`: pairing/bootstrap methods the server is currently\n *   willing to accept\n * - `sessionMethods`: authenticated request/session methods the server supports\n *   once pairing is complete\n * - `sessionCookieName`: cookie name clients should expect when\n *   `browser-session-cookie` is in use\n *\n * This descriptor is intentionally capability-oriented. It lets clients choose\n * the right UX without embedding server-specific auth logic or assuming a\n * single access method.\n */\nexport const ServerAuthDescriptor = Schema.Struct({\n  policy: ServerAuthPolicy,\n  bootstrapMethods: Schema.Array(ServerAuthBootstrapMethod),\n  sessionMethods: Schema.Array(ServerAuthSessionMethod),\n  sessionCookieName: TrimmedNonEmptyString,\n});\nexport type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;\n\nexport const AuthBrowserSessionRequest = Schema.Struct({\n  credential: TrimmedNonEmptyString,\n});\nexport type AuthBrowserSessionRequest = typeof AuthBrowserSessionRequest.Type;\n\nexport const AuthBrowserSessionResult = Schema.Struct({\n  authenticated: Schema.Literal(true),\n  scopes: AuthEnvironmentScopes,\n  sessionMethod: ServerAuthSessionMethod,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthBrowserSessionResult = typeof AuthBrowserSessionResult.Type;\n\nexport const AuthClientMetadataDeviceType = Schema.Literals([\n  \"desktop\",\n  \"mobile\",\n  \"tablet\",\n  \"bot\",\n  \"unknown\",\n]);\nexport type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;\n\nexport const AuthClientPresentationMetadata = Schema.Struct({\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  deviceType: Schema.optionalKey(AuthClientMetadataDeviceType),\n  os: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;\n\nexport const AuthTokenExchangeRequest = Schema.Struct({\n  grant_type: Schema.Literal(AuthTokenExchangeGrantType),\n  subject_token: TrimmedNonEmptyString,\n  subject_token_type: Schema.Literal(AuthEnvironmentBootstrapTokenType),\n  requested_token_type: Schema.Literal(AuthAccessTokenType),\n  scope: Schema.optionalKey(TrimmedNonEmptyString),\n  client_label: Schema.optionalKey(TrimmedNonEmptyString),\n  client_device_type: Schema.optionalKey(AuthClientMetadataDeviceType),\n  client_os: Schema.optionalKey(TrimmedNonEmptyString),\n}).pipe(HttpApiSchema.asFormUrlEncoded());\nexport type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;\n\nexport const AuthAccessTokenResult = Schema.Struct({\n  access_token: TrimmedNonEmptyString,\n  issued_token_type: Schema.Literal(AuthAccessTokenType),\n  token_type: Schema.Literals([\"Bearer\", \"DPoP\"]),\n  expires_in: Schema.Number,\n  scope: TrimmedNonEmptyString,\n});\nexport type AuthAccessTokenResult = typeof AuthAccessTokenResult.Type;\n\nexport const AuthWebSocketTicketResult = Schema.Struct({\n  ticket: TrimmedNonEmptyString,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthWebSocketTicketResult = typeof AuthWebSocketTicketResult.Type;\n\nexport const AuthPairingCredentialResult = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  credential: TrimmedNonEmptyString,\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;\n\nexport const AuthPairingLink = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  credential: TrimmedNonEmptyString,\n  scopes: AuthEnvironmentScopes,\n  subject: TrimmedNonEmptyString,\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  createdAt: Schema.DateTimeUtc,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthPairingLink = typeof AuthPairingLink.Type;\n\nexport const AuthClientMetadata = Schema.Struct({\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  ipAddress: Schema.optionalKey(TrimmedNonEmptyString),\n  userAgent: Schema.optionalKey(TrimmedNonEmptyString),\n  deviceType: AuthClientMetadataDeviceType,\n  os: Schema.optionalKey(TrimmedNonEmptyString),\n  browser: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type AuthClientMetadata = typeof AuthClientMetadata.Type;\n\nexport const AuthClientSession = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: TrimmedNonEmptyString,\n  scopes: AuthEnvironmentScopes,\n  method: ServerAuthSessionMethod,\n  client: AuthClientMetadata,\n  issuedAt: Schema.DateTimeUtc,\n  expiresAt: Schema.DateTimeUtc,\n  lastConnectedAt: Schema.NullOr(Schema.DateTimeUtc),\n  connected: Schema.Boolean,\n  current: Schema.Boolean,\n});\nexport type AuthClientSession = typeof AuthClientSession.Type;\n\nexport const AuthAccessSnapshot = Schema.Struct({\n  pairingLinks: Schema.Array(AuthPairingLink),\n  clientSessions: Schema.Array(AuthClientSession),\n});\nexport type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;\n\nexport const AuthAccessStreamSnapshotEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"snapshot\"),\n  payload: AuthAccessSnapshot,\n});\nexport type AuthAccessStreamSnapshotEvent = typeof AuthAccessStreamSnapshotEvent.Type;\n\nexport const AuthAccessStreamPairingLinkUpsertedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"pairingLinkUpserted\"),\n  payload: AuthPairingLink,\n});\nexport type AuthAccessStreamPairingLinkUpsertedEvent =\n  typeof AuthAccessStreamPairingLinkUpsertedEvent.Type;\n\nexport const AuthAccessStreamPairingLinkRemovedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"pairingLinkRemoved\"),\n  payload: Schema.Struct({\n    id: TrimmedNonEmptyString,\n  }),\n});\nexport type AuthAccessStreamPairingLinkRemovedEvent =\n  typeof AuthAccessStreamPairingLinkRemovedEvent.Type;\n\nexport class AuthAccessStreamError extends Schema.TaggedErrorClass<AuthAccessStreamError>()(\n  \"AuthAccessStreamError\",\n  {\n    message: Schema.String,\n  },\n) {}\n\nexport class EnvironmentAuthorizationError extends Schema.TaggedErrorClass<EnvironmentAuthorizationError>()(\n  \"EnvironmentAuthorizationError\",\n  {\n    message: Schema.String,\n    requiredScope: AuthEnvironmentScope,\n  },\n) {}\n\nexport const AuthAccessStreamClientUpsertedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"clientUpserted\"),\n  payload: AuthClientSession,\n});\nexport type AuthAccessStreamClientUpsertedEvent = typeof AuthAccessStreamClientUpsertedEvent.Type;\n\nexport const AuthAccessStreamClientRemovedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"clientRemoved\"),\n  payload: Schema.Struct({\n    sessionId: AuthSessionId,\n  }),\n});\nexport type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;\n\nexport const AuthAccessStreamEvent = Schema.Union([\n  AuthAccessStreamSnapshotEvent,\n  AuthAccessStreamPairingLinkUpsertedEvent,\n  AuthAccessStreamPairingLinkRemovedEvent,\n  AuthAccessStreamClientUpsertedEvent,\n  AuthAccessStreamClientRemovedEvent,\n]);\nexport type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;\n\nexport const AuthRevokePairingLinkInput = Schema.Struct({\n  id: TrimmedNonEmptyString,\n});\nexport type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;\n\nexport const AuthRevokeClientSessionInput = Schema.Struct({\n  sessionId: AuthSessionId,\n});\nexport type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;\n\nexport const AuthCreatePairingCredentialInput = Schema.Struct({\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  scopes: Schema.optionalKey(AuthEnvironmentScopes),\n});\nexport type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;\n\nexport const AuthSessionState = Schema.Struct({\n  authenticated: Schema.Boolean,\n  auth: ServerAuthDescriptor,\n  scopes: Schema.optionalKey(AuthEnvironmentScopes),\n  sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),\n  expiresAt: Schema.optionalKey(Schema.DateTimeUtc),\n});\nexport type AuthSessionState = typeof AuthSessionState.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { EnvironmentId, ProjectId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const ExecutionEnvironmentPlatformOs = Schema.Literals([\n  \"darwin\",\n  \"linux\",\n  \"windows\",\n  \"unknown\",\n]);\nexport type ExecutionEnvironmentPlatformOs = typeof ExecutionEnvironmentPlatformOs.Type;\n\nexport const ExecutionEnvironmentPlatformArch = Schema.Literals([\"arm64\", \"x64\", \"other\"]);\nexport type ExecutionEnvironmentPlatformArch = typeof ExecutionEnvironmentPlatformArch.Type;\n\nexport const ExecutionEnvironmentPlatform = Schema.Struct({\n  os: ExecutionEnvironmentPlatformOs,\n  arch: ExecutionEnvironmentPlatformArch,\n});\nexport type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;\n\n/** How a server can replace itself with another version when asked over RPC.\n    New servers only advertise the stable launcher-backed \"boot-service\" path;\n    \"respawn\" remains decodable for compatibility with older servers. */\nexport const ServerSelfUpdateMethod = Schema.Literals([\"boot-service\", \"respawn\"]);\nexport type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;\n\n/** What update path a client should offer for a server: one of the RPC\n    self-update methods above, or \"desktop-managed\" when the backend's\n    version belongs to the T3 Code desktop app supervising it — updating the\n    app on that machine is the only way to update the server. */\nexport const ServerSelfUpdateCapability = Schema.Literals([\n  \"boot-service\",\n  \"respawn\",\n  \"desktop-managed\",\n]);\nexport type ServerSelfUpdateCapability = typeof ServerSelfUpdateCapability.Type;\n\nexport const ExecutionEnvironmentCapabilities = Schema.Struct({\n  repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  connectionProbe: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.settle / thread.unsettle commands. Absent on\n      pre-settlement servers, so clients treat missing as unsupported and\n      never send the commands under version skew. */\n  threadSettlement: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.snooze / thread.unsnooze commands. Same\n      version-skew contract as threadSettlement. */\n  threadSnooze: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.pin / thread.unpin commands. Same\n      version-skew contract as threadSettlement. */\n  threadPinning: Schema.optionalKey(Schema.Boolean),\n  /** Server understands regenerateTitle on thread.meta.update. Absent on\n      older servers, so clients hide the action instead of sending it. */\n  threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),\n  /** The update path clients should offer for this server. Absent on\n      servers that must be relaunched manually (dev checkouts, Windows\n      foreground runs, pre-update servers). */\n  serverSelfUpdate: Schema.optionalKey(ServerSelfUpdateCapability),\n  /** Server can stream self-update progress before acknowledging the\n      restart. Clients fall back to server.updateServer when absent. */\n  serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),\n  /** Server understands portProxy.list/authorize/revoke. Older servers omit\n      this, so clients must not send those requests under version skew. */\n  portProxy: Schema.optionalKey(Schema.Boolean),\n});\nexport type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;\n\nexport const ExecutionEnvironmentDescriptor = Schema.Struct({\n  environmentId: EnvironmentId,\n  label: TrimmedNonEmptyString,\n  platform: ExecutionEnvironmentPlatform,\n  serverVersion: TrimmedNonEmptyString,\n  capabilities: ExecutionEnvironmentCapabilities,\n});\nexport type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type;\n\nexport const EnvironmentConnectionState = Schema.Literals([\n  \"connecting\",\n  \"connected\",\n  \"disconnected\",\n  \"error\",\n]);\nexport type EnvironmentConnectionState = typeof EnvironmentConnectionState.Type;\n\nexport const RepositoryIdentityLocator = Schema.Struct({\n  source: Schema.Literal(\"git-remote\"),\n  remoteName: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n});\nexport type RepositoryIdentityLocator = typeof RepositoryIdentityLocator.Type;\n\nexport const RepositoryIdentity = Schema.Struct({\n  canonicalKey: TrimmedNonEmptyString,\n  locator: RepositoryIdentityLocator,\n  rootPath: Schema.optionalKey(TrimmedNonEmptyString),\n  displayName: Schema.optionalKey(TrimmedNonEmptyString),\n  provider: Schema.optionalKey(TrimmedNonEmptyString),\n  owner: Schema.optionalKey(TrimmedNonEmptyString),\n  name: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type RepositoryIdentity = typeof RepositoryIdentity.Type;\n\nexport const ScopedProjectRef = Schema.Struct({\n  environmentId: EnvironmentId,\n  projectId: ProjectId,\n});\nexport type ScopedProjectRef = typeof ScopedProjectRef.Type;\n\nexport const ScopedThreadRef = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n});\nexport type ScopedThreadRef = typeof ScopedThreadRef.Type;\n\nexport const ScopedThreadSessionRef = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n});\nexport type ScopedThreadSessionRef = typeof ScopedThreadSessionRef.Type;\n","/**\n * @since 1.0.0\n */\n// Taken from https://github.com/anonrig/fast-querystring under MIT License\nconst plusRegex = /\\+/g;\nconst Empty = function () {};\nEmpty.prototype = /*#__PURE__*/Object.create(null);\n/**\n * @category parsing\n * @since 1.0.0\n */\nexport function parse(input) {\n  // Optimization: Use new Empty() instead of Object.create(null) for performance\n  // v8 has a better optimization for initializing functions compared to Object\n  const result = new Empty();\n  if (typeof input !== \"string\") {\n    return result;\n  }\n  const inputLength = input.length;\n  let key = \"\";\n  let value = \"\";\n  let startingIndex = -1;\n  let equalityIndex = -1;\n  let shouldDecodeKey = false;\n  let shouldDecodeValue = false;\n  let keyHasPlus = false;\n  let valueHasPlus = false;\n  let hasBothKeyValuePair = false;\n  let c = 0;\n  // Have a boundary of input.length + 1 to access last pair inside the loop.\n  for (let i = 0; i < inputLength + 1; i++) {\n    c = i !== inputLength ? input.charCodeAt(i) : 38;\n    // Handle '&' and end of line to pass the current values to result\n    if (c === 38) {\n      hasBothKeyValuePair = equalityIndex > startingIndex;\n      // Optimization: Reuse equality index to store the end of key\n      if (!hasBothKeyValuePair) {\n        equalityIndex = i;\n      }\n      key = input.slice(startingIndex + 1, equalityIndex);\n      // Add key/value pair only if the range size is greater than 1; a.k.a. contains at least \"=\"\n      if (hasBothKeyValuePair || key.length > 0) {\n        // Optimization: Replace '+' with space\n        if (keyHasPlus) {\n          key = key.replace(plusRegex, \" \");\n        }\n        // Optimization: Do not decode if it's not necessary.\n        if (shouldDecodeKey) {\n          try {\n            key = decodeURIComponent(key) || key;\n          } catch {}\n        }\n        if (hasBothKeyValuePair) {\n          value = input.slice(equalityIndex + 1, i);\n          if (valueHasPlus) {\n            value = value.replace(plusRegex, \" \");\n          }\n          if (shouldDecodeValue) {\n            try {\n              value = decodeURIComponent(value) || value;\n            } catch {}\n          }\n        }\n        const currentValue = result[key];\n        if (currentValue === undefined) {\n          result[key] = value;\n        } else {\n          // Optimization: value.pop is faster than Array.isArray(value)\n          if (currentValue.pop) {\n            currentValue.push(value);\n          } else {\n            result[key] = [currentValue, value];\n          }\n        }\n      }\n      // Reset reading key value pairs\n      value = \"\";\n      startingIndex = i;\n      equalityIndex = i;\n      shouldDecodeKey = false;\n      shouldDecodeValue = false;\n      keyHasPlus = false;\n      valueHasPlus = false;\n    }\n    // Check '='\n    else if (c === 61) {\n      if (equalityIndex <= startingIndex) {\n        equalityIndex = i;\n      }\n      // If '=' character occurs again, we should decode the input.\n      else {\n        shouldDecodeValue = true;\n      }\n    }\n    // Check '+', and remember to replace it with empty space.\n    else if (c === 43) {\n      if (equalityIndex > startingIndex) {\n        valueHasPlus = true;\n      } else {\n        keyHasPlus = true;\n      }\n    }\n    // Check '%' character for encoding\n    else if (c === 37) {\n      if (equalityIndex > startingIndex) {\n        shouldDecodeValue = true;\n      } else {\n        shouldDecodeKey = true;\n      }\n    }\n  }\n  return result;\n}\nfunction getAsPrimitive(value) {\n  const type = typeof value;\n  if (type === \"string\") {\n    // Length check is handled inside encodeString function\n    return encodeString(value);\n  } else if (type === \"bigint\" || type === \"boolean\") {\n    return \"\" + value;\n  } else if (type === \"number\" && Number.isFinite(value)) {\n    return value < 1e21 ? \"\" + value : encodeString(\"\" + value);\n  }\n  return \"\";\n}\n/**\n * @category encoding\n * @since 1.0.0\n */\nexport function stringify(input) {\n  let result = \"\";\n  if (input === null || typeof input !== \"object\") {\n    return result;\n  }\n  const separator = \"&\";\n  const keys = Object.keys(input);\n  const keyLength = keys.length;\n  let valueLength = 0;\n  for (let i = 0; i < keyLength; i++) {\n    const key = keys[i];\n    const value = input[key];\n    const encodedKey = encodeString(key) + \"=\";\n    if (i) {\n      result += separator;\n    }\n    if (Array.isArray(value)) {\n      valueLength = value.length;\n      for (let j = 0; j < valueLength; j++) {\n        if (j) {\n          result += separator;\n        }\n        // Optimization: Dividing into multiple lines improves the performance.\n        // Since v8 does not need to care about the '+' character if it was one-liner.\n        result += encodedKey;\n        result += getAsPrimitive(value[j]);\n      }\n    } else {\n      result += encodedKey;\n      result += getAsPrimitive(value);\n    }\n  }\n  return result;\n}\n// -----------------------------------------------------------------------------\n// This has been taken from Node.js project.\n// Full implementation can be found from https://github.com/nodejs/node/blob/main/lib/internal/querystring.js\nconst hexTable = /*#__PURE__*/Array.from({\n  length: 256\n}, (_, i) => \"%\" + ((i < 16 ? \"0\" : \"\") + i.toString(16)).toUpperCase());\n// These characters do not need escaping when generating query strings:\n// ! - . _ ~\n// ' ( ) *\n// digits\n// alpha (uppercase)\n// alpha (lowercase)\n// biome-ignore format: the array should not be formatted\nconst noEscape = /*#__PURE__*/new Int8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n// 0 - 15\n0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n// 16 - 31\n0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0,\n// 32 - 47\n1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n// 48 - 63\n0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n// 64 - 79\n1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,\n// 80 - 95\n0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n// 96 - 111\n1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0 // 112 - 127\n]);\nfunction encodeString(str) {\n  const len = str.length;\n  if (len === 0) return \"\";\n  let out = \"\";\n  let lastPos = 0;\n  let i = 0;\n  outer: for (; i < len; i++) {\n    let c = str.charCodeAt(i);\n    // ASCII\n    while (c < 0x80) {\n      if (noEscape[c] !== 1) {\n        if (lastPos < i) out += str.slice(lastPos, i);\n        lastPos = i + 1;\n        out += hexTable[c];\n      }\n      if (++i === len) break outer;\n      c = str.charCodeAt(i);\n    }\n    if (lastPos < i) out += str.slice(lastPos, i);\n    // Multi-byte characters ...\n    if (c < 0x800) {\n      lastPos = i + 1;\n      out += hexTable[0xc0 | c >> 6] + hexTable[0x80 | c & 0x3f];\n      continue;\n    }\n    if (c < 0xd800 || c >= 0xe000) {\n      lastPos = i + 1;\n      out += hexTable[0xe0 | c >> 12] + hexTable[0x80 | c >> 6 & 0x3f] + hexTable[0x80 | c & 0x3f];\n      continue;\n    }\n    // Surrogate pair\n    ++i;\n    // This branch should never happen because all URLSearchParams entries\n    // should already be converted to USVString. But, included for\n    // completion's sake anyway.\n    if (i >= len) {\n      throw new Error(\"URI malformed\");\n    }\n    const c2 = str.charCodeAt(i) & 0x3ff;\n    lastPos = i + 1;\n    c = 0x10000 + ((c & 0x3ff) << 10 | c2);\n    out += hexTable[0xf0 | c >> 18] + hexTable[0x80 | c >> 12 & 0x3f] + hexTable[0x80 | c >> 6 & 0x3f] + hexTable[0x80 | c & 0x3f];\n  }\n  if (lastPos === 0) return str;\n  if (lastPos < len) return out + str.slice(lastPos);\n  return out;\n}\n//# sourceMappingURL=QueryString.js.map","import * as QS from \"../QueryString.js\";\nconst FULL_PATH_REGEXP = /^https?:\\/\\/.*?\\//;\nconst OPTIONAL_PARAM_REGEXP = /(\\/:[^/()]*?)\\?(\\/?)/;\n/** @internal */\nexport const make = (options = {}) => new RouterImpl(options);\nclass RouterImpl {\n  constructor(options = {}) {\n    this.options = {\n      ignoreTrailingSlash: true,\n      ignoreDuplicateSlashes: true,\n      caseSensitive: false,\n      maxParamLength: 100,\n      ...options\n    };\n  }\n  options;\n  routes = [];\n  trees = {};\n  on(method, path, handler) {\n    const optionalParamMatch = path.match(OPTIONAL_PARAM_REGEXP);\n    if (optionalParamMatch && optionalParamMatch.index !== undefined) {\n      assert(path.length === optionalParamMatch.index + optionalParamMatch[0].length, \"Optional Parameter needs to be the last parameter of the path\");\n      const pathFull = path.replace(OPTIONAL_PARAM_REGEXP, \"$1$2\");\n      const pathOptional = path.replace(OPTIONAL_PARAM_REGEXP, \"$2\");\n      this.on(method, pathFull, handler);\n      this.on(method, pathOptional, handler);\n      return;\n    }\n    if (this.options.ignoreDuplicateSlashes) {\n      path = removeDuplicateSlashes(path);\n    }\n    if (this.options.ignoreTrailingSlash) {\n      path = trimLastSlash(path);\n    }\n    const methods = typeof method === \"string\" ? [method] : method;\n    for (const method of methods) {\n      this._on(method, path, handler);\n    }\n  }\n  all(path, handler) {\n    this.on(httpMethods, path, handler);\n  }\n  _on(method, path, handler) {\n    if (this.trees[method] === undefined) {\n      this.trees[method] = new StaticNode(\"/\");\n    }\n    let pattern = path;\n    if (pattern === \"*\" && this.trees[method].prefix.length !== 0) {\n      const currentRoot = this.trees[method];\n      this.trees[method] = new StaticNode(\"\");\n      this.trees[method].staticChildren[\"/\"] = currentRoot;\n    }\n    let parentNodePathIndex = this.trees[method].prefix.length;\n    let currentNode = this.trees[method];\n    const params = [];\n    for (let i = 0; i <= pattern.length; i++) {\n      if (pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) === 58) {\n        // It's a double colon\n        i++;\n        continue;\n      }\n      const isParametricNode = pattern.charCodeAt(i) === 58 && pattern.charCodeAt(i + 1) !== 58;\n      const isWildcardNode = pattern.charCodeAt(i) === 42;\n      if (isParametricNode || isWildcardNode || i === pattern.length && i !== parentNodePathIndex) {\n        let staticNodePath = pattern.slice(parentNodePathIndex, i);\n        if (!this.options.caseSensitive) {\n          staticNodePath = staticNodePath.toLowerCase();\n        }\n        staticNodePath = staticNodePath.split(\"::\").join(\":\");\n        staticNodePath = staticNodePath.split(\"%\").join(\"%25\");\n        // add the static part of the route to the tree\n        currentNode = currentNode.createStaticChild(staticNodePath);\n      }\n      if (isParametricNode) {\n        let isRegexNode = false;\n        const regexps = [];\n        let lastParamStartIndex = i + 1;\n        for (let j = lastParamStartIndex;; j++) {\n          const charCode = pattern.charCodeAt(j);\n          const isRegexParam = charCode === 40;\n          const isStaticPart = charCode === 45 || charCode === 46;\n          const isEndOfNode = charCode === 47 || j === pattern.length;\n          if (isRegexParam || isStaticPart || isEndOfNode) {\n            const paramName = pattern.slice(lastParamStartIndex, j);\n            params.push(paramName);\n            isRegexNode = isRegexNode || isRegexParam || isStaticPart;\n            if (isRegexParam) {\n              const endOfRegexIndex = getClosingParenthensePosition(pattern, j);\n              const regexString = pattern.slice(j, endOfRegexIndex + 1);\n              regexps.push(trimRegExpStartAndEnd(regexString));\n              j = endOfRegexIndex + 1;\n            } else {\n              regexps.push(\"(.*?)\");\n            }\n            const staticPartStartIndex = j;\n            for (; j < pattern.length; j++) {\n              const charCode = pattern.charCodeAt(j);\n              if (charCode === 47) break;\n              if (charCode === 58) {\n                const nextCharCode = pattern.charCodeAt(j + 1);\n                if (nextCharCode === 58) j++;else break;\n              }\n            }\n            let staticPart = pattern.slice(staticPartStartIndex, j);\n            if (staticPart) {\n              staticPart = staticPart.split(\"::\").join(\":\");\n              staticPart = staticPart.split(\"%\").join(\"%25\");\n              regexps.push(escapeRegExp(staticPart));\n            }\n            lastParamStartIndex = j + 1;\n            if (isEndOfNode || pattern.charCodeAt(j) === 47 || j === pattern.length) {\n              const nodePattern = isRegexNode ? \"()\" + staticPart : staticPart;\n              const nodePath = pattern.slice(i, j);\n              pattern = pattern.slice(0, i + 1) + nodePattern + pattern.slice(j);\n              i += nodePattern.length;\n              const regex = isRegexNode ? new RegExp(\"^\" + regexps.join(\"\") + \"$\") : undefined;\n              currentNode = currentNode.createParametricChild(regex, staticPart, nodePath);\n              parentNodePathIndex = i + 1;\n              break;\n            }\n          }\n        }\n      } else if (isWildcardNode) {\n        // add the wildcard parameter\n        params.push(\"*\");\n        currentNode = currentNode.createWildcardChild();\n        parentNodePathIndex = i + 1;\n        if (i !== pattern.length - 1) {\n          throw new Error(\"Wildcard must be the last character in the route\");\n        }\n      }\n    }\n    if (!this.options.caseSensitive) {\n      pattern = pattern.toLowerCase();\n    }\n    if (pattern === \"*\") {\n      pattern = \"/*\";\n    }\n    for (const existRoute of this.routes) {\n      if (existRoute.method === method && existRoute.pattern === pattern) {\n        throw new Error(`Method '${method}' already declared for route '${pattern}'`);\n      }\n    }\n    const route = {\n      method,\n      path,\n      pattern,\n      params,\n      handler\n    };\n    this.routes.push(route);\n    currentNode.addRoute(route);\n  }\n  has(method, path) {\n    const node = this.trees[method];\n    if (node === undefined) {\n      return false;\n    }\n    const staticNode = node.getStaticChild(path);\n    if (staticNode === undefined) {\n      return false;\n    }\n    return staticNode.isLeafNode;\n  }\n  find(method, path) {\n    let currentNode = this.trees[method];\n    if (currentNode === undefined) return undefined;\n    if (path.charCodeAt(0) !== 47) {\n      // 47 is '/'\n      path = path.replace(FULL_PATH_REGEXP, \"/\");\n    }\n    // This must be run before sanitizeUrl as the resulting function\n    // .sliceParameter must be constructed with same URL string used\n    // throughout the rest of this function.\n    if (this.options.ignoreDuplicateSlashes) {\n      path = removeDuplicateSlashes(path);\n    }\n    let sanitizedUrl;\n    let querystring;\n    let shouldDecodeParam;\n    try {\n      sanitizedUrl = safeDecodeURI(path);\n      path = sanitizedUrl.path;\n      querystring = sanitizedUrl.querystring;\n      shouldDecodeParam = sanitizedUrl.shouldDecodeParam;\n    } catch (error) {\n      return undefined;\n    }\n    if (this.options.ignoreTrailingSlash) {\n      path = trimLastSlash(path);\n    }\n    const originPath = path;\n    if (this.options.caseSensitive === false) {\n      path = path.toLowerCase();\n    }\n    const maxParamLength = this.options.maxParamLength;\n    let pathIndex = currentNode.prefix.length;\n    const params = [];\n    const pathLen = path.length;\n    const brothersNodesStack = [];\n    while (true) {\n      if (pathIndex === pathLen && currentNode.isLeafNode) {\n        const handle = currentNode.handlerStorage?.find();\n        if (handle !== undefined) {\n          return {\n            handler: handle.handler,\n            params: handle.createParams(params),\n            searchParams: QS.parse(querystring)\n          };\n        }\n      }\n      let node = currentNode.getNextNode(path, pathIndex, brothersNodesStack, params.length);\n      if (node === undefined) {\n        if (brothersNodesStack.length === 0) {\n          return undefined;\n        }\n        const brotherNodeState = brothersNodesStack.pop();\n        pathIndex = brotherNodeState.brotherPathIndex;\n        params.splice(brotherNodeState.paramsCount);\n        node = brotherNodeState.brotherNode;\n      }\n      currentNode = node;\n      // static route\n      if (currentNode._tag === \"StaticNode\") {\n        pathIndex += currentNode.prefix.length;\n        continue;\n      }\n      if (currentNode._tag === \"WildcardNode\") {\n        let param = originPath.slice(pathIndex);\n        if (shouldDecodeParam) {\n          param = safeDecodeURIComponent(param);\n        }\n        params.push(param);\n        pathIndex = pathLen;\n        continue;\n      }\n      if (currentNode._tag === \"ParametricNode\") {\n        let paramEndIndex = originPath.indexOf(\"/\", pathIndex);\n        if (paramEndIndex === -1) {\n          paramEndIndex = pathLen;\n        }\n        let param = originPath.slice(pathIndex, paramEndIndex);\n        if (shouldDecodeParam) {\n          param = safeDecodeURIComponent(param);\n        }\n        if (currentNode.regex !== undefined) {\n          const matchedParameters = currentNode.regex.exec(param);\n          if (matchedParameters === null) continue;\n          for (let i = 1; i < matchedParameters.length; i++) {\n            const matchedParam = matchedParameters[i];\n            if (matchedParam.length > maxParamLength) {\n              return undefined;\n            }\n            params.push(matchedParam);\n          }\n        } else {\n          if (param.length > maxParamLength) {\n            return undefined;\n          }\n          params.push(param);\n        }\n        pathIndex = paramEndIndex;\n      }\n    }\n  }\n}\nclass HandlerStorage {\n  handlers = [];\n  unconstrainedHandler;\n  find() {\n    return this.unconstrainedHandler;\n  }\n  add(route) {\n    const handler = {\n      params: route.params,\n      handler: route.handler,\n      createParams: compileCreateParams(route.params)\n    };\n    this.handlers.push(handler);\n    this.unconstrainedHandler = this.handlers[0];\n  }\n}\nclass NodeBase {\n  isLeafNode = false;\n  routes;\n  handlerStorage;\n  addRoute(route) {\n    if (this.routes === undefined) {\n      this.routes = [route];\n    } else {\n      this.routes.push(route);\n    }\n    if (this.handlerStorage === undefined) {\n      this.handlerStorage = new HandlerStorage();\n    }\n    this.isLeafNode = true;\n    this.handlerStorage.add(route);\n  }\n}\nclass ParentNode extends NodeBase {\n  staticChildren = {};\n  findStaticMatchingChild(path, pathIndex) {\n    const staticChild = this.staticChildren[path.charAt(pathIndex)];\n    if (staticChild === undefined || !staticChild.matchPrefix(path, pathIndex)) {\n      return undefined;\n    }\n    return staticChild;\n  }\n  getStaticChild(path, pathIndex = 0) {\n    if (path.length === pathIndex) {\n      return this;\n    }\n    const staticChild = this.findStaticMatchingChild(path, pathIndex);\n    if (staticChild === undefined) {\n      return undefined;\n    }\n    return staticChild.getStaticChild(path, pathIndex + staticChild.prefix.length);\n  }\n  createStaticChild(path) {\n    if (path.length === 0) {\n      return this;\n    }\n    let staticChild = this.staticChildren[path.charAt(0)];\n    if (staticChild) {\n      let i = 1;\n      for (; i < staticChild.prefix.length; i++) {\n        if (path.charCodeAt(i) !== staticChild.prefix.charCodeAt(i)) {\n          staticChild = staticChild.split(this, i);\n          break;\n        }\n      }\n      return staticChild.createStaticChild(path.slice(i));\n    }\n    const label = path.charAt(0);\n    this.staticChildren[label] = new StaticNode(path);\n    return this.staticChildren[label];\n  }\n}\nclass StaticNode extends ParentNode {\n  _tag = \"StaticNode\";\n  constructor(prefix) {\n    super();\n    this.setPrefix(prefix);\n  }\n  prefix;\n  matchPrefix;\n  parametricChildren = [];\n  wildcardChild;\n  setPrefix(prefix) {\n    this.prefix = prefix;\n    if (prefix.length === 1) {\n      this.matchPrefix = (_path, _pathIndex) => true;\n    } else {\n      const len = prefix.length;\n      this.matchPrefix = function (path, pathIndex) {\n        for (let i = 1; i < len; i++) {\n          if (path.charCodeAt(pathIndex + i) !== this.prefix.charCodeAt(i)) {\n            return false;\n          }\n        }\n        return true;\n      };\n    }\n  }\n  getParametricChild(regex) {\n    if (regex === undefined) {\n      return this.parametricChildren.find(child => child.isRegex === false);\n    }\n    const source = regex.source;\n    return this.parametricChildren.find(child => {\n      if (child.regex === undefined) {\n        return false;\n      }\n      return child.regex.source === source;\n    });\n  }\n  createParametricChild(regex, staticSuffix, nodePath) {\n    let child = this.getParametricChild(regex);\n    if (child !== undefined) {\n      child.nodePaths.add(nodePath);\n      return child;\n    }\n    child = new ParametricNode(regex, staticSuffix, nodePath);\n    this.parametricChildren.push(child);\n    this.parametricChildren.sort((child1, child2) => {\n      if (!child1.isRegex) return 1;\n      if (!child2.isRegex) return -1;\n      if (child1.staticSuffix === undefined) return 1;\n      if (child2.staticSuffix === undefined) return -1;\n      if (child2.staticSuffix.endsWith(child1.staticSuffix)) return 1;\n      if (child1.staticSuffix.endsWith(child2.staticSuffix)) return -1;\n      return 0;\n    });\n    return child;\n  }\n  createWildcardChild() {\n    if (this.wildcardChild === undefined) {\n      this.wildcardChild = new WildcardNode();\n    }\n    return this.wildcardChild;\n  }\n  split(parentNode, length) {\n    const parentPrefix = this.prefix.slice(0, length);\n    const childPrefix = this.prefix.slice(length);\n    this.setPrefix(childPrefix);\n    const staticNode = new StaticNode(parentPrefix);\n    staticNode.staticChildren[childPrefix.charAt(0)] = this;\n    parentNode.staticChildren[parentPrefix.charAt(0)] = staticNode;\n    return staticNode;\n  }\n  getNextNode(path, pathIndex, nodeStack, paramsCount) {\n    let node = this.findStaticMatchingChild(path, pathIndex);\n    let parametricBrotherNodeIndex = 0;\n    if (node === undefined) {\n      if (this.parametricChildren.length === 0) {\n        return this.wildcardChild;\n      }\n      node = this.parametricChildren[0];\n      parametricBrotherNodeIndex = 1;\n    }\n    if (this.wildcardChild !== undefined) {\n      nodeStack.push({\n        paramsCount,\n        brotherPathIndex: pathIndex,\n        brotherNode: this.wildcardChild\n      });\n    }\n    for (let i = this.parametricChildren.length - 1; i >= parametricBrotherNodeIndex; i--) {\n      nodeStack.push({\n        paramsCount,\n        brotherPathIndex: pathIndex,\n        brotherNode: this.parametricChildren[i]\n      });\n    }\n    return node;\n  }\n}\nclass ParametricNode extends ParentNode {\n  regex;\n  staticSuffix;\n  _tag = \"ParametricNode\";\n  constructor(regex, staticSuffix, nodePath) {\n    super();\n    this.regex = regex;\n    this.staticSuffix = staticSuffix;\n    this.isRegex = !!regex;\n    this.nodePaths = new Set([nodePath]);\n  }\n  isRegex;\n  nodePaths;\n  getNextNode(path, pathIndex) {\n    return this.findStaticMatchingChild(path, pathIndex);\n  }\n}\nclass WildcardNode extends NodeBase {\n  _tag = \"WildcardNode\";\n  getNextNode(_path, _pathIndex, _nodeStack, _paramsCount) {\n    return undefined;\n  }\n}\nconst assert = (condition, message) => {\n  if (!condition) {\n    throw new Error(message);\n  }\n};\nfunction removeDuplicateSlashes(path) {\n  return path.replace(/\\/\\/+/g, \"/\");\n}\nfunction trimLastSlash(path) {\n  if (path.length > 1 && path.charCodeAt(path.length - 1) === 47) {\n    return path.slice(0, -1);\n  }\n  return path;\n}\nfunction compileCreateParams(params) {\n  const len = params.length;\n  return function (paramsArray) {\n    const paramsObject = {};\n    for (let i = 0; i < len; i++) {\n      paramsObject[params[i]] = paramsArray[i];\n    }\n    return paramsObject;\n  };\n}\nfunction getClosingParenthensePosition(path, idx) {\n  // `path.indexOf()` will always return the first position of the closing parenthese,\n  // but it's inefficient for grouped or wrong regexp expressions.\n  // see issues #62 and #63 for more info\n  let parentheses = 1;\n  while (idx < path.length) {\n    idx++;\n    // ignore skipped chars\n    if (path[idx] === \"\\\\\") {\n      idx++;\n      continue;\n    }\n    if (path[idx] === \")\") {\n      parentheses--;\n    } else if (path[idx] === \"(\") {\n      parentheses++;\n    }\n    if (!parentheses) return idx;\n  }\n  throw new TypeError('Invalid regexp expression in \"' + path + '\"');\n}\nfunction trimRegExpStartAndEnd(regexString) {\n  // removes chars that marks start \"^\" and end \"$\" of regexp\n  if (regexString.charCodeAt(1) === 94) {\n    regexString = regexString.slice(0, 1) + regexString.slice(2);\n  }\n  if (regexString.charCodeAt(regexString.length - 2) === 36) {\n    regexString = regexString.slice(0, regexString.length - 2) + regexString.slice(regexString.length - 1);\n  }\n  return regexString;\n}\nfunction escapeRegExp(string) {\n  return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// It must spot all the chars where decodeURIComponent(x) !== decodeURI(x)\n// The chars are: # $ & + , / : ; = ? @\nfunction decodeComponentChar(highCharCode, lowCharCode) {\n  if (highCharCode === 50) {\n    if (lowCharCode === 53) return \"%\";\n    if (lowCharCode === 51) return \"#\";\n    if (lowCharCode === 52) return \"$\";\n    if (lowCharCode === 54) return \"&\";\n    if (lowCharCode === 66) return \"+\";\n    if (lowCharCode === 98) return \"+\";\n    if (lowCharCode === 67) return \",\";\n    if (lowCharCode === 99) return \",\";\n    if (lowCharCode === 70) return \"/\";\n    if (lowCharCode === 102) return \"/\";\n    return undefined;\n  }\n  if (highCharCode === 51) {\n    if (lowCharCode === 65) return \":\";\n    if (lowCharCode === 97) return \":\";\n    if (lowCharCode === 66) return \";\";\n    if (lowCharCode === 98) return \";\";\n    if (lowCharCode === 68) return \"=\";\n    if (lowCharCode === 100) return \"=\";\n    if (lowCharCode === 70) return \"?\";\n    if (lowCharCode === 102) return \"?\";\n    return undefined;\n  }\n  if (highCharCode === 52 && lowCharCode === 48) {\n    return \"@\";\n  }\n  return undefined;\n}\nfunction safeDecodeURI(path) {\n  let shouldDecode = false;\n  let shouldDecodeParam = false;\n  let querystring = \"\";\n  for (let i = 1; i < path.length; i++) {\n    const charCode = path.charCodeAt(i);\n    if (charCode === 37) {\n      const highCharCode = path.charCodeAt(i + 1);\n      const lowCharCode = path.charCodeAt(i + 2);\n      if (decodeComponentChar(highCharCode, lowCharCode) === undefined) {\n        shouldDecode = true;\n      } else {\n        shouldDecodeParam = true;\n        // %25 - encoded % char. We need to encode one more time to prevent double decoding\n        if (highCharCode === 50 && lowCharCode === 53) {\n          shouldDecode = true;\n          path = path.slice(0, i + 1) + \"25\" + path.slice(i + 1);\n          i += 2;\n        }\n        i += 2;\n      }\n      // Some systems do not follow RFC and separate the path and query\n      // string with a `;` character (code 59), e.g. `/foo;jsessionid=123456`.\n      // Thus, we need to split on `;` as well as `?` and `#`.\n    } else if (charCode === 63 || charCode === 59 || charCode === 35) {\n      querystring = path.slice(i + 1);\n      path = path.slice(0, i);\n      break;\n    }\n  }\n  const decodedPath = shouldDecode ? decodeURI(path) : path;\n  return {\n    path: decodedPath,\n    querystring,\n    shouldDecodeParam\n  };\n}\nfunction safeDecodeURIComponent(uriComponent) {\n  const startIndex = uriComponent.indexOf(\"%\");\n  if (startIndex === -1) return uriComponent;\n  let decoded = \"\";\n  let lastIndex = startIndex;\n  for (let i = startIndex; i < uriComponent.length; i++) {\n    if (uriComponent.charCodeAt(i) === 37) {\n      const highCharCode = uriComponent.charCodeAt(i + 1);\n      const lowCharCode = uriComponent.charCodeAt(i + 2);\n      const decodedChar = decodeComponentChar(highCharCode, lowCharCode);\n      decoded += uriComponent.slice(lastIndex, i) + decodedChar;\n      lastIndex = i + 3;\n    }\n  }\n  return uriComponent.slice(0, startIndex) + decoded + uriComponent.slice(lastIndex);\n}\nconst httpMethods = [\"ACL\", \"BIND\", \"CHECKOUT\", \"CONNECT\", \"COPY\", \"DELETE\", \"GET\", \"HEAD\", \"LINK\", \"LOCK\", \"M-SEARCH\", \"MERGE\", \"MKACTIVITY\", \"MKCALENDAR\", \"MKCOL\", \"MOVE\", \"NOTIFY\", \"OPTIONS\", \"PATCH\", \"POST\", \"PROPFIND\", \"PROPPATCH\", \"PURGE\", \"PUT\", \"REBIND\", \"REPORT\", \"SEARCH\", \"SOURCE\", \"SUBSCRIBE\", \"TRACE\", \"UNBIND\", \"UNLINK\", \"UNLOCK\", \"UNSUBSCRIBE\"];\n//# sourceMappingURL=router.js.map","/**\n * @since 1.0.0\n */\nimport * as internal from \"./internal/router.js\";\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = internal.make;\n//# sourceMappingURL=index.js.map","/**\n * Builds server-side routers for Effect HTTP applications.\n *\n * `HttpRouter` collects routes and middleware while an application layer is\n * being built. Once the router is complete, it handles each\n * `HttpServerRequest` by finding a matching route and producing an\n * `HttpServerResponse`. The module also includes helpers for route definitions,\n * prefixes, parameters, request decoding, CORS, and running the router.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { compose, dual, identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Tracer from \"../../Tracer.js\";\nimport * as FindMyWay from \"./FindMyWay.js\";\nimport * as HttpEffect from \"./HttpEffect.js\";\nimport * as HttpMiddleware from \"./HttpMiddleware.js\";\nimport * as HttpServer from \"./HttpServer.js\";\nimport * as HttpServerError from \"./HttpServerError.js\";\nimport * as HttpServerRequest from \"./HttpServerRequest.js\";\nimport * as HttpServerResponse from \"./HttpServerResponse.js\";\nconst TypeId = \"~effect/http/HttpRouter\";\n/**\n * Service tag for the HTTP router used while constructing an HTTP application.\n * Route and middleware layers require this service to register themselves with\n * the router.\n *\n * @category services\n * @since 4.0.0\n */\nexport const HttpRouter = /*#__PURE__*/Context.Service(\"effect/http/HttpRouter\");\n/**\n * Constructs an empty `HttpRouter` service.\n *\n * **Details**\n *\n * The returned router accepts route and middleware registrations and later routes\n * the current `HttpServerRequest` to the matching `HttpServerResponse`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.gen(function* () {\n  const router = FindMyWay.make(yield* RouterConfig);\n  const middleware = new Set();\n  const addAll = routes => Effect.contextWith(context => {\n    const middleware = getMiddleware(context);\n    const applyMiddleware = effect => {\n      for (let i = 0; i < middleware.length; i++) {\n        effect = middleware[i](effect);\n      }\n      return effect;\n    };\n    for (let i = 0; i < routes.length; i++) {\n      const route = middleware.length === 0 ? routes[i] : makeRoute({\n        ...routes[i],\n        handler: applyMiddleware(routes[i].handler)\n      });\n      if (route.method === \"*\") {\n        if (route.path.endsWith(\"/*\")) {\n          router.all(route.path, route);\n          router.all(route.path.slice(0, -2), route);\n        } else {\n          router.all(route.path, route);\n        }\n      } else {\n        if (route.path.endsWith(\"/*\")) {\n          router.on(route.method, route.path, route);\n          router.on(route.method, route.path.slice(0, -2), route);\n        } else {\n          router.on(route.method, route.path, route);\n        }\n      }\n    }\n    return Effect.void;\n  });\n  return HttpRouter.of({\n    [TypeId]: TypeId,\n    prefixed(prefix) {\n      return HttpRouter.of({\n        ...this,\n        prefixed: newPrefix => this.prefixed(prefixPath(prefix, newPrefix)),\n        addAll: routes => addAll(routes.map(prefixRoute(prefix))),\n        add: (method, path, handler, options) => addAll([makeRoute({\n          method,\n          path: prefixPath(path, prefix),\n          handler: HttpServerResponse.isHttpServerResponse(handler) ? Effect.succeed(handler) : Effect.isEffect(handler) ? handler : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler),\n          uninterruptible: options?.uninterruptible ?? false,\n          prefix\n        })])\n      });\n    },\n    addAll,\n    add: (method, path, handler, options) => addAll([route(method, path, handler, options)]),\n    addGlobalMiddleware: middleware_ => Effect.sync(() => {\n      middleware.add(middleware_);\n    }),\n    asHttpEffect() {\n      let handler = Effect.withFiber(fiber => {\n        let context = fiber.context;\n        const request = Context.getUnsafe(context, HttpServerRequest.HttpServerRequest);\n        let result = router.find(request.method, request.url);\n        if (result === undefined && request.method === \"HEAD\") {\n          result = router.find(\"GET\", request.url);\n        }\n        if (result === undefined) {\n          return Effect.fail(new HttpServerError.HttpServerError({\n            reason: new HttpServerError.RouteNotFound({\n              request\n            })\n          }));\n        }\n        const route = result.handler;\n        if (Option.isSome(route.prefix)) {\n          context = Context.add(context, HttpServerRequest.HttpServerRequest, sliceRequestUrl(request, route.prefix.value));\n        }\n        context = Context.add(context, HttpServerRequest.ParsedSearchParams, result.searchParams);\n        context = Context.add(context, RouteContext, {\n          route,\n          params: result.params\n        });\n        const span = Context.getOrUndefined(context, Tracer.ParentSpan);\n        if (span && span._tag === \"Span\") {\n          span.attribute(\"http.route\", route.path);\n        }\n        return Effect.updateContext(route.uninterruptible ? route.handler : Effect.interruptible(route.handler), () => context);\n      });\n      if (middleware.size === 0) return handler;\n      for (const fn of Arr.reverse(middleware)) {\n        handler = fn(handler);\n      }\n      return handler;\n    }\n  });\n});\nfunction sliceRequestUrl(request, prefix) {\n  const prefexLen = prefix.length;\n  return request.modify({\n    url: request.url.length <= prefexLen ? \"/\" : request.url.slice(prefexLen)\n  });\n}\n/**\n * Context reference for low-level router configuration.\n *\n * **Details**\n *\n * The value is passed to the route matcher when an `HttpRouter` is created and\n * defaults to an empty configuration.\n *\n * @category services\n * @since 4.0.0\n */\nexport const RouterConfig = /*#__PURE__*/Context.Reference(\"effect/http/HttpRouter/RouterConfig\", {\n  defaultValue: () => ({})\n});\n/**\n * Service for the matched HTTP route in the current request.\n *\n * **When to use**\n *\n * Use to read captured path parameters and route metadata while handling a\n * request matched by the router.\n *\n * **Details**\n *\n * It provides the route definition and the path parameters captured by the route\n * matcher.\n *\n * @category services\n * @since 4.0.0\n */\nexport class RouteContext extends /*#__PURE__*/Context.Service()(\"effect/http/HttpRouter/RouteContext\") {}\n/**\n * Effect that returns the path parameters captured for the current matched route.\n *\n * @category getters\n * @since 4.0.0\n */\nexport const params = /*#__PURE__*/Effect.map(RouteContext, _ => _.params);\n/**\n * Decodes a schema from the current request and its JSON body.\n *\n * **Details**\n *\n * The input passed to the schema includes the request method, URL, headers,\n * cookies, path parameters, search parameters, and parsed JSON body. The effect\n * fails if the body cannot be parsed or the schema decode fails.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n  const parse = Schema.decodeUnknownEffect(schema);\n  return Effect.contextWith(context => {\n    const request = Context.get(context, HttpServerRequest.HttpServerRequest);\n    const searchParams = Context.get(context, HttpServerRequest.ParsedSearchParams);\n    const routeContext = Context.get(context, RouteContext);\n    return Effect.flatMap(request.json, body => parse({\n      method: request.method,\n      url: request.url,\n      headers: request.headers,\n      cookies: request.cookies,\n      pathParams: routeContext.params,\n      searchParams,\n      body\n    }, options));\n  });\n};\n/**\n * Decodes a schema from the current request without reading the request body.\n *\n * **Details**\n *\n * The input passed to the schema includes the request method, URL, headers,\n * cookies, path parameters, and search parameters.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaNoBody = (schema, options) => {\n  const parse = Schema.decodeUnknownEffect(schema);\n  return Effect.contextWith(context => {\n    const request = Context.get(context, HttpServerRequest.HttpServerRequest);\n    const searchParams = Context.get(context, HttpServerRequest.ParsedSearchParams);\n    const routeContext = Context.get(context, RouteContext);\n    return parse({\n      method: request.method,\n      url: request.url,\n      headers: request.headers,\n      cookies: request.cookies,\n      pathParams: routeContext.params,\n      searchParams\n    }, options);\n  });\n};\n/**\n * Decodes a schema from the current route path parameters and search parameters.\n *\n * **Details**\n *\n * When the same key appears in both sources, the path parameter value is used.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaParams = (schema, options) => {\n  const parse = Schema.decodeUnknownEffect(schema);\n  return Effect.contextWith(context => {\n    const searchParams = Context.get(context, HttpServerRequest.ParsedSearchParams);\n    const routeContext = Context.get(context, RouteContext);\n    return parse({\n      ...searchParams,\n      ...routeContext.params\n    }, options);\n  });\n};\n/**\n * Decodes a schema from the path parameters captured for the current matched\n * route.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaPathParams = (schema, options) => {\n  const parse = Schema.decodeUnknownEffect(schema);\n  return Effect.flatMap(params, _ => parse(_, options));\n};\n/**\n * Creates a layer that accesses the current `HttpRouter` service and runs the\n * supplied effect.\n *\n * **When to use**\n *\n * Use when you need to register routes or middleware with the router during layer\n * construction.\n *\n * **Example** (Registering routes during layer construction)\n *\n * ```ts import.meta.vitest\n * import { Effect } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Routes = HttpRouter.use((router) =>\n *   router.add(\"GET\", \"/health\", HttpServerResponse.text(\"ready\"))\n * )\n *\n * const program = Effect.acquireUseRelease(\n *   Effect.sync(() => HttpRouter.toWebHandler(Routes, { disableLogger: true })),\n *   ({ handler }) =>\n *     Effect.gen(function*() {\n *       const response = yield* Effect.promise(() => handler(new Request(\"http://localhost/health\")))\n *       const body = yield* Effect.promise(() => response.text())\n *       return body\n *     }),\n *   ({ dispose }) => Effect.promise(dispose)\n * )\n *\n * await Effect.runPromise(program) // => \"ready\"\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const use = f => Layer.effectDiscard(Effect.flatMap(HttpRouter, f));\n/**\n * Create a layer that adds a single route to the HTTP router.\n *\n * **Example** (Adding a GET route)\n *\n * ```ts import.meta.vitest\n * import { Layer } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Route = HttpRouter.add(\n *   \"GET\",\n *   \"/hello\",\n *   HttpServerResponse.text(\"Hello, World!\")\n * )\n * Layer.isLayer(Route) // => true\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const add = (method, path, handler, options) => use(router => router.add(method, path, handler, options));\n/**\n * Create a layer that adds multiple routes to the HTTP router.\n *\n * **Example** (Adding multiple routes)\n *\n * ```ts import.meta.vitest\n * import { Layer } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Routes = HttpRouter.addAll([\n *   HttpRouter.route(\n *     \"GET\",\n *     \"/hello\",\n *     HttpServerResponse.text(\"Hello, World!\")\n *   )\n * ])\n * Layer.isLayer(Routes) // => true\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const addAll = (routes, options) => Layer.effectDiscard(Effect.gen(function* () {\n  const toAdd = Effect.isEffect(routes) ? yield* routes : routes;\n  let router = yield* HttpRouter;\n  if (options?.prefix) {\n    router = router.prefixed(options.prefix);\n  }\n  yield* router.addAll(toAdd);\n}));\n/**\n * Layer that provides a newly constructed `HttpRouter`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Layer.effect(HttpRouter)(make);\n/**\n * Builds an application layer with a router and returns the router as an HTTP\n * handler effect.\n *\n * **Details**\n *\n * The returned effect handles the current `HttpServerRequest` in the current\n * `Scope`; route request markers are converted into the ordinary requirements of\n * the returned handler.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toHttpEffect = appLayer => Effect.gen(function* () {\n  const context = yield* Layer.build(Layer.provideMerge(appLayer, layer));\n  const router = Context.get(context, HttpRouter);\n  // @effect-diagnostics effect/returnEffectInGen:off\n  return router.asHttpEffect();\n});\nconst RouteTypeId = \"~effect/http/HttpRouter/Route\";\nconst makeRoute = options => ({\n  ...options,\n  uninterruptible: options.uninterruptible ?? false,\n  prefix: typeof options.prefix === \"string\" ? Option.some(options.prefix) : options.prefix ?? Option.none(),\n  [RouteTypeId]: RouteTypeId\n});\n/**\n * Constructs a `Route` from an HTTP method, path, and handler.\n *\n * **Details**\n *\n * The handler may be a static response, an effect that produces a response, or a\n * function from the current request to a response effect. Set `uninterruptible` to\n * prevent the route handler from being made interruptible while it runs.\n *\n * @category routes\n * @since 4.0.0\n */\nexport const route = (method, path, handler, options) => makeRoute({\n  ...options,\n  method,\n  path,\n  handler: HttpServerResponse.isHttpServerResponse(handler) ? Effect.succeed(handler) : Effect.isEffect(handler) ? handler : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler),\n  uninterruptible: options?.uninterruptible ?? false\n});\nconst removeTrailingSlash = path => path.endsWith(\"/\") ? path.slice(0, -1) : path;\n/**\n * Adds a path prefix to a route path.\n *\n * **Details**\n *\n * Trailing slashes are removed from the prefix; `/` becomes the prefix itself and\n * `*` becomes a wildcard route under the prefix.\n *\n * @category transforming\n * @since 4.0.0\n */\nexport const prefixPath = /*#__PURE__*/dual(2, (self, prefix) => {\n  prefix = removeTrailingSlash(prefix);\n  if (self === \"*\") return `${prefix}/*`;else if (self === \"/\") return prefix;\n  return prefix + self;\n});\n/**\n * Returns a copy of a route with its path prefixed.\n *\n * **Details**\n *\n * The prefix is also tracked on the route so that, when the route handles a\n * request, the matched prefix can be removed from the request URL seen by the\n * handler.\n *\n * @category routes\n * @since 4.0.0\n */\nexport const prefixRoute = /*#__PURE__*/dual(2, (self, prefix) => makeRoute({\n  ...self,\n  path: prefixPath(self.path, prefix),\n  prefix: Option.match(self.prefix, {\n    onNone: () => prefix,\n    onSome: existingPrefix => prefixPath(existingPrefix, prefix)\n  })\n}));\nconst MiddlewareTypeId = \"~effect/http/HttpRouter/Middleware\";\n/**\n * Create a middleware layer that can be used to modify requests and responses.\n *\n * **Details**\n *\n * By default, the middleware only affects the routes that it is provided to.\n *\n * If you want to create a middleware that applies globally to all routes, pass\n * the `global` option as `true`.\n *\n * **Example** (Applying route and global middleware)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const RouteMiddleware = HttpRouter.middleware((httpEffect) =>\n *   Effect.map(httpEffect, HttpServerResponse.setHeader(\"x-route\", \"route\"))\n * ).layer\n *\n * const GlobalMiddleware = HttpRouter.middleware(\n *   (httpEffect) => Effect.map(httpEffect, HttpServerResponse.setHeader(\"x-global\", \"global\")),\n *   { global: true }\n * )\n *\n * const Routes = HttpRouter.add(\"GET\", \"/hello\", HttpServerResponse.text(\"Hello\")).pipe(\n *   Layer.provide(RouteMiddleware)\n * )\n * const App = Layer.mergeAll(Routes, GlobalMiddleware)\n *\n * const program = Effect.acquireUseRelease(\n *   Effect.sync(() => HttpRouter.toWebHandler(App, { disableLogger: true })),\n *   ({ handler }) =>\n *     Effect.gen(function*() {\n *       const response = yield* Effect.promise(() => handler(new Request(\"http://localhost/hello\")))\n *       return [response.headers.get(\"x-route\"), response.headers.get(\"x-global\")]\n *     }),\n *   ({ dispose }) => Effect.promise(dispose)\n * )\n *\n * await Effect.runPromise(program) // => [\"route\", \"global\"]\n * ```\n *\n * @category middleware\n * @since 4.0.0\n */\nexport const middleware = function () {\n  if (arguments.length === 0) {\n    return makeMiddleware;\n  }\n  return makeMiddleware(arguments[0], arguments[1]);\n};\nconst makeMiddleware = (middleware, options) => options?.global ? Layer.effectDiscard(Effect.gen(function* () {\n  const router = yield* HttpRouter;\n  const fn = Effect.isEffect(middleware) ? yield* middleware : middleware;\n  yield* router.addGlobalMiddleware(fn);\n})) : new MiddlewareImpl(Effect.isEffect(middleware) ? Layer.effectContext(Effect.map(middleware, fn => Context.makeUnsafe(new Map([[fnContextKey, fn]])))) : Layer.succeedContext(Context.makeUnsafe(new Map([[fnContextKey, middleware]]))));\nlet middlewareId = 0;\nconst fnContextKey = \"effect/http/HttpRouter/MiddlewareFn\";\nclass MiddlewareImpl {\n  [MiddlewareTypeId] = {};\n  layerFn;\n  dependencies;\n  constructor(layerFn, dependencies) {\n    this.layerFn = layerFn;\n    this.dependencies = dependencies;\n    const contextKey = `effect/http/HttpRouter/Middleware-${++middlewareId}`;\n    this.layer = Layer.effectContext(Effect.gen({\n      self: this\n    }, function* () {\n      const context = yield* Effect.context();\n      const stack = [context.mapUnsafe.get(fnContextKey)];\n      if (this.dependencies) {\n        const memoMap = yield* Layer.CurrentMemoMap;\n        const scope = Context.get(context, Scope.Scope);\n        const depsContext = yield* Layer.buildWithMemoMap(this.dependencies, memoMap, scope);\n        stack.push(...getMiddleware(depsContext));\n      }\n      return Context.makeUnsafe(new Map([[contextKey, stack]]));\n    })).pipe(Layer.provide(this.layerFn));\n  }\n  layer;\n  combine(other) {\n    return new MiddlewareImpl(this.layerFn, this.dependencies ? Layer.provideMerge(this.dependencies, other.layer) : other.layer);\n  }\n}\nconst middlewareCache = /*#__PURE__*/new WeakMap();\nconst getMiddleware = context => {\n  let arr = middlewareCache.get(context);\n  if (arr) return arr;\n  const topLevel = Arr.empty();\n  let maxLength = 0;\n  for (const [key, value] of context.mapUnsafe) {\n    if (key.startsWith(\"effect/http/HttpRouter/Middleware-\")) {\n      topLevel.push(value);\n      if (value.length > maxLength) {\n        maxLength = value.length;\n      }\n    }\n  }\n  if (topLevel.length === 0) {\n    arr = [];\n  } else {\n    const middleware = new Set();\n    for (let i = maxLength - 1; i >= 0; i--) {\n      for (const arr of topLevel) {\n        if (i < arr.length) {\n          middleware.add(arr[i]);\n        }\n      }\n    }\n    arr = Arr.fromIterable(middleware).reverse();\n  }\n  middlewareCache.set(context, arr);\n  return arr;\n};\n/**\n * Middleware that applies CORS headers to the HTTP response.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const cors = options => middleware(HttpMiddleware.cors(options), {\n  global: true\n});\n/**\n * Middleware that disables the logger for some routes.\n *\n * **Example** (Disabling route logging)\n *\n * ```ts import.meta.vitest\n * import { Layer } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n *\n * const Route = HttpRouter.add(\n *   \"GET\",\n *   \"/hello\",\n *   HttpServerResponse.text(\"Hello, World!\")\n * ).pipe(\n *   // disable the logger for this route\n *   Layer.provide(HttpRouter.disableLogger)\n * )\n * Layer.isLayer(Route) // => true\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const disableLogger = /*#__PURE__*/middleware(HttpMiddleware.withLoggerDisabled).layer;\n/**\n * Provides request-level dependencies to some routes.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const provideRequest = layer => self => Layer.provide(self, middleware()(Effect.gen(function* () {\n  const services = yield* Layer.build(layer);\n  return effect => Effect.provideContext(effect, services);\n})).layer);\n/**\n * Runs the provided application layer as an HTTP server.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const serve = (appLayer, options) => {\n  let middleware = options?.middleware;\n  if (options?.disableLogger !== true) {\n    middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger;\n  }\n  const RouterLayer = options?.routerConfig ? Layer.provide(layer, Layer.succeed(RouterConfig)(options.routerConfig)) : layer;\n  return Effect.gen(function* () {\n    const router = yield* HttpRouter;\n    const handler = router.asHttpEffect();\n    return middleware ? HttpServer.serve(handler, middleware) : HttpServer.serve(handler);\n  }).pipe(Layer.unwrap, Layer.provideMerge(appLayer), Layer.provide(RouterLayer), options?.disableListenLog ? identity : HttpServer.withLogAddress);\n};\n/**\n * Builds a Fetch-compatible request handler from an HTTP router application\n * layer.\n *\n * **Details**\n *\n * The result contains a `handler` function that converts Web `Request` values to\n * Web `Response` values and a `dispose` function for releasing the layer\n * resources.\n *\n * @category converting\n * @since 4.0.0\n */\nexport const toWebHandler = (appLayer, options) => {\n  let middleware = options?.middleware;\n  if (options?.disableLogger !== true) {\n    middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger;\n  }\n  const RouterLayer = options?.routerConfig ? Layer.provide(layer, Layer.succeed(RouterConfig)(options.routerConfig)) : layer;\n  return HttpEffect.toWebHandlerLayerWith(Layer.provideMerge(appLayer, RouterLayer), {\n    toHandler: s => Effect.succeed(Context.get(s, HttpRouter).asHttpEffect()),\n    middleware,\n    memoMap: options?.memoMap\n  });\n};\n//# sourceMappingURL=HttpRouter.js.map","/** @internal */\nexport function normalize(contentType) {\n  const normalized = contentType.toLowerCase().trim();\n  const index = normalized.indexOf(\";\");\n  return index === -1 ? normalized : normalized.slice(0, index).trim();\n}\n//# sourceMappingURL=mediaType.js.map","/**\n * Defines endpoint declarations used inside an HTTP API group.\n *\n * An endpoint records a stable identifier, HTTP method, router path, request schemas,\n * response schemas, declared errors, middleware, and annotations. Endpoint\n * values are declarations, not handlers: builders use them to decode requests,\n * type handler input, encode responses, generate OpenAPI metadata, and derive\n * generated-client call signatures. This module also includes HTTP method\n * constructors, payload and response schema helpers, and type utilities used by\n * builders and generated clients.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Context from \"../../Context.js\";\nimport { identity } from \"../../Function.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as AST from \"../../SchemaAST.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as HttpApiSchema from \"./HttpApiSchema.js\";\nimport * as MediaType from \"./internal/mediaType.js\";\nconst TypeId = \"~effect/httpapi/HttpApiEndpoint\";\n/**\n * Returns `true` when a value is an `HttpApiEndpoint`, narrowing the value to the\n * endpoint interface.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpApiEndpoint = u => Predicate.hasProperty(u, TypeId);\n/** @internal */\nexport function getPayloadSchemas(endpoint) {\n  const result = [];\n  for (const {\n    schemas\n  } of endpoint.payload.values()) {\n    result.push(...schemas);\n  }\n  return result;\n}\n/** @internal */\nexport function getSuccessSchemas(endpoint) {\n  const schemas = Array.from(endpoint.success);\n  return Arr.isArrayNonEmpty(schemas) ? schemas : [HttpApiSchema.NoContent];\n}\n/** @internal */\nexport function getErrorSchemas(endpoint) {\n  const schemas = new Set(endpoint.error);\n  for (const middleware of endpoint.middlewares) {\n    const key = middleware;\n    for (const schema of key.error) {\n      schemas.add(schema);\n    }\n  }\n  return Array.from(schemas);\n}\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments);\n  },\n  prefix(prefix) {\n    return makeProto({\n      ...optionsFromEndpoint(this),\n      path: HttpRouter.prefixPath(this.path, prefix)\n    });\n  },\n  middleware(middleware) {\n    return makeProto({\n      ...optionsFromEndpoint(this),\n      middlewares: new Set([...this.middlewares, middleware])\n    });\n  },\n  annotate(key, value) {\n    return makeProto({\n      ...optionsFromEndpoint(this),\n      annotations: Context.add(this.annotations, key, value)\n    });\n  },\n  annotateMerge(annotations) {\n    return makeProto({\n      ...optionsFromEndpoint(this),\n      annotations: Context.merge(this.annotations, annotations)\n    });\n  }\n};\nconst optionsFromEndpoint = endpoint => ({\n  identifier: endpoint.identifier,\n  path: endpoint.path,\n  method: endpoint.method,\n  params: endpoint.params,\n  query: endpoint.query,\n  headers: endpoint.headers,\n  payload: endpoint.payload,\n  success: endpoint.success,\n  error: endpoint.error,\n  annotations: endpoint.annotations,\n  middlewares: endpoint.middlewares\n});\nfunction makeProto(options) {\n  function HttpApiEndpoint() {}\n  Object.setPrototypeOf(HttpApiEndpoint, Proto);\n  return Object.assign(HttpApiEndpoint, options);\n}\n/**\n * Creates endpoint constructors for a specific HTTP method. The resulting\n * constructor builds an `HttpApiEndpoint` from an identifier, path, and optional request\n * and response schemas, applying automatic JSON or string-tree codecs unless\n * `disableCodecs` is enabled.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = method => (identifier, path, options) => {\n  const disableCodecs = options?.disableCodecs ?? false;\n  const transformStringTree = disableCodecs ? identity : Schema.toCodecStringTree;\n  return makeProto({\n    identifier,\n    path,\n    method,\n    params: ensureStruct(options?.params, transformStringTree),\n    query: ensureStruct(options?.query, transformStringTree),\n    headers: ensureStruct(options?.headers, transformStringTree),\n    payload: getPayload(options?.payload, method, disableCodecs),\n    success: getSuccessResponse(options?.success, method, disableCodecs),\n    error: getErrorResponse(options?.error, disableCodecs),\n    annotations: Context.empty(),\n    middlewares: new Set()\n  });\n};\nfunction ensureStruct(params, transform) {\n  if (params === undefined) return undefined;\n  if (Schema.isSchema(params)) return transform(params);\n  return transform(Schema.Struct(params));\n}\nfunction getPayload(payload, method, disableCodecs) {\n  const result = new Map();\n  if (payload === undefined) return result;\n  const schemas = Array.isArray(payload) ? payload : Schema.isSchema(payload) ? [payload] : [Schema.Struct(payload).pipe(HttpApiSchema.asFormUrlEncoded())];\n  const transform = disableCodecs ? identity : transformPayload;\n  for (const schema of schemas) {\n    const encoding = HttpApiSchema.getPayloadEncoding(schema.ast, method);\n    const contentType = MediaType.normalize(encoding.contentType);\n    const existing = result.get(contentType);\n    if (existing) {\n      if (existing.encoding._tag !== encoding._tag) {\n        throw new Error(`Multiple payload encodings for content-type: ${encoding.contentType}`);\n      }\n      if (existing.encoding._tag === \"Multipart\") {\n        throw new Error(`Multiple multipart payloads for content-type: ${encoding.contentType}`);\n      }\n      existing.schemas.push(transform(schema, method));\n    } else {\n      result.set(contentType, {\n        encoding,\n        schemas: [transform(schema, method)]\n      });\n    }\n  }\n  return result;\n}\nconst reservedStreamFailureEvent = \"effect/httpapi/stream/failure\";\nfunction getSuccessResponse(success, method, disableCodecs) {\n  if (success === undefined) return new Set();\n  const schemas = Arr.ensure(success);\n  validateSuccessResponse(schemas, method);\n  return new Set(disableCodecs ? schemas : schemas.map(schema => HttpApiSchema.isStreamSchema(schema) ? schema : transformResponse(schema)));\n}\nfunction getErrorResponse(error, disableCodecs) {\n  if (error === undefined) return new Set();\n  const schemas = Arr.ensure(error);\n  for (const schema of schemas) {\n    if (HttpApiSchema.isStreamSchema(schema)) {\n      throw new Error(\"Streaming schemas are not supported in error responses\");\n    }\n  }\n  return new Set(disableCodecs ? schemas : schemas.map(transformResponse));\n}\nfunction validateSuccessResponse(schemas, method) {\n  const statuses = new Map();\n  for (const schema of schemas) {\n    if (HttpApiSchema.isStreamSchema(schema)) {\n      validateStreamSuccess(schema, method);\n      const status = HttpApiSchema.getStatusStream(schema);\n      const entry = getStatusEntry(statuses, status);\n      if (entry.stream !== undefined) {\n        throw new Error(`Multiple streaming success responses for status: ${status}`);\n      }\n      if (entry.noContent) {\n        throw new Error(`Cannot combine no-content and streaming success responses for status: ${status}`);\n      }\n      if (entry.bufferedContentTypes.has(MediaType.normalize(schema.contentType))) {\n        throw new Error(`Cannot combine buffered and streaming success responses for status ${status} and content-type: ${schema.contentType}`);\n      }\n      statuses.set(status, {\n        ...entry,\n        stream: schema\n      });\n    } else {\n      const status = HttpApiSchema.getStatusSuccess(schema.ast);\n      const entry = getStatusEntry(statuses, status);\n      const noContent = HttpApiSchema.isNoContent(schema.ast);\n      if (entry.stream !== undefined) {\n        if (noContent) {\n          throw new Error(`Cannot combine no-content and streaming success responses for status: ${status}`);\n        }\n        const encoding = HttpApiSchema.getResponseEncoding(schema.ast);\n        if (MediaType.normalize(encoding.contentType) === MediaType.normalize(entry.stream.contentType)) {\n          throw new Error(`Cannot combine buffered and streaming success responses for status ${status} and content-type: ${encoding.contentType}`);\n        }\n      }\n      if (!noContent) {\n        entry.bufferedContentTypes.add(MediaType.normalize(HttpApiSchema.getResponseEncoding(schema.ast).contentType));\n      }\n      entry.noContent = entry.noContent || noContent;\n    }\n  }\n}\nfunction getStatusEntry(statuses, status) {\n  let entry = statuses.get(status);\n  if (entry === undefined) {\n    entry = {\n      bufferedContentTypes: new Set(),\n      noContent: false\n    };\n    statuses.set(status, entry);\n  }\n  return entry;\n}\nfunction validateStreamSuccess(schema, method) {\n  if (method === \"HEAD\") {\n    throw new Error(\"HEAD endpoints cannot declare streaming success responses\");\n  }\n  if (HttpApiSchema.isStreamSse(schema) && hasReservedSseEventName(schema.events.ast)) {\n    throw new Error(`SSE event name is reserved: ${reservedStreamFailureEvent}`);\n  }\n}\nfunction hasReservedSseEventName(ast) {\n  return hasReservedEventName(AST.toEncoded(ast), new Set());\n}\nfunction hasReservedEventName(ast, seen) {\n  if (seen.has(ast)) return false;\n  seen.add(ast);\n  if (AST.isUnion(ast)) {\n    return ast.types.some(type => hasReservedEventName(type, seen));\n  }\n  if (AST.isSuspend(ast)) {\n    return hasReservedEventName(ast.thunk(), seen);\n  }\n  if (!AST.isObjects(ast)) return false;\n  const event = ast.propertySignatures.find(ps => ps.name === \"event\");\n  return event !== undefined && hasReservedEventLiteral(event.type, seen);\n}\nfunction hasReservedEventLiteral(ast, seen) {\n  if (seen.has(ast)) return false;\n  seen.add(ast);\n  const encoded = AST.toEncoded(ast);\n  if (encoded !== ast) {\n    return hasReservedEventLiteral(encoded, seen);\n  }\n  if (AST.isLiteral(ast)) {\n    return ast.literal === reservedStreamFailureEvent;\n  }\n  if (AST.isUnion(ast)) {\n    return ast.types.some(type => hasReservedEventLiteral(type, seen));\n  }\n  if (AST.isSuspend(ast)) {\n    return hasReservedEventLiteral(ast.thunk(), seen);\n  }\n  return false;\n}\nfunction transformResponse(schema) {\n  const encoding = HttpApiSchema.getResponseEncoding(schema.ast);\n  switch (encoding._tag) {\n    case \"Json\":\n      return Schema.toCodecJson(schema);\n    case \"FormUrlEncoded\":\n      return Schema.toCodecStringTree(schema);\n    case \"Text\":\n    case \"Uint8Array\":\n      return schema;\n  }\n}\nfunction transformPayload(schema, method) {\n  const encoding = HttpApiSchema.getPayloadEncoding(schema.ast, method);\n  switch (encoding._tag) {\n    case \"Json\":\n      return Schema.toCodecJson(schema);\n    case \"FormUrlEncoded\":\n      return Schema.toCodecStringTree(schema);\n    case \"Text\":\n    case \"Uint8Array\":\n    case \"Multipart\":\n      return schema;\n  }\n}\n/**\n * Creates a `GET` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/make(\"GET\");\n/**\n * Creates a `POST` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const post = /*#__PURE__*/make(\"POST\");\n/**\n * Creates a `PUT` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const put = /*#__PURE__*/make(\"PUT\");\n/**\n * Creates a `PATCH` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const patch = /*#__PURE__*/make(\"PATCH\");\nconst del = /*#__PURE__*/make(\"DELETE\");\nexport {\n/**\n * Creates a `DELETE` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\ndel as delete };\n/**\n * Creates a `HEAD` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const head = /*#__PURE__*/make(\"HEAD\");\n/**\n * Creates an `OPTIONS` endpoint declaration.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const options = /*#__PURE__*/make(\"OPTIONS\");\n//# sourceMappingURL=HttpApiEndpoint.js.map","import * as Context from \"../../Context.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Record from \"../../Record.js\";\nimport * as HttpApiEndpoint from \"./HttpApiEndpoint.js\";\nimport * as HttpApiSchema from \"./HttpApiSchema.js\";\nconst TypeId = \"~effect/httpapi/HttpApi\";\n/**\n * Returns `true` when a value is an `HttpApi`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpApi = u => Predicate.hasProperty(u, TypeId);\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments);\n  },\n  add(...toAdd) {\n    const groups = {\n      ...this.groups\n    };\n    for (const group of toAdd) {\n      InternalRecord.assignProperty(groups, group.identifier, group);\n    }\n    return makeProto({\n      ...optionsFromApi(this),\n      groups\n    });\n  },\n  addHttpApi(api) {\n    const newGroups = {\n      ...this.groups\n    };\n    for (const key of Object.keys(api.groups)) {\n      const group = api.groups[key];\n      InternalRecord.assignProperty(newGroups, key, group.annotateMerge(Context.merge(api.annotations, group.annotations)));\n    }\n    return makeProto({\n      ...optionsFromApi(this),\n      groups: newGroups\n    });\n  },\n  prefix(prefix) {\n    return makeProto({\n      ...optionsFromApi(this),\n      groups: Record.map(this.groups, group => group.prefix(prefix))\n    });\n  },\n  middleware(tag) {\n    return makeProto({\n      ...optionsFromApi(this),\n      groups: Record.map(this.groups, group => group.middleware(tag))\n    });\n  },\n  annotate(key, value) {\n    return makeProto({\n      ...optionsFromApi(this),\n      annotations: Context.add(this.annotations, key, value)\n    });\n  },\n  annotateMerge(annotations) {\n    return makeProto({\n      ...optionsFromApi(this),\n      annotations: Context.merge(this.annotations, annotations)\n    });\n  }\n};\nconst optionsFromApi = api => ({\n  identifier: api.identifier,\n  groups: api.groups,\n  annotations: api.annotations\n});\nconst makeProto = options => {\n  function HttpApi() {}\n  Object.setPrototypeOf(HttpApi, Proto);\n  return Object.assign(HttpApi, options);\n};\n/**\n * Creates an empty `HttpApi` with the supplied identifier.\n *\n * **When to use**\n *\n * Use when you need to start defining an HTTP API, add groups with `add` or\n * `addHttpApi`, provide endpoint implementations with `HttpApiBuilder.group`,\n * and register the API with `HttpApiBuilder.layer`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = identifier => makeProto({\n  identifier,\n  groups: {},\n  annotations: Context.empty()\n});\n/**\n * Describes the groups and endpoints in an `HttpApi`.\n *\n * **Details**\n *\n * The callbacks receive each group or endpoint with merged annotations, endpoint\n * middleware, and response schemas grouped by HTTP status.\n *\n * @category reflection\n * @since 4.0.0\n */\nexport const reflect = (self, options) => {\n  const groups = Object.values(self.groups);\n  for (const group of groups) {\n    const groupAnnotations = Context.merge(self.annotations, group.annotations);\n    options.onGroup({\n      group,\n      mergedAnnotations: groupAnnotations\n    });\n    const endpoints = Object.values(group.endpoints);\n    for (const endpoint of endpoints) {\n      if (options.predicate && !options.predicate({\n        endpoint,\n        group\n      })) continue;\n      options.onEndpoint({\n        group,\n        endpoint,\n        middleware: endpoint.middlewares,\n        mergedAnnotations: Context.merge(groupAnnotations, endpoint.annotations),\n        successes: extractResponseContent(HttpApiEndpoint.getSuccessSchemas(endpoint), HttpApiSchema.getStatusSuccess),\n        errors: extractResponseContent(HttpApiEndpoint.getErrorSchemas(endpoint), HttpApiSchema.getStatusError)\n      });\n    }\n  }\n};\n// -------------------------------------------------------------------------------------\nconst extractResponseContent = (schemas, getStatus) => {\n  const map = new Map();\n  schemas.forEach(add);\n  return map;\n  function add(schema) {\n    if (HttpApiSchema.isStreamSchema(schema)) return;\n    const ast = schema.ast;\n    const status = getStatus(ast);\n    const schemas = map.get(status);\n    if (schemas === undefined) {\n      map.set(status, [schema]);\n    } else {\n      schemas.push(schema);\n    }\n  }\n};\n/**\n * Adds additional schemas to components/schemas.\n * The provided schemas must have a `identifier` annotation.\n *\n * @category services\n * @since 4.0.0\n */\nexport class AdditionalSchemas extends /*#__PURE__*/Context.Service()(\"effect/httpapi/HttpApi/AdditionalSchemas\") {}\n//# sourceMappingURL=HttpApi.js.map","import * as Context from \"../../Context.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Record from \"../../Record.js\";\nconst TypeId = \"~effect/httpapi/HttpApiGroup\";\n/**\n * Returns `true` when a value is an `HttpApiGroup`, narrowing the value to the\n * group interface.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpApiGroup = u => Predicate.hasProperty(u, TypeId);\nconst Proto = {\n  [TypeId]: TypeId,\n  add(...toAdd) {\n    const endpoints = {\n      ...this.endpoints\n    };\n    for (const endpoint of toAdd) {\n      InternalRecord.assignProperty(endpoints, endpoint.identifier, endpoint);\n    }\n    return makeProto({\n      ...optionsFromGroup(this),\n      endpoints\n    });\n  },\n  prefix(prefix) {\n    return makeProto({\n      ...optionsFromGroup(this),\n      endpoints: Record.map(this.endpoints, endpoint => endpoint.prefix(prefix))\n    });\n  },\n  middleware(middleware) {\n    return makeProto({\n      ...optionsFromGroup(this),\n      endpoints: Record.map(this.endpoints, endpoint => endpoint.middleware(middleware))\n    });\n  },\n  annotateMerge(annotations) {\n    return makeProto({\n      ...optionsFromGroup(this),\n      annotations: Context.merge(this.annotations, annotations)\n    });\n  },\n  annotate(annotation, value) {\n    return makeProto({\n      ...optionsFromGroup(this),\n      annotations: Context.add(this.annotations, annotation, value)\n    });\n  },\n  annotateEndpointsMerge(annotations) {\n    return makeProto({\n      ...optionsFromGroup(this),\n      endpoints: Record.map(this.endpoints, endpoint => endpoint.annotateMerge(annotations))\n    });\n  },\n  annotateEndpoints(annotation, value) {\n    return makeProto({\n      ...optionsFromGroup(this),\n      endpoints: Record.map(this.endpoints, endpoint => endpoint.annotate(annotation, value))\n    });\n  },\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\nconst optionsFromGroup = group => ({\n  identifier: group.identifier,\n  topLevel: group.topLevel,\n  endpoints: group.endpoints,\n  annotations: group.annotations\n});\nconst makeProto = options => {\n  function HttpApiGroup() {}\n  Object.setPrototypeOf(HttpApiGroup, Proto);\n  HttpApiGroup.key = `effect/httpapi/HttpApiGroup/${options.identifier}`;\n  return Object.assign(HttpApiGroup, options);\n};\n/**\n * Creates an empty `HttpApiGroup` with the supplied identifier.\n *\n * **Details**\n *\n * Add endpoints with `add`, provide implementations with `HttpApiBuilder.group`,\n * and set `topLevel` when the generated client should expose endpoint methods\n * directly instead of nesting them under the group identifier.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (identifier, options) => makeProto({\n  identifier,\n  topLevel: options?.topLevel ?? false,\n  endpoints: {},\n  annotations: Context.empty()\n});\n//# sourceMappingURL=HttpApiGroup.js.map","/**\n * Built-in error schemas for common HTTP API failure responses.\n *\n * This module provides reusable `Schema.ErrorClass` values for common HTTP\n * status codes, plus `HttpApiSchemaError` for request decoding failures raised\n * by the HTTP API runtime. The status errors can be used in endpoint or\n * middleware error declarations and are understood by builders, generated\n * clients, reflection, and OpenAPI generation.\n *\n * @since 4.0.0\n */\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as ErrorReporter from \"../../ErrorReporter.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as HttpServerRespondable from \"../http/HttpServerRespondable.js\";\nimport * as HttpServerResponse from \"../http/HttpServerResponse.js\";\nimport * as HttpApiSchema from \"./HttpApiSchema.js\";\nconst badRequestResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 400\n});\nconst unauthorizedResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 401\n});\nconst forbiddenResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 403\n});\nconst notFoundResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 404\n});\nconst methodNotAllowedResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 405\n});\nconst notAcceptableResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 406\n});\nconst requestTimeoutResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 408\n});\nconst conflictResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 409\n});\nconst goneResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 410\n});\nconst unprocessableEntityResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 422\n});\nconst internalServerErrorResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 500\n});\nconst notImplementedResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 501\n});\nconst serviceUnavailableResponse = /*#__PURE__*/HttpServerResponse.empty({\n  status: 503\n});\n/**\n * Built-in HTTP API error for a `400 Bad Request` response. When used directly as\n * a server response, it renders as an empty response with status 400.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class BadRequest extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/BadRequest\")({\n  _tag: /*#__PURE__*/Schema.tag(\"BadRequest\")\n}, {\n  description: \"BadRequest\",\n  httpApiStatus: 400\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(badRequestResponse);\n  }\n  static singleton = /*#__PURE__*/new BadRequest();\n}\n/**\n * No-content schema variant for `BadRequest`, decoding an empty 400 response into\n * a `BadRequest` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const BadRequestNoContent = /*#__PURE__*/BadRequest.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new BadRequest({})\n}));\n/**\n * Built-in HTTP API error for a `401 Unauthorized` response. When used directly as\n * a server response, it renders as an empty response with status 401.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class Unauthorized extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/Unauthorized\")({\n  _tag: /*#__PURE__*/Schema.tag(\"Unauthorized\")\n}, {\n  description: \"Unauthorized\",\n  httpApiStatus: 401\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(unauthorizedResponse);\n  }\n}\n/**\n * No-content schema variant for `Unauthorized`, decoding an empty 401 response\n * into an `Unauthorized` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const UnauthorizedNoContent = /*#__PURE__*/Unauthorized.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new Unauthorized({})\n}));\n/**\n * Built-in HTTP API error for a `403 Forbidden` response. When used directly as a\n * server response, it renders as an empty response with status 403.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class Forbidden extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/Forbidden\")({\n  _tag: /*#__PURE__*/Schema.tag(\"Forbidden\")\n}, {\n  description: \"Forbidden\",\n  httpApiStatus: 403\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(forbiddenResponse);\n  }\n}\n/**\n * No-content schema variant for `Forbidden`, decoding an empty 403 response into a\n * `Forbidden` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ForbiddenNoContent = /*#__PURE__*/Forbidden.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new Forbidden({})\n}));\n/**\n * Built-in HTTP API error for a `404 Not Found` response. When used directly as a\n * server response, it renders as an empty response with status 404.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class NotFound extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/NotFound\")({\n  _tag: /*#__PURE__*/Schema.tag(\"NotFound\")\n}, {\n  description: \"NotFound\",\n  httpApiStatus: 404\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(notFoundResponse);\n  }\n}\n/**\n * No-content schema variant for `NotFound`, decoding an empty 404 response into a\n * `NotFound` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const NotFoundNoContent = /*#__PURE__*/NotFound.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new NotFound({})\n}));\n/**\n * Built-in HTTP API error for a `405 Method Not Allowed` response. When used\n * directly as a server response, it renders as an empty response with status 405.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MethodNotAllowed extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/MethodNotAllowed\")({\n  _tag: /*#__PURE__*/Schema.tag(\"MethodNotAllowed\")\n}, {\n  description: \"MethodNotAllowed\",\n  httpApiStatus: 405\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(methodNotAllowedResponse);\n  }\n}\n/**\n * No-content schema variant for `MethodNotAllowed`, decoding an empty 405 response\n * into a `MethodNotAllowed` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const MethodNotAllowedNoContent = /*#__PURE__*/MethodNotAllowed.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new MethodNotAllowed({})\n}));\n/**\n * Built-in HTTP API error for a `406 Not Acceptable` response. When used directly\n * as a server response, it renders as an empty response with status 406.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class NotAcceptable extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/NotAcceptable\")({\n  _tag: /*#__PURE__*/Schema.tag(\"NotAcceptable\")\n}, {\n  description: \"NotAcceptable\",\n  httpApiStatus: 406\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(notAcceptableResponse);\n  }\n}\n/**\n * No-content schema variant for `NotAcceptable`, decoding an empty 406 response\n * into a `NotAcceptable` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const NotAcceptableNoContent = /*#__PURE__*/NotAcceptable.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new NotAcceptable({})\n}));\n/**\n * Built-in HTTP API error for a `408 Request Timeout` response. When used directly\n * as a server response, it renders as an empty response with status 408.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class RequestTimeout extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/RequestTimeout\")({\n  _tag: /*#__PURE__*/Schema.tag(\"RequestTimeout\")\n}, {\n  description: \"RequestTimeout\",\n  httpApiStatus: 408\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(requestTimeoutResponse);\n  }\n}\n/**\n * No-content schema variant for `RequestTimeout`, decoding an empty 408 response\n * into a `RequestTimeout` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const RequestTimeoutNoContent = /*#__PURE__*/RequestTimeout.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new RequestTimeout({})\n}));\n/**\n * Built-in HTTP API error for a `409 Conflict` response. When used directly as a\n * server response, it renders as an empty response with status 409.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class Conflict extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/Conflict\")({\n  _tag: /*#__PURE__*/Schema.tag(\"Conflict\")\n}, {\n  description: \"Conflict\",\n  httpApiStatus: 409\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(conflictResponse);\n  }\n}\n/**\n * No-content schema variant for `Conflict`, decoding an empty 409 response into a\n * `Conflict` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ConflictNoContent = /*#__PURE__*/Conflict.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new Conflict({})\n}));\n/**\n * Built-in HTTP API error for a `410 Gone` response. When used directly as a\n * server response, it renders as an empty response with status 410.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class Gone extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/Gone\")({\n  _tag: /*#__PURE__*/Schema.tag(\"Gone\")\n}, {\n  description: \"Gone\",\n  httpApiStatus: 410\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(goneResponse);\n  }\n}\n/**\n * No-content schema variant for `Gone`, decoding an empty 410 response into a\n * `Gone` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const GoneNoContent = /*#__PURE__*/Gone.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new Gone({})\n}));\n/**\n * Built-in HTTP API error for a `422 Unprocessable Entity` response. When used\n * directly as a server response, it renders as an empty response with status 422.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class UnprocessableEntity extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/UnprocessableEntity\")({\n  _tag: /*#__PURE__*/Schema.tag(\"UnprocessableEntity\")\n}, {\n  description: \"UnprocessableEntity\",\n  httpApiStatus: 422\n}) {\n  [ErrorReporter.ignore] = true;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(unprocessableEntityResponse);\n  }\n}\n/**\n * No-content schema variant for `UnprocessableEntity`, decoding an empty 422\n * response into an `UnprocessableEntity` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const UnprocessableEntityNoContent = /*#__PURE__*/UnprocessableEntity.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new UnprocessableEntity({})\n}));\n/**\n * Built-in HTTP API error for a `500 Internal Server Error` response. When used\n * directly as a server response, it renders as an empty response with status 500.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class InternalServerError extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/InternalServerError\")({\n  _tag: /*#__PURE__*/Schema.tag(\"InternalServerError\")\n}, {\n  description: \"InternalServerError\",\n  httpApiStatus: 500\n}) {\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(internalServerErrorResponse);\n  }\n}\n/**\n * No-content schema variant for `InternalServerError`, decoding an empty 500\n * response into an `InternalServerError` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const InternalServerErrorNoContent = /*#__PURE__*/InternalServerError.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new InternalServerError({})\n}));\n/**\n * Built-in HTTP API error for a `501 Not Implemented` response. When used directly\n * as a server response, it renders as an empty response with status 501.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class NotImplemented extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/NotImplemented\")({\n  _tag: /*#__PURE__*/Schema.tag(\"NotImplemented\")\n}, {\n  description: \"NotImplemented\",\n  httpApiStatus: 501\n}) {\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(notImplementedResponse);\n  }\n}\n/**\n * No-content schema variant for `NotImplemented`, decoding an empty 501 response\n * into a `NotImplemented` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const NotImplementedNoContent = /*#__PURE__*/NotImplemented.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new NotImplemented({})\n}));\n/**\n * Built-in HTTP API error for a `503 Service Unavailable` response. When used\n * directly as a server response, it renders as an empty response with status 503.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class ServiceUnavailable extends /*#__PURE__*/Schema.ErrorClass(\"effect/HttpApiError/ServiceUnavailable\")({\n  _tag: /*#__PURE__*/Schema.tag(\"ServiceUnavailable\")\n}, {\n  description: \"ServiceUnavailable\",\n  httpApiStatus: 503\n}) {\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(serviceUnavailableResponse);\n  }\n}\n/**\n * No-content schema variant for `ServiceUnavailable`, decoding an empty 503\n * response into a `ServiceUnavailable` error value.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ServiceUnavailableNoContent = /*#__PURE__*/ServiceUnavailable.pipe(/*#__PURE__*/HttpApiSchema.asNoContent({\n  decode: () => new ServiceUnavailable({})\n}));\n/**\n * Runtime identifier used to mark and detect `HttpApiSchemaError` values.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const HttpApiSchemaErrorTypeId = \"~effect/httpapi/HttpApiError/HttpApiSchemaError\";\n/**\n * Error raised when an HTTP API request component fails schema decoding. It records\n * which component failed and responds as an empty `400 Bad Request` when rendered\n * as a server response.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class HttpApiSchemaError extends /*#__PURE__*/Data.TaggedClass(\"HttpApiSchemaError\") {\n  [HttpApiSchemaErrorTypeId] = HttpApiSchemaErrorTypeId;\n  static is(u) {\n    return hasProperty(u, HttpApiSchemaErrorTypeId);\n  }\n  static wrap(kind, effect) {\n    return Effect.mapError(effect, error => new HttpApiSchemaError({\n      kind,\n      cause: error\n    }));\n  }\n  name = \"HttpApiSchemaError\";\n  message = this.kind;\n  [HttpServerRespondable.symbol]() {\n    return Effect.succeed(badRequestResponse);\n  }\n}\n//# sourceMappingURL=HttpApiError.js.map","/**\n * Declares middleware for schema-driven HTTP APIs.\n *\n * HTTP API middleware wraps endpoint execution on the server and, when the API\n * requires it, can also wrap requests made by generated clients. It is used for\n * cross-cutting behavior that belongs to the API contract, such as\n * authentication, authorization, logging, tracing, rate limiting,\n * request-scoped services, schema-error handling, and client request\n * decoration. This module defines the middleware service keys and helpers used\n * by `HttpApi` declarations.\n *\n * @since 4.0.0\n */\n/** @effect-diagnostics floatingEffect:skip-file */\n/** @effect-diagnostics classSelfMismatch:off */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"../../internal/stackTraceLimit.js\";\nimport * as Layer from \"../../Layer.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport { Scope } from \"../../Scope.js\";\nimport { HttpApiSchemaError } from \"./HttpApiError.js\";\nconst TypeId = \"~effect/httpapi/HttpApiMiddleware\";\nconst SecurityTypeId = \"~effect/httpapi/HttpApiMiddleware/Security\";\n/**\n * Returns `true` when an HTTP API middleware service is security middleware.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isSecurity = u => hasProperty(u, SecurityTypeId);\n/**\n * Creates a `Context.Service` class for an HTTP API middleware implementation.\n *\n * **When to use**\n *\n * Use when you need an HTTP API middleware service whose configuration declares\n * required services, provided services, typed error schemas, security schemes,\n * client errors, or a matching client middleware requirement.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const Service = () => (id, options) => {\n  const Err = globalThis.Error;\n  const limit = getStackTraceLimit();\n  setStackTraceLimit(2);\n  const creationError = new Err();\n  setStackTraceLimit(limit);\n  class Service extends Context.Service()(id) {}\n  const self = Service;\n  Object.defineProperty(Service, \"stack\", {\n    get() {\n      return creationError.stack;\n    }\n  });\n  self[TypeId] = TypeId;\n  self.error = getError(options?.error);\n  self.requiredForClient = options?.requiredForClient ?? false;\n  if (options?.security !== undefined) {\n    if (Object.keys(options.security).length === 0) {\n      throw new Error(\"HttpApiMiddleware.Service: security object must not be empty\");\n    }\n    self[SecurityTypeId] = SecurityTypeId;\n    self.security = options.security;\n  }\n  return self;\n};\nfunction getError(error) {\n  if (error === undefined) return new Set();\n  return new Set(Array.isArray(error) ? error : [error]);\n}\n/**\n * Creates a middleware layer that transforms `HttpApiSchemaError` failures.\n *\n * **Details**\n *\n * The middleware catches schema errors produced while running an endpoint and uses\n * the supplied `transform` function to convert them into the middleware's declared\n * error schema.\n *\n * **Example** (Mapping schema errors to custom errors)\n *\n * ```ts import.meta.vitest\n * import { Effect, Schema, type Types } from \"effect\"\n * import { HttpRouter, HttpServerResponse } from \"effect/unstable/http\"\n * import {\n *   HttpApiEndpoint,\n *   HttpApiError,\n *   HttpApiGroup,\n *   HttpApiMiddleware\n * } from \"effect/unstable/httpapi\"\n *\n * class CustomError extends Schema.TaggedErrorClass<CustomError>()(\"CustomError\", {}) {}\n *\n * class ErrorHandler extends HttpApiMiddleware.Service<ErrorHandler>()(\"api/ErrorHandler\", {\n *   error: CustomError\n * }) {}\n *\n * const messages: Array<string> = []\n * const ErrorHandlerLayer = HttpApiMiddleware.layerSchemaErrorTransform(\n *   ErrorHandler,\n *   (schemaError) =>\n *     Effect.sync(() => messages.push(`Mapping ${schemaError.kind} schema error`)).pipe(\n *       Effect.andThen(Effect.fail(new CustomError()))\n *     )\n * )\n *\n * const endpoint = HttpApiEndpoint.get(\"example\", \"/\")\n * const group = HttpApiGroup.make(\"examples\").add(endpoint)\n * const middlewareContext = {\n *   endpoint: endpoint as unknown as HttpApiEndpoint.Top,\n *   group: group as unknown as HttpApiGroup.Top\n * }\n * const Routes = HttpRouter.add(\n *   \"GET\",\n *   \"/\",\n *   Effect.gen(function*() {\n *     const applySchemaErrorTransform = yield* ErrorHandler\n *     const schemaError = yield* HttpApiError.HttpApiSchemaError.wrap(\n *       \"Body\",\n *       Schema.decodeUnknownEffect(Schema.String)(42)\n *     ).pipe(Effect.flip)\n *     const failingResponse = Effect.fail(schemaError as unknown as Types.unhandled)\n *     const result = yield* applySchemaErrorTransform(failingResponse, middlewareContext).pipe(\n *       Effect.match({\n *         onFailure: (error) => error instanceof CustomError ? error._tag : \"UnexpectedError\",\n *         onSuccess: () => \"Success\"\n *       })\n *     )\n *     return HttpServerResponse.text(result)\n *   })\n * ).pipe(HttpRouter.provideRequest(ErrorHandlerLayer))\n *\n * const program = Effect.acquireUseRelease(\n *   Effect.sync(() => HttpRouter.toWebHandler(Routes, { disableLogger: true })),\n *   ({ handler }) =>\n *     Effect.gen(function*() {\n *       const response = yield* Effect.promise(() => handler(new Request(\"http://localhost/\")))\n *       const body = yield* Effect.promise(() => response.text())\n *       return body\n *     }),\n *   ({ dispose }) => Effect.promise(dispose)\n * )\n *\n * const body = await Effect.runPromise(program)\n * const result = [messages, body] // => [[\"Mapping Body schema error\"], \"CustomError\"]\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerSchemaErrorTransform = (service, transform) => Layer.succeed(service, (httpEffect, options) => Effect.catch(httpEffect, e => HttpApiSchemaError.is(e) ? transform(e, options) : Effect.fail(e)));\n/**\n * Provides a client-side middleware implementation for a middleware that is required by generated clients.\n *\n * **Details**\n *\n * The layer captures the surrounding services and makes the middleware available\n * through the `ForClient` service marker used by HTTP API clients.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerClient = (tag, service) => Layer.effectContext(Effect.gen(function* () {\n  const services = (yield* Effect.context()).pipe(Context.omit(Scope));\n  const middleware = Effect.isEffect(service) ? yield* service : service;\n  return Context.makeUnsafe(new Map([[`${tag.key}/Client`, options => Effect.updateContext(middleware(options), requestContext => Context.merge(services, requestContext))]]));\n}));\n//# sourceMappingURL=HttpApiMiddleware.js.map","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { ProviderDriverKind } from \"./providerInstance.ts\";\n\nexport const ProviderOptionDescriptorType = Schema.Literals([\"select\", \"boolean\"]);\nexport type ProviderOptionDescriptorType = typeof ProviderOptionDescriptorType.Type;\n\nexport const ProviderOptionChoice = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n  isDefault: Schema.optional(Schema.Boolean),\n});\nexport type ProviderOptionChoice = typeof ProviderOptionChoice.Type;\n\nconst ProviderOptionDescriptorBase = {\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n} as const;\n\nexport const SelectProviderOptionDescriptor = Schema.Struct({\n  ...ProviderOptionDescriptorBase,\n  type: Schema.Literal(\"select\"),\n  options: Schema.Array(ProviderOptionChoice),\n  currentValue: Schema.optional(TrimmedNonEmptyString),\n  promptInjectedValues: Schema.optional(Schema.Array(TrimmedNonEmptyString)),\n});\nexport type SelectProviderOptionDescriptor = typeof SelectProviderOptionDescriptor.Type;\n\nexport const BooleanProviderOptionDescriptor = Schema.Struct({\n  ...ProviderOptionDescriptorBase,\n  type: Schema.Literal(\"boolean\"),\n  currentValue: Schema.optional(Schema.Boolean),\n});\nexport type BooleanProviderOptionDescriptor = typeof BooleanProviderOptionDescriptor.Type;\n\nexport const ProviderOptionDescriptor = Schema.Union([\n  SelectProviderOptionDescriptor,\n  BooleanProviderOptionDescriptor,\n]);\nexport type ProviderOptionDescriptor = typeof ProviderOptionDescriptor.Type;\n\nexport const ProviderOptionSelectionValue = Schema.Union([TrimmedNonEmptyString, Schema.Boolean]);\nexport type ProviderOptionSelectionValue = typeof ProviderOptionSelectionValue.Type;\n\nexport const ProviderOptionSelection = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  value: ProviderOptionSelectionValue,\n});\nexport type ProviderOptionSelection = typeof ProviderOptionSelection.Type;\n\n/**\n * Legacy on-disk shape for provider option selections, kept readable by the\n * decoder so we can tolerate stored data written before the v3 array shape.\n *\n * Persisted historically as `{ effort: \"max\", fastMode: true, ... }` inside\n * `modelSelection.options`. Migration 026 rewrites stored rows to the\n * canonical array shape, but we still see the legacy form in:\n *   - `settings.json` files from older client builds,\n *   - SQLite databases that have not yet run migration 026,\n *   - any future regression that re-introduces the legacy shape.\n */\nconst LegacyProviderOptionSelectionsObject = Schema.Record(Schema.String, Schema.Unknown);\n\nconst ProviderOptionSelectionsFromLegacyObject = LegacyProviderOptionSelectionsObject.pipe(\n  Schema.decodeTo(\n    Schema.Array(ProviderOptionSelection),\n    SchemaTransformation.transformOrFail({\n      decode: (record) => Effect.succeed(coerceLegacyOptionsObjectToArray(record)),\n      encode: (selections) => Effect.succeed(canonicalSelectionsToLegacyObject(selections)),\n    }),\n  ),\n);\n\n/**\n * Schema for the `options` field of every `ModelSelection` variant.\n *\n * Accepts both:\n *   - the canonical array shape `Array<{ id, value }>` (preferred), and\n *   - the legacy object shape `Record<string, string | boolean | …>` from\n *     pre-migration data.\n *\n * Always normalizes to the canonical array on decode and re-encodes as the\n * canonical array, so any legacy storage gets cleaned up the next time the\n * containing record is written back.\n */\nexport const ProviderOptionSelections = Schema.Union([\n  Schema.Array(ProviderOptionSelection),\n  ProviderOptionSelectionsFromLegacyObject,\n]);\nexport type ProviderOptionSelections = typeof ProviderOptionSelections.Type;\n\nfunction coerceLegacyOptionsObjectToArray(\n  record: Record<string, unknown>,\n): ReadonlyArray<ProviderOptionSelection> {\n  const entries: Array<ProviderOptionSelection> = [];\n  for (const [rawKey, rawValue] of Object.entries(record)) {\n    const id = typeof rawKey === \"string\" ? rawKey.trim() : \"\";\n    if (id.length === 0) continue;\n    if (typeof rawValue === \"string\") {\n      const trimmed = rawValue.trim();\n      if (trimmed.length > 0) entries.push({ id, value: trimmed });\n    } else if (typeof rawValue === \"boolean\") {\n      entries.push({ id, value: rawValue });\n    }\n    // Drop anything else (numbers, null, nested objects/arrays) to match the\n    // permissive normalization performed by migration 026.\n  }\n  return entries;\n}\n\nfunction canonicalSelectionsToLegacyObject(\n  selections: ReadonlyArray<ProviderOptionSelection>,\n): Record<string, string | boolean> {\n  const out: Record<string, string | boolean> = {};\n  for (const { id, value } of selections) {\n    out[id] = value;\n  }\n  return out;\n}\n\nexport const ModelCapabilities = Schema.Struct({\n  optionDescriptors: Schema.optional(Schema.Array(ProviderOptionDescriptor)),\n});\nexport type ModelCapabilities = typeof ModelCapabilities.Type;\n\nconst CODEX_DRIVER_KIND = ProviderDriverKind.make(\"codex\");\nconst CLAUDE_DRIVER_KIND = ProviderDriverKind.make(\"claudeAgent\");\nconst GEMINI_DRIVER_KIND = ProviderDriverKind.make(\"gemini\");\nconst QWEN_DRIVER_KIND = ProviderDriverKind.make(\"qwen\");\nconst KIMI_DRIVER_KIND = ProviderDriverKind.make(\"kimi\");\nconst JOYCODE_DRIVER_KIND = ProviderDriverKind.make(\"joycode\");\n\nexport const DEFAULT_MODEL = \"gpt-5.6-sol\";\n\n/**\n * Codex default-model preference, most preferred first. The provider snapshot\n * marks the first of these present in the live `model/list` response as\n * default; when none are available, Codex's own `isDefault` flag wins.\n */\nexport const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [\n  \"gpt-5.6-sol\",\n  \"gpt-5.6-terra\",\n];\nexport const DEFAULT_TEXT_GENERATION_MODEL = \"gpt-5.6-luna\";\nexport const DEFAULT_TEXT_GENERATION_REASONING_EFFORT = \"low\";\n\nexport const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {\n  [CODEX_DRIVER_KIND]: DEFAULT_MODEL,\n  [CLAUDE_DRIVER_KIND]: \"claude-sonnet-5\",\n  [GEMINI_DRIVER_KIND]: \"gemini-2.5-pro\",\n  [QWEN_DRIVER_KIND]: \"qwen3-coder-plus\",\n  [KIMI_DRIVER_KIND]: \"kimi-k2\",\n  [JOYCODE_DRIVER_KIND]: \"default\",\n};\n\n/** Per-provider text generation model defaults. */\nexport const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<\n  Record<ProviderDriverKind, string>\n> = {\n  [CODEX_DRIVER_KIND]: DEFAULT_TEXT_GENERATION_MODEL,\n  [CLAUDE_DRIVER_KIND]: \"claude-haiku-4-5\",\n  [GEMINI_DRIVER_KIND]: \"gemini-2.5-flash\",\n  [QWEN_DRIVER_KIND]: \"qwen3-coder-flash\",\n  [KIMI_DRIVER_KIND]: \"kimi-k2\",\n  [JOYCODE_DRIVER_KIND]: \"default\",\n};\n\nexport const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<\n  Record<ProviderDriverKind, Record<string, string>>\n> = {\n  [CODEX_DRIVER_KIND]: {\n    \"gpt-5-codex\": \"gpt-5.4\",\n    \"5.4\": \"gpt-5.4\",\n    \"5.3\": \"gpt-5.3-codex\",\n    \"gpt-5.3\": \"gpt-5.3-codex\",\n    \"5.3-spark\": \"gpt-5.3-codex-spark\",\n    \"gpt-5.3-spark\": \"gpt-5.3-codex-spark\",\n  },\n  [CLAUDE_DRIVER_KIND]: {\n    opus: \"claude-opus-5\",\n    \"opus-5\": \"claude-opus-5\",\n    \"claude-opus-5.0\": \"claude-opus-5\",\n    \"claude-opus-5-0\": \"claude-opus-5\",\n    \"opus-4.8\": \"claude-opus-4-8\",\n    \"claude-opus-4.8\": \"claude-opus-4-8\",\n    \"opus-4.7\": \"claude-opus-4-7\",\n    \"claude-opus-4.7\": \"claude-opus-4-7\",\n    \"opus-4.6\": \"claude-opus-4-6\",\n    \"claude-opus-4.6\": \"claude-opus-4-6\",\n    \"claude-opus-4-6-20251117\": \"claude-opus-4-6\",\n    sonnet: \"claude-sonnet-5\",\n    \"sonnet-5\": \"claude-sonnet-5\",\n    \"claude-sonnet-5.0\": \"claude-sonnet-5\",\n    \"claude-sonnet-5-0\": \"claude-sonnet-5\",\n    \"sonnet-4.6\": \"claude-sonnet-4-6\",\n    \"claude-sonnet-4.6\": \"claude-sonnet-4-6\",\n    \"claude-sonnet-4-6-20251117\": \"claude-sonnet-4-6\",\n    haiku: \"claude-haiku-4-5\",\n    \"haiku-4.5\": \"claude-haiku-4-5\",\n    \"claude-haiku-4.5\": \"claude-haiku-4-5\",\n    \"claude-haiku-4-5-20251001\": \"claude-haiku-4-5\",\n  },\n  [GEMINI_DRIVER_KIND]: {},\n  [QWEN_DRIVER_KIND]: {},\n  [KIMI_DRIVER_KIND]: {},\n  [JOYCODE_DRIVER_KIND]: {},\n};\n\n// ── Provider display names ────────────────────────────────────────────\n\nexport const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>> = {\n  [CODEX_DRIVER_KIND]: \"Codex\",\n  [CLAUDE_DRIVER_KIND]: \"Claude\",\n  [GEMINI_DRIVER_KIND]: \"Gemini CLI\",\n  [QWEN_DRIVER_KIND]: \"Qwen Code\",\n  [KIMI_DRIVER_KIND]: \"Kimi CLI\",\n  [JOYCODE_DRIVER_KIND]: \"JoyCode\",\n};\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Struct from \"effect/Struct\";\nimport { ProviderOptionSelections } from \"./model.ts\";\nimport { RepositoryIdentity } from \"./environment.ts\";\nimport {\n  ApprovalRequestId,\n  CheckpointRef,\n  CommandId,\n  EventId,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  ProjectId,\n  ProviderItemId,\n  ThreadId,\n  TrimmedNonEmptyString,\n  TrimmedString,\n  TurnId,\n} from \"./baseSchemas.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\n\nexport const ORCHESTRATION_WS_METHODS = {\n  dispatchCommand: \"orchestration.dispatchCommand\",\n  getWorkflowScript: \"orchestration.getWorkflowScript\",\n  getTurnDiff: \"orchestration.getTurnDiff\",\n  getFullThreadDiff: \"orchestration.getFullThreadDiff\",\n  searchThreads: \"orchestration.searchThreads\",\n  getArchivedShellSnapshot: \"orchestration.getArchivedShellSnapshot\",\n  subscribeShell: \"orchestration.subscribeShell\",\n  subscribeThread: \"orchestration.subscribeThread\",\n} as const;\n\nexport const ProviderApprovalPolicy = Schema.Literals([\n  \"untrusted\",\n  \"on-failure\",\n  \"on-request\",\n  \"never\",\n]);\nexport type ProviderApprovalPolicy = typeof ProviderApprovalPolicy.Type;\nexport const ProviderSandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\nexport type ProviderSandboxMode = typeof ProviderSandboxMode.Type;\n\n/**\n * `ModelSelection` — selection of a model on a configured provider instance.\n *\n * The routing key is `instanceId` (a user-defined slug identifying one\n * configured provider instance). Drivers, credentials, working-directory\n * bindings, and any other per-instance state are recovered from the\n * runtime registry via the instance id.\n *\n * Wire legacy: persisted selections produced before the driver/instance\n * split carried a `provider: <driver-id>` field instead. The schema absorbs\n * that shape via a pre-decoding transform — `{provider, model}` is promoted\n * to `{instanceId: defaultInstanceIdForDriver(provider), model}`. No\n * post-decode compatibility code lives in the runtime; the transform is the\n * only compat surface.\n */\nconst ModelSelectionWire = Schema.Struct({\n  instanceId: ProviderInstanceId,\n  model: TrimmedNonEmptyString,\n  options: Schema.optionalKey(ProviderOptionSelections),\n});\n\n// Source shape for persisted legacy payloads. Fields are typed as\n// `Schema.Unknown` so malformed drafts still make it into the transform and\n// fail validation through the target schema (with proper error messages)\n// rather than at the source-struct layer where the error is less actionable.\nconst ModelSelectionSource = Schema.Struct({\n  provider: Schema.optional(Schema.Unknown),\n  instanceId: Schema.optional(Schema.Unknown),\n  model: Schema.Unknown,\n  options: Schema.optional(Schema.Unknown),\n});\n\nexport const ModelSelection = ModelSelectionSource.pipe(\n  Schema.decodeTo(\n    ModelSelectionWire,\n    SchemaTransformation.transformOrFail({\n      decode: (raw) => {\n        // Resolve the routing key: prefer an explicit `instanceId`; fall\n        // back to promoting the legacy `provider` slug (the canonical\n        // `defaultInstanceIdForDriver` mapping) so persisted rollout-era\n        // payloads decode without data loss. The target schema brands the\n        // string as `ProviderInstanceId`.\n        const instanceIdSource =\n          raw.instanceId !== undefined\n            ? raw.instanceId\n            : typeof raw.provider === \"string\"\n              ? raw.provider\n              : undefined;\n        const base: Record<string, unknown> = {\n          instanceId: instanceIdSource,\n          model: raw.model,\n        };\n        if (raw.options !== undefined) base.options = raw.options;\n        return Effect.succeed(base as typeof ModelSelectionWire.Encoded);\n      },\n      encode: (value) => {\n        const base: Record<string, unknown> = {\n          model: value.model,\n          instanceId: value.instanceId,\n        };\n        if (value.options !== undefined) base.options = value.options;\n        return Effect.succeed(base as typeof ModelSelectionSource.Encoded);\n      },\n    }),\n  ),\n);\nexport type ModelSelection = typeof ModelSelection.Type;\n\nexport const RuntimeMode = Schema.Literals([\n  \"approval-required\",\n  \"auto-accept-edits\",\n  \"auto\",\n  \"full-access\",\n]);\nexport type RuntimeMode = typeof RuntimeMode.Type;\nexport const DEFAULT_RUNTIME_MODE: RuntimeMode = \"full-access\";\nexport const ProviderInteractionMode = Schema.Literals([\"default\", \"plan\"]);\nexport type ProviderInteractionMode = typeof ProviderInteractionMode.Type;\nexport const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = \"default\";\nexport const ProviderRequestKind = Schema.Literals([\"command\", \"file-read\", \"file-change\"]);\nexport type ProviderRequestKind = typeof ProviderRequestKind.Type;\nexport const AssistantDeliveryMode = Schema.Literals([\"buffered\", \"streaming\"]);\nexport type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type;\nexport const ProviderApprovalDecision = Schema.Literals([\n  \"accept\",\n  \"acceptForSession\",\n  \"decline\",\n  \"cancel\",\n]);\nexport type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type;\nexport const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown);\nexport type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;\n\nexport const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;\nexport const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;\nexport const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;\nconst PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;\nconst CHAT_ATTACHMENT_ID_MAX_CHARS = 128;\n// Correlation id is command id by design in this model.\nexport const CorrelationId = CommandId;\nexport type CorrelationId = typeof CorrelationId.Type;\n\nconst ChatAttachmentId = TrimmedNonEmptyString.check(\n  Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS),\n  Schema.isPattern(/^[a-z0-9_-]+$/i),\n);\nexport type ChatAttachmentId = typeof ChatAttachmentId.Type;\n\nexport const ChatImageAttachment = Schema.Struct({\n  type: Schema.Literal(\"image\"),\n  id: ChatAttachmentId,\n  name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),\n  mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\\//i)),\n  sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),\n});\nexport type ChatImageAttachment = typeof ChatImageAttachment.Type;\n\nconst UploadChatImageAttachment = Schema.Struct({\n  type: Schema.Literal(\"image\"),\n  name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),\n  mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\\//i)),\n  sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),\n  dataUrl: TrimmedNonEmptyString.check(\n    Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),\n  ),\n});\nexport type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;\n\nexport const ChatAttachment = Schema.Union([ChatImageAttachment]);\nexport type ChatAttachment = typeof ChatAttachment.Type;\nconst UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);\nexport type UploadChatAttachment = typeof UploadChatAttachment.Type;\n\nexport const ProjectScriptIcon = Schema.Literals([\n  \"play\",\n  \"test\",\n  \"lint\",\n  \"configure\",\n  \"build\",\n  \"debug\",\n]);\nexport type ProjectScriptIcon = typeof ProjectScriptIcon.Type;\n\nexport const ProjectScript = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  name: TrimmedNonEmptyString,\n  command: TrimmedNonEmptyString,\n  icon: ProjectScriptIcon,\n  runOnWorktreeCreate: Schema.Boolean,\n  /**\n   * URL to open in the in-app browser preview when this script runs (or\n   * when the user explicitly requests a preview). Optional; only honored on\n   * the desktop build.\n   */\n  previewUrl: Schema.optional(TrimmedNonEmptyString),\n  /**\n   * When true, automatically open the preview panel pointed at `previewUrl`\n   * the moment this script starts. Ignored without `previewUrl` or on web.\n   */\n  autoOpenPreview: Schema.optional(Schema.Boolean),\n});\nexport type ProjectScript = typeof ProjectScript.Type;\n\nexport const OrchestrationProject = Schema.Struct({\n  id: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  deletedAt: Schema.NullOr(IsoDateTime),\n});\nexport type OrchestrationProject = typeof OrchestrationProject.Type;\n\nexport const OrchestrationMessageRole = Schema.Literals([\"user\", \"assistant\", \"system\"]);\nexport type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;\n\nexport const OrchestrationMessage = Schema.Struct({\n  id: MessageId,\n  role: OrchestrationMessageRole,\n  text: Schema.String,\n  attachments: Schema.optional(Schema.Array(ChatAttachment)),\n  turnId: Schema.NullOr(TurnId),\n  streaming: Schema.Boolean,\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationMessage = typeof OrchestrationMessage.Type;\n\nexport const OrchestrationProposedPlanId = TrimmedNonEmptyString;\nexport type OrchestrationProposedPlanId = typeof OrchestrationProposedPlanId.Type;\n\nexport const OrchestrationProposedPlan = Schema.Struct({\n  id: OrchestrationProposedPlanId,\n  turnId: Schema.NullOr(TurnId),\n  planMarkdown: TrimmedNonEmptyString,\n  implementedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  implementationThreadId: Schema.NullOr(ThreadId).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationProposedPlan = typeof OrchestrationProposedPlan.Type;\n\nconst SourceProposedPlanReference = Schema.Struct({\n  threadId: ThreadId,\n  planId: OrchestrationProposedPlanId,\n});\n\nexport const OrchestrationSessionStatus = Schema.Literals([\n  \"idle\",\n  \"starting\",\n  \"running\",\n  \"ready\",\n  \"interrupted\",\n  \"stopped\",\n  \"error\",\n]);\nexport type OrchestrationSessionStatus = typeof OrchestrationSessionStatus.Type;\n\nexport const OrchestrationSession = Schema.Struct({\n  threadId: ThreadId,\n  status: OrchestrationSessionStatus,\n  providerName: Schema.NullOr(TrimmedNonEmptyString),\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  activeTurnId: Schema.NullOr(TurnId),\n  lastError: Schema.NullOr(TrimmedNonEmptyString),\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationSession = typeof OrchestrationSession.Type;\n\nexport const OrchestrationCheckpointFile = Schema.Struct({\n  path: TrimmedNonEmptyString,\n  kind: TrimmedNonEmptyString,\n  additions: NonNegativeInt,\n  deletions: NonNegativeInt,\n});\nexport type OrchestrationCheckpointFile = typeof OrchestrationCheckpointFile.Type;\n\nexport const OrchestrationCheckpointStatus = Schema.Literals([\"ready\", \"missing\", \"error\"]);\nexport type OrchestrationCheckpointStatus = typeof OrchestrationCheckpointStatus.Type;\n\nexport const OrchestrationCheckpointSummary = Schema.Struct({\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\nexport type OrchestrationCheckpointSummary = typeof OrchestrationCheckpointSummary.Type;\n\nexport const OrchestrationThreadActivityTone = Schema.Literals([\n  \"info\",\n  \"tool\",\n  \"approval\",\n  \"error\",\n]);\nexport type OrchestrationThreadActivityTone = typeof OrchestrationThreadActivityTone.Type;\n\nexport const OrchestrationThreadActivity = Schema.Struct({\n  id: EventId,\n  tone: OrchestrationThreadActivityTone,\n  kind: TrimmedNonEmptyString,\n  summary: TrimmedNonEmptyString,\n  payload: Schema.Unknown,\n  turnId: Schema.NullOr(TurnId),\n  sequence: Schema.optional(NonNegativeInt),\n  createdAt: IsoDateTime,\n});\nexport type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;\n\nconst OrchestrationLatestTurnState = Schema.Literals([\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"error\",\n]);\nexport type OrchestrationLatestTurnState = typeof OrchestrationLatestTurnState.Type;\n\nexport const OrchestrationLatestTurn = Schema.Struct({\n  turnId: TurnId,\n  state: OrchestrationLatestTurnState,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  assistantMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n});\nexport type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;\n\nexport const ThreadTitleRegeneration = Schema.Struct({\n  requestId: CommandId,\n  startedAt: IsoDateTime,\n});\nexport type ThreadTitleRegeneration = typeof ThreadTitleRegeneration.Type;\n\nexport const OrchestrationThread = Schema.Struct({\n  id: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  latestTurn: Schema.NullOr(OrchestrationLatestTurn),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  settledOverride: Schema.NullOr(Schema.Literals([\"settled\", \"active\"])).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n  settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  // Snooze is an overlay on the active lifecycle, not a fourth destination:\n  // a snoozed thread stays \"active\" in the model and is only suppressed from\n  // the inbox until snoozedUntil passes (or the thread raises its hand).\n  // Optional so payloads from pre-snooze servers still decode.\n  snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),\n  snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  // A pin overrides the settled/snoozed lifecycle: while pinnedAt is set the\n  // thread renders in the pinned block and never classifies into a shelf.\n  // Optional so payloads from pre-pinning servers still decode.\n  pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  // Pending-only state. Optional so older servers remain compatible.\n  titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),\n  deletedAt: Schema.NullOr(IsoDateTime),\n  messages: Schema.Array(OrchestrationMessage),\n  proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(\n    Schema.withDecodingDefault(Effect.succeed([])),\n  ),\n  activities: Schema.Array(OrchestrationThreadActivity),\n  checkpoints: Schema.Array(OrchestrationCheckpointSummary),\n  session: Schema.NullOr(OrchestrationSession),\n});\nexport type OrchestrationThread = typeof OrchestrationThread.Type;\n\nexport const OrchestrationReadModel = Schema.Struct({\n  snapshotSequence: NonNegativeInt,\n  projects: Schema.Array(OrchestrationProject),\n  threads: Schema.Array(OrchestrationThread),\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationReadModel = typeof OrchestrationReadModel.Type;\n\nexport const OrchestrationProjectShell = Schema.Struct({\n  id: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;\n\nexport const OrchestrationThreadShell = Schema.Struct({\n  id: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  latestTurn: Schema.NullOr(OrchestrationLatestTurn),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  settledOverride: Schema.NullOr(Schema.Literals([\"settled\", \"active\"])).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n  settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),\n  snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),\n  session: Schema.NullOr(OrchestrationSession),\n  latestUserMessageAt: Schema.NullOr(IsoDateTime),\n  hasPendingApprovals: Schema.Boolean,\n  hasPendingUserInput: Schema.Boolean,\n  hasActionableProposedPlan: Schema.Boolean,\n  /**\n   * Native background work alive after the turn settles: \"working\" while\n   * subagents/workflows run, \"monitoring\" when watch loops are the only\n   * live work. Optional so old servers/clients interop; absent = none.\n   */\n  backgroundLiveness: Schema.optional(Schema.NullOr(Schema.Literals([\"working\", \"monitoring\"]))),\n});\nexport type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;\n\nexport const OrchestrationShellSnapshot = Schema.Struct({\n  snapshotSequence: NonNegativeInt,\n  projects: Schema.Array(OrchestrationProjectShell),\n  threads: Schema.Array(OrchestrationThreadShell),\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationShellSnapshot = typeof OrchestrationShellSnapshot.Type;\n\nexport const OrchestrationShellStreamEvent = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"project-upserted\"),\n    sequence: NonNegativeInt,\n    project: OrchestrationProjectShell,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"project-removed\"),\n    sequence: NonNegativeInt,\n    projectId: ProjectId,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"thread-upserted\"),\n    sequence: NonNegativeInt,\n    thread: OrchestrationThreadShell,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"thread-removed\"),\n    sequence: NonNegativeInt,\n    threadId: ThreadId,\n  }),\n]);\nexport type OrchestrationShellStreamEvent = typeof OrchestrationShellStreamEvent.Type;\n\nexport const OrchestrationShellStreamItem = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"synchronized\"),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"snapshot\"),\n    snapshot: OrchestrationShellSnapshot,\n  }),\n  OrchestrationShellStreamEvent,\n]);\nexport type OrchestrationShellStreamItem = typeof OrchestrationShellStreamItem.Type;\n\nexport const OrchestrationSubscribeShellInput = Schema.Struct({\n  /**\n   * When provided, the server skips the initial full shell snapshot and instead\n   * replays shell events after this sequence before streaming live events.\n   * Clients that already hold a cached (or HTTP-loaded) shell snapshot pass its\n   * sequence here so the subscription resumes without re-sending the entire\n   * projects/threads list (overlapping events are deduped by sequence on the\n   * client).\n   */\n  afterSequence: Schema.optionalKey(NonNegativeInt),\n  /**\n   * Requests an explicit marker after the subscription has emitted its initial\n   * snapshot or catch-up replay and before it begins emitting live events.\n   */\n  requestCompletionMarker: Schema.optionalKey(Schema.Boolean),\n});\nexport type OrchestrationSubscribeShellInput = typeof OrchestrationSubscribeShellInput.Type;\n\nexport const OrchestrationSubscribeThreadInput = Schema.Struct({\n  threadId: ThreadId,\n  /**\n   * When provided, the server skips the initial snapshot frame and instead\n   * replays events after this sequence before streaming live events. Clients\n   * that load the snapshot over HTTP pass the snapshot's sequence here so the\n   * live subscription resumes without a gap (overlapping events are deduped by\n   * sequence on the client).\n   */\n  afterSequence: Schema.optionalKey(NonNegativeInt),\n  /**\n   * Requests an explicit marker after the subscription has emitted its initial\n   * snapshot or catch-up replay and before it begins emitting live events.\n   */\n  requestCompletionMarker: Schema.optionalKey(Schema.Boolean),\n});\nexport type OrchestrationSubscribeThreadInput = typeof OrchestrationSubscribeThreadInput.Type;\n\nexport const OrchestrationThreadDetailSnapshot = Schema.Struct({\n  snapshotSequence: NonNegativeInt,\n  thread: OrchestrationThread,\n});\nexport type OrchestrationThreadDetailSnapshot = typeof OrchestrationThreadDetailSnapshot.Type;\n\nexport const ProjectCreateCommand = Schema.Struct({\n  type: Schema.Literal(\"project.create\"),\n  commandId: CommandId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean),\n  defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),\n  createdAt: IsoDateTime,\n});\n\nconst ProjectMetaUpdateCommand = Schema.Struct({\n  type: Schema.Literal(\"project.meta.update\"),\n  commandId: CommandId,\n  projectId: ProjectId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  workspaceRoot: Schema.optional(TrimmedNonEmptyString),\n  defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),\n  scripts: Schema.optional(Schema.Array(ProjectScript)),\n});\n\nconst ProjectDeleteCommand = Schema.Struct({\n  type: Schema.Literal(\"project.delete\"),\n  commandId: CommandId,\n  projectId: ProjectId,\n  force: Schema.optional(Schema.Boolean),\n});\n\nconst ThreadCreateCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.create\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadDeleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.delete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadArchiveCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.archive\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadUnarchiveCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unarchive\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadSettleCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.settle\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadUnsettleCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unsettle\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // Commands only carry \"user\": activity un-settles are decided server-side\n  // (the decider emits thread.unsettled(reason: \"activity\") events directly,\n  // never through this command), so a client cannot forge the neutral reset.\n  reason: Schema.Literal(\"user\"),\n});\n\nconst ThreadSnoozeCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.snooze\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // The wake time. Event-based wake conditions (PR merged, review posted)\n  // will arrive as an optional condition field alongside this; time-based\n  // snooze is just the first kind of condition.\n  snoozedUntil: IsoDateTime,\n});\n\nconst ThreadUnsnoozeCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unsnooze\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // Commands only carry \"user\": activity wakes are decided server-side (the\n  // decider emits thread.unsnoozed(reason: \"activity\") directly), and timer\n  // wakes need no event at all — clients derive visibility from snoozedUntil,\n  // so a passed wake time simply stops classifying as snoozed.\n  reason: Schema.Literal(\"user\"),\n});\n\nconst ThreadPinCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.pin\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadUnpinCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unpin\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadMetaUpdateCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.meta.update\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  regenerateTitle: Schema.optional(Schema.Literal(true)),\n  modelSelection: Schema.optional(ModelSelection),\n  branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n}).check(\n  Schema.makeFilter(\n    (input) =>\n      !(input.title !== undefined && input.regenerateTitle === true) ||\n      \"title and regenerateTitle cannot be specified together\",\n  ),\n);\n\nconst ThreadRuntimeModeSetCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.runtime-mode.set\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  runtimeMode: RuntimeMode,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadInteractionModeSetCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.interaction-mode.set\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  interactionMode: ProviderInteractionMode,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnStartBootstrapCreateThread = Schema.Struct({\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode,\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnStartBootstrapPrepareWorktree = Schema.Struct({\n  projectCwd: TrimmedNonEmptyString,\n  baseBranch: TrimmedNonEmptyString,\n  branch: Schema.optional(TrimmedNonEmptyString),\n  startFromOrigin: Schema.optional(Schema.Boolean),\n});\n\nconst ThreadTurnStartBootstrap = Schema.Struct({\n  createThread: Schema.optional(ThreadTurnStartBootstrapCreateThread),\n  prepareWorktree: Schema.optional(ThreadTurnStartBootstrapPrepareWorktree),\n  runSetupScript: Schema.optional(Schema.Boolean),\n});\n\nexport type ThreadTurnStartBootstrap = typeof ThreadTurnStartBootstrap.Type;\n\nexport const ThreadTurnStartCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.start\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  message: Schema.Struct({\n    messageId: MessageId,\n    role: Schema.Literal(\"user\"),\n    text: Schema.String,\n    attachments: Schema.Array(ChatAttachment),\n  }),\n  modelSelection: Schema.optional(ModelSelection),\n  titleSeed: Schema.optional(TrimmedNonEmptyString),\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  bootstrap: Schema.optional(ThreadTurnStartBootstrap),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n  createdAt: IsoDateTime,\n});\n\nconst ClientThreadTurnStartCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.start\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  message: Schema.Struct({\n    messageId: MessageId,\n    role: Schema.Literal(\"user\"),\n    text: Schema.String,\n    attachments: Schema.Array(UploadChatAttachment),\n  }),\n  modelSelection: Schema.optional(ModelSelection),\n  titleSeed: Schema.optional(TrimmedNonEmptyString),\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode,\n  bootstrap: Schema.optional(ThreadTurnStartBootstrap),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnInterruptCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.interrupt\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadApprovalRespondCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.approval.respond\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  decision: ProviderApprovalDecision,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadUserInputRespondCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.user-input.respond\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  answers: ProviderUserInputAnswers,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadCheckpointRevertCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.checkpoint.revert\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadSessionStopCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.session.stop\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n});\n\nconst DispatchableClientOrchestrationCommand = Schema.Union([\n  ProjectCreateCommand,\n  ProjectMetaUpdateCommand,\n  ProjectDeleteCommand,\n  ThreadCreateCommand,\n  ThreadDeleteCommand,\n  ThreadArchiveCommand,\n  ThreadUnarchiveCommand,\n  ThreadSettleCommand,\n  ThreadUnsettleCommand,\n  ThreadSnoozeCommand,\n  ThreadUnsnoozeCommand,\n  ThreadPinCommand,\n  ThreadUnpinCommand,\n  ThreadMetaUpdateCommand,\n  ThreadRuntimeModeSetCommand,\n  ThreadInteractionModeSetCommand,\n  ThreadTurnStartCommand,\n  ThreadTurnInterruptCommand,\n  ThreadApprovalRespondCommand,\n  ThreadUserInputRespondCommand,\n  ThreadCheckpointRevertCommand,\n  ThreadSessionStopCommand,\n]);\nexport type DispatchableClientOrchestrationCommand =\n  typeof DispatchableClientOrchestrationCommand.Type;\n\nexport const ClientOrchestrationCommand = Schema.Union([\n  ProjectCreateCommand,\n  ProjectMetaUpdateCommand,\n  ProjectDeleteCommand,\n  ThreadCreateCommand,\n  ThreadDeleteCommand,\n  ThreadArchiveCommand,\n  ThreadUnarchiveCommand,\n  ThreadSettleCommand,\n  ThreadUnsettleCommand,\n  ThreadSnoozeCommand,\n  ThreadUnsnoozeCommand,\n  ThreadPinCommand,\n  ThreadUnpinCommand,\n  ThreadMetaUpdateCommand,\n  ThreadRuntimeModeSetCommand,\n  ThreadInteractionModeSetCommand,\n  ClientThreadTurnStartCommand,\n  ThreadTurnInterruptCommand,\n  ThreadApprovalRespondCommand,\n  ThreadUserInputRespondCommand,\n  ThreadCheckpointRevertCommand,\n  ThreadSessionStopCommand,\n]);\nexport type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;\n\nconst ThreadSessionSetCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.session.set\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  session: OrchestrationSession,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadMessageUserImportCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.message.user.import\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  messageId: MessageId,\n  turnId: TurnId,\n  text: Schema.String,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadMessageAssistantDeltaCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.message.assistant.delta\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  messageId: MessageId,\n  delta: Schema.String,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadMessageAssistantCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.message.assistant.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  messageId: MessageId,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadProposedPlanUpsertCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.proposed-plan.upsert\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  proposedPlan: OrchestrationProposedPlan,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnDiffCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.diff.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnId: TurnId,\n  completedAt: IsoDateTime,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.optional(MessageId),\n  checkpointTurnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadActivityAppendCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.activity.append\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  activity: OrchestrationThreadActivity,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadRevertCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.revert.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTitleRegenerationCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.title.regeneration.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  requestId: CommandId,\n  title: Schema.optional(TrimmedNonEmptyString),\n});\n\nconst InternalOrchestrationCommand = Schema.Union([\n  ThreadSessionSetCommand,\n  ThreadMessageUserImportCommand,\n  ThreadMessageAssistantDeltaCommand,\n  ThreadMessageAssistantCompleteCommand,\n  ThreadProposedPlanUpsertCommand,\n  ThreadTurnDiffCompleteCommand,\n  ThreadActivityAppendCommand,\n  ThreadRevertCompleteCommand,\n  ThreadTitleRegenerationCompleteCommand,\n]);\nexport type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;\n\nexport const OrchestrationCommand = Schema.Union([\n  DispatchableClientOrchestrationCommand,\n  InternalOrchestrationCommand,\n]);\nexport type OrchestrationCommand = typeof OrchestrationCommand.Type;\n\nexport const OrchestrationEventType = Schema.Literals([\n  \"project.created\",\n  \"project.meta-updated\",\n  \"project.deleted\",\n  \"thread.created\",\n  \"thread.deleted\",\n  \"thread.archived\",\n  \"thread.unarchived\",\n  \"thread.settled\",\n  \"thread.unsettled\",\n  \"thread.snoozed\",\n  \"thread.unsnoozed\",\n  \"thread.pinned\",\n  \"thread.unpinned\",\n  \"thread.meta-updated\",\n  \"thread.runtime-mode-set\",\n  \"thread.interaction-mode-set\",\n  \"thread.message-sent\",\n  \"thread.turn-start-requested\",\n  \"thread.turn-interrupt-requested\",\n  \"thread.approval-response-requested\",\n  \"thread.user-input-response-requested\",\n  \"thread.checkpoint-revert-requested\",\n  \"thread.reverted\",\n  \"thread.session-stop-requested\",\n  \"thread.session-set\",\n  \"thread.proposed-plan-upserted\",\n  \"thread.turn-diff-completed\",\n  \"thread.activity-appended\",\n]);\nexport type OrchestrationEventType = typeof OrchestrationEventType.Type;\n\nexport const OrchestrationAggregateKind = Schema.Literals([\"project\", \"thread\"]);\nexport type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;\nexport const OrchestrationActorKind = Schema.Literals([\"client\", \"server\", \"provider\"]);\n\nexport const ProjectCreatedPayload = Schema.Struct({\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ProjectMetaUpdatedPayload = Schema.Struct({\n  projectId: ProjectId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  workspaceRoot: Schema.optional(TrimmedNonEmptyString),\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),\n  scripts: Schema.optional(Schema.Array(ProjectScript)),\n  updatedAt: IsoDateTime,\n});\n\nexport const ProjectDeletedPayload = Schema.Struct({\n  projectId: ProjectId,\n  deletedAt: IsoDateTime,\n});\n\nexport const ThreadCreatedPayload = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadDeletedPayload = Schema.Struct({\n  threadId: ThreadId,\n  deletedAt: IsoDateTime,\n});\n\nexport const ThreadArchivedPayload = Schema.Struct({\n  threadId: ThreadId,\n  archivedAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnarchivedPayload = Schema.Struct({\n  threadId: ThreadId,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadSettledPayload = Schema.Struct({\n  threadId: ThreadId,\n  settledAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnsettledPayload = Schema.Struct({\n  threadId: ThreadId,\n  reason: Schema.Literals([\"user\", \"activity\"]),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadSnoozedPayload = Schema.Struct({\n  threadId: ThreadId,\n  snoozedUntil: IsoDateTime,\n  snoozedAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnsnoozedPayload = Schema.Struct({\n  threadId: ThreadId,\n  // user: explicit \"wake now\". activity: real work arrived (user message /\n  // session coming alive) and the decider cleared the snooze — mirrors\n  // thread.unsettled's activity resets. Timer wakes emit no event: clients\n  // derive them from snoozedUntil passing.\n  reason: Schema.Literals([\"user\", \"activity\"]),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadPinnedPayload = Schema.Struct({\n  threadId: ThreadId,\n  pinnedAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnpinnedPayload = Schema.Struct({\n  threadId: ThreadId,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadMetaUpdatedPayload = Schema.Struct({\n  threadId: ThreadId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  /** Intent marker consumed by the title-generation reactor. Keeping this on\n      the existing event lets older clients safely ignore the new field. */\n  regenerateTitle: Schema.optional(Schema.Literal(true)),\n  /** Title at request time, used to avoid overwriting a later manual rename. */\n  previousTitle: Schema.optional(TrimmedNonEmptyString),\n  /** Pending state shared with clients. Null clears a matching request. */\n  titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),\n  modelSelection: Schema.optional(ModelSelection),\n  branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadRuntimeModeSetPayload = Schema.Struct({\n  threadId: ThreadId,\n  runtimeMode: RuntimeMode,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadInteractionModeSetPayload = Schema.Struct({\n  threadId: ThreadId,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadMessageSentPayload = Schema.Struct({\n  threadId: ThreadId,\n  messageId: MessageId,\n  role: OrchestrationMessageRole,\n  text: Schema.String,\n  attachments: Schema.optional(Schema.Array(ChatAttachment)),\n  turnId: Schema.NullOr(TurnId),\n  streaming: Schema.Boolean,\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadTurnStartRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  messageId: MessageId,\n  modelSelection: Schema.optional(ModelSelection),\n  titleSeed: Schema.optional(TrimmedNonEmptyString),\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadTurnInterruptRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadApprovalResponseRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  decision: ProviderApprovalDecision,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadUserInputResponseRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  answers: ProviderUserInputAnswers,\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadCheckpointRevertRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadRevertedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n});\n\nexport const ThreadSessionStopRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadSessionSetPayload = Schema.Struct({\n  threadId: ThreadId,\n  session: OrchestrationSession,\n});\n\nexport const ThreadProposedPlanUpsertedPayload = Schema.Struct({\n  threadId: ThreadId,\n  proposedPlan: OrchestrationProposedPlan,\n});\n\nexport const ThreadTurnDiffCompletedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\n\nexport const ThreadActivityAppendedPayload = Schema.Struct({\n  threadId: ThreadId,\n  activity: OrchestrationThreadActivity,\n});\n\nexport const OrchestrationEventMetadata = Schema.Struct({\n  providerTurnId: Schema.optional(TrimmedNonEmptyString),\n  providerItemId: Schema.optional(ProviderItemId),\n  adapterKey: Schema.optional(TrimmedNonEmptyString),\n  requestId: Schema.optional(ApprovalRequestId),\n  ingestedAt: Schema.optional(IsoDateTime),\n});\nexport type OrchestrationEventMetadata = typeof OrchestrationEventMetadata.Type;\n\nconst EventBaseFields = {\n  sequence: NonNegativeInt,\n  eventId: EventId,\n  aggregateKind: OrchestrationAggregateKind,\n  aggregateId: Schema.Union([ProjectId, ThreadId]),\n  occurredAt: IsoDateTime,\n  commandId: Schema.NullOr(CommandId),\n  causationEventId: Schema.NullOr(EventId),\n  correlationId: Schema.NullOr(CommandId),\n  metadata: OrchestrationEventMetadata,\n} as const;\n\nexport const OrchestrationEvent = Schema.Union([\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"project.created\"),\n    payload: ProjectCreatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"project.meta-updated\"),\n    payload: ProjectMetaUpdatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"project.deleted\"),\n    payload: ProjectDeletedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.created\"),\n    payload: ThreadCreatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.deleted\"),\n    payload: ThreadDeletedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.archived\"),\n    payload: ThreadArchivedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unarchived\"),\n    payload: ThreadUnarchivedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.settled\"),\n    payload: ThreadSettledPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unsettled\"),\n    payload: ThreadUnsettledPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.snoozed\"),\n    payload: ThreadSnoozedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unsnoozed\"),\n    payload: ThreadUnsnoozedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.pinned\"),\n    payload: ThreadPinnedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unpinned\"),\n    payload: ThreadUnpinnedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.meta-updated\"),\n    payload: ThreadMetaUpdatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.runtime-mode-set\"),\n    payload: ThreadRuntimeModeSetPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.interaction-mode-set\"),\n    payload: ThreadInteractionModeSetPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.message-sent\"),\n    payload: ThreadMessageSentPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.turn-start-requested\"),\n    payload: ThreadTurnStartRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.turn-interrupt-requested\"),\n    payload: ThreadTurnInterruptRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.approval-response-requested\"),\n    payload: ThreadApprovalResponseRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.user-input-response-requested\"),\n    payload: ThreadUserInputResponseRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.checkpoint-revert-requested\"),\n    payload: ThreadCheckpointRevertRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.reverted\"),\n    payload: ThreadRevertedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.session-stop-requested\"),\n    payload: ThreadSessionStopRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.session-set\"),\n    payload: ThreadSessionSetPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.proposed-plan-upserted\"),\n    payload: ThreadProposedPlanUpsertedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.turn-diff-completed\"),\n    payload: ThreadTurnDiffCompletedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.activity-appended\"),\n    payload: ThreadActivityAppendedPayload,\n  }),\n]);\nexport type OrchestrationEvent = typeof OrchestrationEvent.Type;\n\nexport const OrchestrationThreadStreamItem = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"synchronized\"),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"snapshot\"),\n    snapshot: OrchestrationThreadDetailSnapshot,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"event\"),\n    event: OrchestrationEvent,\n  }),\n]);\nexport type OrchestrationThreadStreamItem = typeof OrchestrationThreadStreamItem.Type;\n\nexport const OrchestrationCommandReceiptStatus = Schema.Literals([\"accepted\", \"rejected\"]);\nexport type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type;\n\nexport const TurnCountRange = Schema.Struct({\n  fromTurnCount: NonNegativeInt,\n  toTurnCount: NonNegativeInt,\n}).check(\n  Schema.makeFilter(\n    (input) =>\n      input.fromTurnCount <= input.toTurnCount ||\n      new SchemaIssue.InvalidValue({\n        message: \"fromTurnCount must be less than or equal to toTurnCount\",\n      }),\n    { identifier: \"OrchestrationTurnDiffRange\" },\n  ),\n);\n\nexport const ThreadTurnDiff = TurnCountRange.mapFields(\n  Struct.assign({\n    threadId: ThreadId,\n    diff: Schema.String,\n  }),\n  { unsafePreserveChecks: true },\n);\n\nexport const ProviderSessionRuntimeStatus = Schema.Literals([\n  \"starting\",\n  \"running\",\n  \"stopped\",\n  \"error\",\n]);\nexport type ProviderSessionRuntimeStatus = typeof ProviderSessionRuntimeStatus.Type;\n\nconst ProjectionThreadTurnStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"interrupted\",\n  \"error\",\n]);\nexport type ProjectionThreadTurnStatus = typeof ProjectionThreadTurnStatus.Type;\n\nconst ProjectionCheckpointRow = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\nexport type ProjectionCheckpointRow = typeof ProjectionCheckpointRow.Type;\n\nexport const ProjectionPendingApprovalStatus = Schema.Literals([\"pending\", \"resolved\"]);\nexport type ProjectionPendingApprovalStatus = typeof ProjectionPendingApprovalStatus.Type;\n\nexport const ProjectionPendingApprovalDecision = Schema.NullOr(ProviderApprovalDecision);\nexport type ProjectionPendingApprovalDecision = typeof ProjectionPendingApprovalDecision.Type;\n\nexport const DispatchResult = Schema.Struct({\n  sequence: NonNegativeInt,\n});\nexport type DispatchResult = typeof DispatchResult.Type;\n\nexport const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(\n  Struct.assign({\n    threadId: ThreadId,\n    ignoreWhitespace: Schema.optionalKey(Schema.Boolean),\n  }),\n  { unsafePreserveChecks: true },\n);\nexport type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;\n\nexport const OrchestrationGetTurnDiffResult = ThreadTurnDiff;\nexport type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;\n\nexport const OrchestrationGetFullThreadDiffInput = Schema.Struct({\n  threadId: ThreadId,\n  toTurnCount: NonNegativeInt,\n  ignoreWhitespace: Schema.optionalKey(Schema.Boolean),\n});\nexport type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;\n\nexport const OrchestrationGetFullThreadDiffResult = ThreadTurnDiff;\nexport type OrchestrationGetFullThreadDiffResult = typeof OrchestrationGetFullThreadDiffResult.Type;\n\nexport const OrchestrationThreadSearchSource = Schema.Literals([\"user\", \"assistant\"]);\nexport type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSource.Type;\n\n// The server's SQLite client is synchronous and single-connection. Bound both\n// scan input and response size so a search cannot monopolize that connection.\nexport const OrchestrationSearchThreadsInput = Schema.Struct({\n  query: TrimmedString.check(Schema.isMinLength(2), Schema.isMaxLength(200)),\n  limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),\n});\nexport type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type;\n\nexport const OrchestrationThreadSearchMatch = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  source: OrchestrationThreadSearchSource,\n  snippet: Schema.String.check(Schema.isMaxLength(240)),\n  messageCreatedAt: Schema.NullOr(IsoDateTime),\n});\nexport type OrchestrationThreadSearchMatch = typeof OrchestrationThreadSearchMatch.Type;\n\nexport const OrchestrationSearchThreadsResult = Schema.Struct({\n  matches: Schema.Array(OrchestrationThreadSearchMatch),\n});\nexport type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;\n\nexport const OrchestrationGetWorkflowScriptInput = Schema.Struct({\n  threadId: ThreadId,\n  /** Absolute path from the workflow's runHandles.scriptPath. The server\n   * re-derives containment; the client value is a hint, never trusted. */\n  scriptPath: TrimmedNonEmptyString,\n});\nexport type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;\n\nexport const OrchestrationGetWorkflowScriptResult = Schema.Struct({\n  scriptPath: TrimmedNonEmptyString,\n  contents: Schema.String,\n  truncated: Schema.Boolean,\n});\nexport type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;\n\nconst WORKFLOW_SCRIPT_ERROR_MESSAGES = {\n  \"invalid-path\": \"Workflow scripts must be absolute .js paths.\",\n  \"root-unavailable\": \"Script root unavailable.\",\n  \"not-found\": \"Script not found.\",\n  \"outside-root\": \"Script path is outside the workflow scripts root.\",\n  \"not-js\": \"Resolved script is not a .js file.\",\n  \"not-regular-file\": \"Script is not a regular file.\",\n  \"changed-during-read\": \"Script changed between resolution and open.\",\n  \"read-failed\": \"Script read failed.\",\n} as const;\n\nexport class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(\n  \"OrchestrationGetWorkflowScriptError\",\n  {\n    reason: Schema.Literals([\n      \"invalid-path\",\n      \"root-unavailable\",\n      \"not-found\",\n      \"outside-root\",\n      \"not-js\",\n      \"not-regular-file\",\n      \"changed-during-read\",\n      \"read-failed\",\n    ]),\n    scriptPath: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return WORKFLOW_SCRIPT_ERROR_MESSAGES[this.reason];\n  }\n}\n\nexport const OrchestrationRpcSchemas = {\n  dispatchCommand: {\n    input: ClientOrchestrationCommand,\n    output: DispatchResult,\n  },\n  getWorkflowScript: {\n    input: OrchestrationGetWorkflowScriptInput,\n    output: OrchestrationGetWorkflowScriptResult,\n  },\n  getTurnDiff: {\n    input: OrchestrationGetTurnDiffInput,\n    output: OrchestrationGetTurnDiffResult,\n  },\n  getFullThreadDiff: {\n    input: OrchestrationGetFullThreadDiffInput,\n    output: OrchestrationGetFullThreadDiffResult,\n  },\n  searchThreads: {\n    input: OrchestrationSearchThreadsInput,\n    output: OrchestrationSearchThreadsResult,\n  },\n  getArchivedShellSnapshot: {\n    input: Schema.Struct({}),\n    output: OrchestrationShellSnapshot,\n  },\n  subscribeThread: {\n    input: OrchestrationSubscribeThreadInput,\n    output: OrchestrationThreadStreamItem,\n  },\n  subscribeShell: {\n    input: OrchestrationSubscribeShellInput,\n    output: OrchestrationShellStreamItem,\n  },\n} as const;\n\nexport class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass<OrchestrationGetSnapshotError>()(\n  \"OrchestrationGetSnapshotError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass<OrchestrationDispatchCommandError>()(\n  \"OrchestrationDispatchCommandError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<OrchestrationGetTurnDiffError>()(\n  \"OrchestrationGetTurnDiffError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(\n  \"OrchestrationGetFullThreadDiffError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationSearchThreadsError extends Schema.TaggedErrorClass<OrchestrationSearchThreadsError>()(\n  \"OrchestrationSearchThreadsError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n","/**\n * Defines security scheme declarations for declarative HTTP APIs.\n *\n * Security schemes describe where credentials are read from and which credential\n * type is passed to security middleware. They are consumed by\n * `HttpApiMiddleware.Service`, `HttpApiBuilder`, generated clients, and OpenAPI\n * generation, but they do not authenticate requests by themselves.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport { dual } from \"../../Function.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nconst TypeId = \"~effect/httpapi/HttpApiSecurity\";\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/**\n * Creates a Http token security scheme.\n *\n * **When to use**\n *\n * Use to require `Authorization: scheme ...` credentials for an HTTP API group\n * or endpoint.\n *\n * **Details**\n *\n * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this\n * security scheme.\n *\n * @see {@link apiKey} for an API-key security scheme\n * @see {@link basic} for an HTTP Basic security scheme\n * @category constructors\n * @since 4.0.0\n */\nexport const http = options => Object.assign(Object.create(Proto), {\n  _tag: \"Http\",\n  scheme: options.scheme,\n  schemeLength: options.scheme.length,\n  annotations: Context.empty()\n});\n/**\n * Creates a Bearer token security scheme.\n *\n * **When to use**\n *\n * Use to require `Authorization: Bearer ...` credentials for an HTTP API group\n * or endpoint.\n *\n * **Details**\n *\n * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this\n * security scheme.\n *\n * @see {@link apiKey} for an API-key security scheme\n * @see {@link basic} for an HTTP Basic security scheme\n * @category constructors\n * @since 4.0.0\n */\nexport const bearer = /*#__PURE__*/http({\n  scheme: \"Bearer\"\n});\n/**\n * Creates an API key security scheme.\n *\n * **When to use**\n *\n * Use to require API key credentials passed through a header, query parameter,\n * or cookie.\n *\n * **Details**\n *\n * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this\n * security scheme.\n *\n * Use `HttpApiBuilder.securitySetCookie` to set the correct cookie in a\n * handler. By default, `in` is `\"header\"`.\n *\n * @see {@link bearer} for a Bearer token security scheme\n * @see {@link basic} for an HTTP Basic security scheme\n * @category constructors\n * @since 4.0.0\n */\nexport const apiKey = options => Object.assign(Object.create(Proto), {\n  _tag: \"ApiKey\",\n  key: options.key,\n  in: options.in ?? \"header\",\n  annotations: Context.empty()\n});\n/**\n * Creates an HTTP Basic authentication security scheme.\n *\n * **When to use**\n *\n * Use to require HTTP Basic username/password credentials.\n *\n * **Details**\n *\n * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this\n * security scheme.\n *\n * @see {@link bearer} for a Bearer token security scheme\n * @see {@link apiKey} for an API-key security scheme\n * @category constructors\n * @since 4.0.0\n */\nexport const basic = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(Proto), {\n  _tag: \"Basic\",\n  annotations: /*#__PURE__*/Context.empty()\n});\n/**\n * Merges OpenAPI annotations into a security scheme.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const annotateMerge = /*#__PURE__*/dual(2, (self, annotations) => Object.assign(Object.create(Proto), {\n  ...self,\n  annotations: Context.merge(self.annotations, annotations)\n}));\n/**\n * Adds an OpenAPI annotation value to a security scheme.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const annotate = /*#__PURE__*/dual(3, (self, service, value) => Object.assign(Object.create(Proto), {\n  ...self,\n  annotations: Context.add(self.annotations, service, value)\n}));\n//# sourceMappingURL=HttpApiSecurity.js.map","/**\n * Generates OpenAPI 3.1 documents from declarative `HttpApi` contracts.\n *\n * The generator reads API groups, endpoints, schemas, security definitions, and\n * annotations, then produces an OpenAPI document. This module also provides the\n * annotations used to shape that output and the TypeScript model for the\n * OpenAPI objects it generates.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Equal from \"../../Equal.js\";\nimport { constFalse } from \"../../Function.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as InternalToJsonSchemaDocument from \"../../internal/schema/toJsonSchemaDocument.js\";\nimport * as InternalToRepresentation from \"../../internal/schema/toRepresentation.js\";\nimport * as JsonPatch from \"../../JsonPatch.js\";\nimport { escapeToken } from \"../../JsonPointer.js\";\nimport * as JsonSchema from \"../../JsonSchema.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\nimport * as HttpMethod from \"../http/HttpMethod.js\";\nimport * as HttpApi from \"./HttpApi.js\";\nimport * as HttpApiEndpoint from \"./HttpApiEndpoint.js\";\nimport * as HttpApiMiddleware from \"./HttpApiMiddleware.js\";\nimport * as HttpApiSchema from \"./HttpApiSchema.js\";\n/**\n * OpenAPI annotation for overriding generated identifiers, including operation ids.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Identifier extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Identifier\") {}\n/**\n * OpenAPI annotation for setting the API title or group tag name.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Title extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Title\") {}\n/**\n * OpenAPI annotation for setting the generated API version.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Version extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Version\") {}\n/**\n * OpenAPI annotation for setting generated descriptions on APIs, groups, endpoints, or security schemes.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Description extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Description\") {}\n/**\n * OpenAPI annotation for setting the generated API license metadata.\n *\n * @category services\n * @since 4.0.0\n */\nexport class License extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/License\") {}\n/**\n * OpenAPI annotation for adding external documentation metadata to groups or endpoints.\n *\n * @category services\n * @since 4.0.0\n */\nexport class ExternalDocs extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/ExternalDocs\") {}\n/**\n * OpenAPI annotation for setting the generated API server list.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Servers extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Servers\") {}\n/**\n * OpenAPI annotation for setting the format metadata, such as a bearer token format on security schemes.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Format extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Format\") {}\n/**\n * OpenAPI annotation for setting generated summary text.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Summary extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Summary\") {}\n/**\n * OpenAPI annotation for marking a generated endpoint operation as deprecated.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Deprecated extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Deprecated\") {}\n/**\n * OpenAPI annotation for shallowly merging additional fields into a generated OpenAPI object.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Override extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Override\") {}\n/**\n * Annotation that excludes an annotated group or endpoint from the generated\n * OpenAPI specification.\n *\n * **When to use**\n *\n * Use to hide internal, experimental, or otherwise undocumented HTTP API groups\n * and endpoints from generated OpenAPI output.\n *\n * @category services\n * @since 4.0.0\n */\nexport const Exclude = /*#__PURE__*/Context.Reference(\"effect/httpapi/OpenApi/Exclude\", {\n  defaultValue: constFalse\n});\n/**\n * OpenAPI annotation for transforming a generated OpenAPI object.\n *\n * **Details**\n *\n * The function is applied during generation to the annotated API, group tag, or\n * endpoint operation.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Transform extends /*#__PURE__*/Context.Service()(\"effect/httpapi/OpenApi/Transform\") {}\nconst servicesPartial = tags => {\n  const entries = Object.entries(tags);\n  return options => {\n    let context = Context.empty();\n    for (const [key, tag] of entries) {\n      if (options[key] !== undefined) {\n        context = Context.add(context, tag, options[key]);\n      }\n    }\n    return context;\n  };\n};\n/**\n * Builds a `Context` containing OpenAPI annotations from the supplied options.\n *\n * @category annotations\n * @since 4.0.0\n */\nexport const annotations = /*#__PURE__*/servicesPartial({\n  identifier: Identifier,\n  title: Title,\n  version: Version,\n  description: Description,\n  license: License,\n  summary: Summary,\n  deprecated: Deprecated,\n  externalDocs: ExternalDocs,\n  servers: Servers,\n  format: Format,\n  override: Override,\n  exclude: Exclude,\n  transform: Transform\n});\nconst apiCache = /*#__PURE__*/new WeakMap();\nconst compileSchemas = asts => JsonSchema.toMultiDocumentOpenApi3_1(InternalToJsonSchemaDocument.toJsonSchemaMultiDocument(InternalToRepresentation.toRepresentations(Arr.map(asts, Schema.toCodecJsonAST))));\n/**\n * This function checks if a given tag exists within the provided context. If\n * the tag is present, it retrieves the associated value and applies the given\n * callback function to it. If the tag is not found, the function does nothing.\n */\nfunction processAnnotation(ctx, annotation, f) {\n  const o = Context.getOption(ctx, annotation);\n  if (Option.isSome(o)) {\n    f(o.value);\n  }\n}\n/**\n * Converts an `HttpApi` instance into an OpenAPI Specification object.\n *\n * **Details**\n *\n * This function takes an `HttpApi` instance, which defines a structured API,\n * and generates an OpenAPI Specification (`OpenAPISpec`). The resulting spec\n * adheres to the OpenAPI 3.1.0 standard and includes detailed metadata such as\n * paths, operations, security schemes, and components. The function processes\n * the API's annotations, middleware, groups, and endpoints to build a complete\n * and accurate representation of the API in OpenAPI format.\n *\n * The function also deduplicates schemas, applies transformations, and\n * integrates annotations like descriptions, summaries, external documentation,\n * and overrides. Cached results are used for better performance when the same\n * `HttpApi` instance is processed multiple times.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function fromApi(api) {\n  return fromApiWith(api, apiCache, compileSchemas);\n}\nfunction fromApiWith(api, cache, compileSchemas) {\n  const cached = cache.get(api);\n  if (cached !== undefined) {\n    return cached;\n  }\n  let spec = {\n    openapi: \"3.1.0\",\n    info: {\n      title: \"Api\",\n      version: \"0.0.1\"\n    },\n    paths: {},\n    components: {\n      schemas: {},\n      securitySchemes: {}\n    },\n    security: [],\n    tags: []\n  };\n  const pathOps = [];\n  const pathOperations = new Set();\n  const operationIds = new Set();\n  processAnnotation(api.annotations, Title, title => {\n    spec.info.title = title;\n  });\n  processAnnotation(api.annotations, Version, version => {\n    spec.info.version = version;\n  });\n  processAnnotation(api.annotations, Description, description => {\n    spec.info.description = description;\n  });\n  processAnnotation(api.annotations, License, license => {\n    spec.info.license = license;\n  });\n  processAnnotation(api.annotations, Summary, summary => {\n    spec.info.summary = summary;\n  });\n  processAnnotation(api.annotations, Servers, servers => {\n    spec.servers = [...servers];\n  });\n  HttpApi.reflect(api, {\n    onGroup({\n      group\n    }) {\n      if (Context.get(group.annotations, Exclude)) {\n        return;\n      }\n      let tag = {\n        name: Context.getOrElse(group.annotations, Title, () => group.identifier)\n      };\n      processAnnotation(group.annotations, Description, description => {\n        tag.description = description;\n      });\n      processAnnotation(group.annotations, ExternalDocs, externalDocs => {\n        tag.externalDocs = externalDocs;\n      });\n      processAnnotation(group.annotations, Override, override => {\n        // OpenAPI documents are JSON, so symbol keys are intentionally ignored.\n        for (const [key, value] of Object.entries(override)) {\n          InternalRecord.assignProperty(tag, key, value);\n        }\n      });\n      processAnnotation(group.annotations, Transform, transformFn => {\n        tag = transformFn(tag);\n      });\n      spec.tags.push(tag);\n    },\n    onEndpoint({\n      endpoint,\n      group,\n      mergedAnnotations,\n      middleware\n    }) {\n      if (Context.get(mergedAnnotations, Exclude)) {\n        return;\n      }\n      let op = {\n        tags: [Context.getOrElse(group.annotations, Title, () => group.identifier)],\n        operationId: Context.getOrElse(endpoint.annotations, Identifier, () => group.topLevel ? endpoint.identifier : `${group.identifier}.${endpoint.identifier}`),\n        parameters: [],\n        security: [],\n        responses: {}\n      };\n      const path = endpoint.path.replace(/:(\\w+)\\??/g, \"{$1}\");\n      const method = endpoint.method.toLowerCase();\n      function processResponseBodies(bodies, defaultDescription) {\n        for (const [status, {\n          content,\n          descriptions,\n          streamContent\n        }] of bodies) {\n          const description = descriptions.size > 0 ? Array.from(descriptions).join(\" | \") : defaultDescription();\n          InternalRecord.assignProperty(op.responses, status, {\n            description\n          });\n          if (content !== undefined) {\n            content.forEach((map, encoding) => {\n              map.forEach((schemas, contentType) => {\n                const asts = Array.from(schemas, SchemaAST.getAST);\n                const ast = asts.length === 1 ? asts[0] : new SchemaAST.Union(asts, \"anyOf\");\n                pathOps.push({\n                  _tag: \"schema\",\n                  ast: toEncodingAST(ast, encoding),\n                  path: [\"paths\", path, method, \"responses\", String(status), \"content\", contentType, \"schema\"]\n                });\n                op.responses[status].content ??= {};\n                InternalRecord.assignProperty(op.responses[status].content, contentType, {\n                  schema: {}\n                });\n              });\n            });\n          }\n          if (streamContent !== undefined) {\n            streamContent.forEach((stream, contentType) => {\n              op.responses[status].content ??= {};\n              if (HttpApiSchema.isStreamSse(stream)) {\n                pathOps.push({\n                  _tag: \"schema\",\n                  ast: SchemaAST.getAST(stream.events),\n                  path: [\"paths\", path, method, \"responses\", String(status), \"content\", contentType, \"schema\"]\n                });\n                pathOps.push({\n                  _tag: \"schema\",\n                  ast: SchemaAST.getAST(Schema.toCodecJson(Schema.Cause(stream.error, Schema.Defect()))),\n                  path: [\"paths\", path, method, \"responses\", String(status), \"content\", contentType, \"x-effect-stream\", \"causeSchema\"]\n                });\n                pathOps.push({\n                  _tag: \"schema\",\n                  ast: SchemaAST.getAST(stream.error),\n                  path: [\"paths\", path, method, \"responses\", String(status), \"content\", contentType, \"x-effect-stream\", \"errorSchema\"]\n                });\n                InternalRecord.assignProperty(op.responses[status].content, contentType, {\n                  schema: {},\n                  \"x-effect-stream\": {\n                    encoding: \"sse\",\n                    causeSchema: {},\n                    errorSchema: {},\n                    failureEvent: reservedStreamFailureEvent\n                  }\n                });\n              } else {\n                InternalRecord.assignProperty(op.responses[status].content, contentType, {\n                  schema: {\n                    type: \"string\",\n                    format: \"binary\"\n                  },\n                  \"x-effect-stream\": {\n                    encoding: \"uint8array\"\n                  }\n                });\n              }\n            });\n          }\n        }\n      }\n      function processParameters(schema, i) {\n        if (schema) {\n          const ast = SchemaAST.getLastEncoding(schema.ast);\n          if (SchemaAST.isObjects(ast)) {\n            for (const ps of ast.propertySignatures) {\n              op.parameters.push({\n                name: String(ps.name),\n                in: i,\n                schema: {},\n                required: i === \"path\" || !SchemaAST.isOptional(ps.type)\n              });\n              pathOps.push({\n                _tag: \"parameter\",\n                ast: ps.type,\n                path: [\"paths\", path, method, \"parameters\", String(op.parameters.length - 1), \"schema\"]\n              });\n            }\n          }\n        }\n      }\n      processAnnotation(endpoint.annotations, Description, description => {\n        op.description = description;\n      });\n      processAnnotation(endpoint.annotations, Summary, summary => {\n        op.summary = summary;\n      });\n      processAnnotation(endpoint.annotations, Deprecated, deprecated => {\n        op.deprecated = deprecated;\n      });\n      processAnnotation(endpoint.annotations, ExternalDocs, externalDocs => {\n        op.externalDocs = externalDocs;\n      });\n      middleware.forEach(middleware => {\n        if (!HttpApiMiddleware.isSecurity(middleware)) {\n          return;\n        }\n        for (const [name, security] of Object.entries(middleware.security)) {\n          processHttpApiSecurity(name, security);\n          op.security.push({\n            [name]: []\n          });\n        }\n      });\n      function processHttpApiSecurity(name, security) {\n        const scheme = makeSecurityScheme(security);\n        if (!Object.hasOwn(spec.components.securitySchemes, name)) {\n          InternalRecord.assignProperty(spec.components.securitySchemes, name, scheme);\n          return;\n        }\n        if (!Equal.equals(securitySchemeForComparison(spec.components.securitySchemes[name]), securitySchemeForComparison(scheme))) {\n          throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`);\n        }\n      }\n      const hasBody = HttpMethod.hasBody(endpoint.method);\n      if (hasBody) {\n        const schemasByContentType = new Map();\n        for (const schema of HttpApiEndpoint.getPayloadSchemas(endpoint)) {\n          if (HttpApiSchema.isNoContent(schema.ast)) continue;\n          const encoding = HttpApiSchema.getPayloadEncoding(schema.ast, endpoint.method);\n          const existing = schemasByContentType.get(encoding.contentType);\n          if (existing === undefined) {\n            schemasByContentType.set(encoding.contentType, {\n              encoding,\n              schemas: [schema]\n            });\n          } else {\n            existing.schemas.push(schema);\n          }\n        }\n        if (schemasByContentType.size > 0) {\n          const content = {};\n          for (const [contentType, {\n            encoding,\n            schemas\n          }] of schemasByContentType) {\n            const asts = schemas.map(SchemaAST.getAST);\n            const ast = asts.length === 1 ? asts[0] : new SchemaAST.Union(asts, \"anyOf\");\n            pathOps.push({\n              _tag: \"schema\",\n              ast: toEncodingAST(ast, encoding._tag),\n              path: [\"paths\", path, method, \"requestBody\", \"content\", contentType, \"schema\"]\n            });\n            InternalRecord.assignProperty(content, contentType, {\n              schema: {}\n            });\n          }\n          op.requestBody = {\n            content,\n            required: true\n          };\n        }\n      }\n      processParameters(endpoint.params, \"path\");\n      if (!hasBody && endpoint.payload.size === 1) {\n        const entry = endpoint.payload.values().next().value;\n        processParameters(entry.schemas[0], \"query\");\n      }\n      processParameters(endpoint.headers, \"header\");\n      processParameters(endpoint.query, \"query\");\n      processResponseBodies(extractSuccessResponseBodies(endpoint), () => \"Success\");\n      processResponseBodies(extractResponseBodies(HttpApiEndpoint.getErrorSchemas(endpoint), HttpApiSchema.getStatusError, resolveDescriptionOrIdentifier), () => \"Error\");\n      processAnnotation(endpoint.annotations, Override, override => {\n        // OpenAPI documents are JSON, so symbol keys are intentionally ignored.\n        for (const [key, value] of Object.entries(override)) {\n          InternalRecord.assignProperty(op, key, value);\n        }\n      });\n      processAnnotation(endpoint.annotations, Transform, transformFn => {\n        op = transformFn(op);\n      });\n      const pathOperation = `${method} ${path.replace(/\\{[^}]+\\}/g, \"{}\")}`;\n      if (pathOperations.has(pathOperation)) {\n        throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path}`);\n      }\n      const operationId = op.operationId;\n      if (operationId !== undefined) {\n        if (operationIds.has(operationId)) {\n          throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`);\n        }\n        operationIds.add(operationId);\n      }\n      pathOperations.add(pathOperation);\n      if (!Object.hasOwn(spec.paths, path)) {\n        InternalRecord.assignProperty(spec.paths, path, {});\n      }\n      spec.paths[path][method] = op;\n    }\n  });\n  processAnnotation(api.annotations, HttpApi.AdditionalSchemas, componentSchemas => {\n    componentSchemas.forEach(componentSchema => {\n      const identifier = SchemaAST.resolveIdentifier(componentSchema.ast);\n      if (identifier !== undefined) {\n        if (Object.hasOwn(spec.components.schemas, identifier)) {\n          throw new globalThis.Error(`Duplicate component schema identifier: ${identifier}`);\n        }\n        InternalRecord.assignProperty(spec.components.schemas, identifier, {});\n        pathOps.push({\n          _tag: \"schema\",\n          ast: componentSchema.ast,\n          path: [\"components\", \"schemas\", identifier]\n        });\n      }\n    });\n  });\n  function escapePath(path) {\n    return \"/\" + path.map(escapeToken).join(\"/\");\n  }\n  if (Arr.isArrayNonEmpty(pathOps)) {\n    const jsonSchemaMultiDocument = compileSchemas(Arr.map(pathOps, op => op.ast));\n    const patchOps = pathOps.map((op, i) => {\n      const oppath = escapePath(op.path);\n      const value = jsonSchemaMultiDocument.schemas[i];\n      return {\n        op: \"replace\",\n        path: oppath,\n        value: value\n      };\n    });\n    Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name, definition]) => {\n      patchOps.push({\n        op: \"add\",\n        path: escapePath([\"components\", \"schemas\", name]),\n        value: definition\n      });\n    });\n    spec = JsonPatch.apply(patchOps, spec);\n  }\n  Object.keys(spec.components.schemas).forEach(key => {\n    if (!JsonSchema.VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)) {\n      throw new globalThis.Error(`Invalid component schema key: ${key}`);\n    }\n  });\n  processAnnotation(api.annotations, Override, override => {\n    // OpenAPI documents are JSON, so symbol keys are intentionally ignored.\n    for (const [key, value] of Object.entries(override)) {\n      InternalRecord.assignProperty(spec, key, value);\n    }\n  });\n  processAnnotation(api.annotations, Transform, transformFn => {\n    spec = transformFn(spec);\n  });\n  cache.set(api, spec);\n  return spec;\n}\nconst reservedStreamFailureEvent = \"effect/httpapi/stream/failure\";\nfunction extractSuccessResponseBodies(endpoint) {\n  return extractResponseBodies(HttpApiEndpoint.getSuccessSchemas(endpoint), HttpApiSchema.getStatusSuccess, resolveDescriptionOrIdentifier);\n}\nfunction extractResponseBodies(schemas, getStatus, getDescription) {\n  const map = new Map();\n  schemas.forEach(process);\n  return map;\n  function process(schema) {\n    if (HttpApiSchema.isStreamSchema(schema)) {\n      addStreamContent(schema);\n      return;\n    }\n    const ast = schema.ast;\n    const status = getStatus(ast);\n    if (HttpApiSchema.isNoContent(ast)) {\n      addNoContent(status, getDescription(schema.ast) ?? \"<No Content>\");\n    } else {\n      addContent(schema, status, HttpApiSchema.getResponseEncoding(ast));\n    }\n  }\n  function addNoContent(status, description) {\n    const statusMap = map.get(status);\n    if (statusMap === undefined) {\n      map.set(status, {\n        descriptions: new Set([description]),\n        content: undefined,\n        streamContent: undefined\n      });\n    } else {\n      if (description !== undefined) {\n        statusMap.descriptions.add(description);\n      }\n    }\n  }\n  function addContent(schema, status, encoding) {\n    const description = getDescription(schema.ast);\n    const statusMap = map.get(status);\n    const {\n      _tag,\n      contentType\n    } = encoding;\n    if (statusMap === undefined) {\n      map.set(status, {\n        descriptions: new Set(description !== undefined ? [description] : []),\n        content: new Map([[_tag, new Map([[contentType, new Set([schema])]])]]),\n        streamContent: undefined\n      });\n    } else {\n      // concat descriptions\n      if (description !== undefined) {\n        statusMap.descriptions.add(description);\n      }\n      if (statusMap.content === undefined) {\n        statusMap.content = new Map([[_tag, new Map([[contentType, new Set([schema])]])]]);\n      } else {\n        const schemasByContentType = statusMap.content.get(_tag);\n        if (schemasByContentType === undefined) {\n          statusMap.content.set(_tag, new Map([[contentType, new Set([schema])]]));\n        } else {\n          const set = schemasByContentType.get(contentType);\n          if (set === undefined) {\n            schemasByContentType.set(contentType, new Set([schema]));\n          } else {\n            set.add(schema);\n          }\n        }\n      }\n    }\n  }\n  function addStreamContent(stream) {\n    const status = HttpApiSchema.getStatusStream(stream);\n    const statusMap = map.get(status);\n    if (statusMap === undefined) {\n      map.set(status, {\n        descriptions: new Set(),\n        content: undefined,\n        streamContent: new Map([[stream.contentType, stream]])\n      });\n    } else if (statusMap.streamContent === undefined) {\n      statusMap.streamContent = new Map([[stream.contentType, stream]]);\n    } else {\n      statusMap.streamContent.set(stream.contentType, stream);\n    }\n  }\n}\nfunction resolveDescriptionOrIdentifier(ast) {\n  return SchemaAST.resolveDescription(ast) ?? SchemaAST.resolveIdentifier(ast);\n}\nconst Uint8ArrayEncoding = /*#__PURE__*/Schema.String.annotate({\n  format: \"binary\"\n});\nfunction toEncodingAST(ast, _tag) {\n  switch (_tag) {\n    case \"Uint8Array\":\n      return Uint8ArrayEncoding.ast;\n    case \"Text\":\n      return Schema.String.ast;\n    case \"FormUrlEncoded\":\n    case \"Json\":\n      return ast;\n    case \"Multipart\":\n      return persistedFileToBinaryEncoding(ast);\n  }\n}\nfunction persistedFileToBinaryEncoding(ast) {\n  if (SchemaAST.isDeclaration(ast) && ast.annotations?.representation?.id === \"effect/http/PersistedFile\") {\n    return Uint8ArrayEncoding.ast;\n  }\n  if (typeof ast?.recur === \"function\") {\n    return ast.recur(persistedFileToBinaryEncoding);\n  }\n  return ast;\n}\nconst makeSecurityScheme = security => {\n  const meta = {};\n  processAnnotation(security.annotations, Description, description => {\n    meta.description = description;\n  });\n  switch (security._tag) {\n    case \"Basic\":\n      {\n        return {\n          ...meta,\n          type: \"http\",\n          scheme: \"basic\"\n        };\n      }\n    case \"Http\":\n      {\n        const format = Context.getOption(security.annotations, Format).pipe(Option.map(format => ({\n          bearerFormat: format\n        })), Option.getOrUndefined);\n        return {\n          ...meta,\n          type: \"http\",\n          scheme: security.scheme,\n          ...format\n        };\n      }\n    case \"ApiKey\":\n      {\n        return {\n          ...meta,\n          type: \"apiKey\",\n          name: security.key,\n          in: security.in\n        };\n      }\n  }\n};\nconst securitySchemeForComparison = scheme => {\n  if (scheme.type === \"http\") {\n    return {\n      ...scheme,\n      scheme: scheme.scheme.toLowerCase()\n    };\n  }\n  if (scheme.in === \"header\") {\n    return {\n      ...scheme,\n      name: scheme.name.toLowerCase()\n    };\n  }\n  return scheme;\n};\n//# sourceMappingURL=OpenApi.js.map","import * as Context from \"effect/Context\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpApi from \"effect/unstable/httpapi/HttpApi\";\nimport * as HttpApiEndpoint from \"effect/unstable/httpapi/HttpApiEndpoint\";\nimport * as HttpApiGroup from \"effect/unstable/httpapi/HttpApiGroup\";\nimport * as HttpApiMiddleware from \"effect/unstable/httpapi/HttpApiMiddleware\";\nimport * as HttpApiSchema from \"effect/unstable/httpapi/HttpApiSchema\";\nimport * as HttpApiSecurity from \"effect/unstable/httpapi/HttpApiSecurity\";\nimport * as OpenApi from \"effect/unstable/httpapi/OpenApi\";\n\nimport { EnvironmentId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { ExecutionEnvironmentDescriptor } from \"./environment.ts\";\n\nexport const RelayAgentAwarenessPlatform = Schema.Literal(\"ios\");\nexport type RelayAgentAwarenessPlatform = typeof RelayAgentAwarenessPlatform.Type;\n\nexport const RelayAgentAwarenessPhase = Schema.Literals([\n  \"starting\",\n  \"running\",\n  \"waiting_for_approval\",\n  \"waiting_for_input\",\n  \"completed\",\n  \"failed\",\n  \"stale\",\n]);\nexport type RelayAgentAwarenessPhase = typeof RelayAgentAwarenessPhase.Type;\n\nexport const RelayAgentAwarenessPreferences = Schema.Struct({\n  liveActivitiesEnabled: Schema.Boolean,\n  notificationsEnabled: Schema.Boolean,\n  notifyOnApproval: Schema.Boolean,\n  notifyOnInput: Schema.Boolean,\n  notifyOnCompletion: Schema.Boolean,\n  notifyOnFailure: Schema.Boolean,\n});\nexport type RelayAgentAwarenessPreferences = typeof RelayAgentAwarenessPreferences.Type;\n\nexport const RelayApnsEnvironment = Schema.Literals([\"sandbox\", \"production\"]);\nexport type RelayApnsEnvironment = typeof RelayApnsEnvironment.Type;\n\nexport const RelayDeviceRegistrationRequest = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  platform: RelayAgentAwarenessPlatform,\n  iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)),\n  appVersion: Schema.optional(TrimmedNonEmptyString),\n  // APNs routing for this install: the topic must match the app's bundle id\n  // (dev/preview/prod variants differ) and development-signed builds receive\n  // sandbox tokens. Optional so older app builds keep registering; the relay\n  // falls back to its configured defaults.\n  bundleId: Schema.optional(TrimmedNonEmptyString),\n  apsEnvironment: Schema.optional(RelayApnsEnvironment),\n  pushToken: Schema.optional(TrimmedNonEmptyString),\n  pushToStartToken: Schema.optional(TrimmedNonEmptyString),\n  preferences: RelayAgentAwarenessPreferences,\n});\nexport type RelayDeviceRegistrationRequest = typeof RelayDeviceRegistrationRequest.Type;\n\nexport const RelayClientDeviceRecord = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  platform: RelayAgentAwarenessPlatform,\n  iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)),\n  appVersion: Schema.NullOr(TrimmedNonEmptyString),\n  notifications: Schema.Struct({\n    enabled: Schema.Boolean,\n    notifyOnApproval: Schema.Boolean,\n    notifyOnInput: Schema.Boolean,\n    notifyOnCompletion: Schema.Boolean,\n    notifyOnFailure: Schema.Boolean,\n  }),\n  liveActivities: Schema.Struct({\n    enabled: Schema.Boolean,\n  }),\n  updatedAt: TrimmedNonEmptyString,\n});\nexport type RelayClientDeviceRecord = typeof RelayClientDeviceRecord.Type;\n\nexport const RelayListDevicesResponse = Schema.Struct({\n  devices: Schema.Array(RelayClientDeviceRecord),\n});\nexport type RelayListDevicesResponse = typeof RelayListDevicesResponse.Type;\n\nexport const RelayLiveActivityRegistrationRequest = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  activityPushToken: TrimmedNonEmptyString,\n});\nexport type RelayLiveActivityRegistrationRequest = typeof RelayLiveActivityRegistrationRequest.Type;\n\nexport const RelayDeviceUnregistrationParams = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n});\nexport type RelayDeviceUnregistrationParams = typeof RelayDeviceUnregistrationParams.Type;\n\nexport const RelayAgentActivityState = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  projectTitle: TrimmedNonEmptyString,\n  threadTitle: TrimmedNonEmptyString,\n  phase: RelayAgentAwarenessPhase,\n  headline: TrimmedNonEmptyString,\n  detail: Schema.optional(TrimmedNonEmptyString),\n  modelTitle: TrimmedNonEmptyString,\n  updatedAt: TrimmedNonEmptyString,\n  deepLink: TrimmedNonEmptyString,\n});\nexport type RelayAgentActivityState = typeof RelayAgentActivityState.Type;\n\nexport const RelayAgentActivityAggregateRow = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  projectTitle: TrimmedNonEmptyString,\n  threadTitle: TrimmedNonEmptyString,\n  modelTitle: TrimmedNonEmptyString,\n  phase: RelayAgentAwarenessPhase,\n  status: TrimmedNonEmptyString,\n  updatedAt: TrimmedNonEmptyString,\n  deepLink: TrimmedNonEmptyString,\n});\nexport type RelayAgentActivityAggregateRow = typeof RelayAgentActivityAggregateRow.Type;\n\nexport const RelayAgentActivityAggregateState = Schema.Struct({\n  title: TrimmedNonEmptyString,\n  subtitle: TrimmedNonEmptyString,\n  activeCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n  updatedAt: TrimmedNonEmptyString,\n  activities: Schema.Array(RelayAgentActivityAggregateRow),\n});\nexport type RelayAgentActivityAggregateState = typeof RelayAgentActivityAggregateState.Type;\n\nexport const RelayManagedEndpointProviderKind = Schema.Literals([\n  \"manual\",\n  \"cloudflare_tunnel\",\n  \"t3_relay\",\n]);\nexport type RelayManagedEndpointProviderKind = typeof RelayManagedEndpointProviderKind.Type;\n\nexport const RelayManagedEndpoint = Schema.Struct({\n  httpBaseUrl: TrimmedNonEmptyString,\n  wsBaseUrl: TrimmedNonEmptyString,\n  providerKind: RelayManagedEndpointProviderKind,\n});\nexport type RelayManagedEndpoint = typeof RelayManagedEndpoint.Type;\n\nexport const RelayManagedEndpointOrigin = Schema.Struct({\n  localHttpHost: TrimmedNonEmptyString,\n  localHttpPort: Schema.Int.check(\n    Schema.isGreaterThanOrEqualTo(1),\n    Schema.isLessThanOrEqualTo(65_535),\n  ),\n});\nexport type RelayManagedEndpointOrigin = typeof RelayManagedEndpointOrigin.Type;\n\nexport const RelayManagedEndpointRuntimeConfig = Schema.Struct({\n  providerKind: RelayManagedEndpointProviderKind,\n  connectorToken: TrimmedNonEmptyString,\n  tunnelId: Schema.optional(TrimmedNonEmptyString),\n  tunnelName: Schema.optional(TrimmedNonEmptyString),\n});\nexport type RelayManagedEndpointRuntimeConfig = typeof RelayManagedEndpointRuntimeConfig.Type;\n\nexport const RelayLinkProofRequest = Schema.Struct({\n  challenge: Schema.String,\n  relayIssuer: Schema.String,\n  endpoint: RelayManagedEndpoint,\n  origin: RelayManagedEndpointOrigin,\n});\nexport type RelayLinkProofRequest = typeof RelayLinkProofRequest.Type;\n\nexport const RelayEnvironmentConfigRequest = Schema.Struct({\n  relayUrl: Schema.String,\n  relayIssuer: Schema.optional(Schema.String),\n  cloudUserId: Schema.String,\n  environmentCredential: Schema.String,\n  cloudMintPublicKey: Schema.String,\n  endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig),\n});\nexport type RelayEnvironmentConfigRequest = typeof RelayEnvironmentConfigRequest.Type;\n\nconst RelaySignedJwtRegisteredClaims = {\n  iss: TrimmedNonEmptyString,\n  aud: TrimmedNonEmptyString,\n  sub: TrimmedNonEmptyString,\n  jti: TrimmedNonEmptyString,\n  iat: Schema.Int,\n  exp: Schema.Int,\n} as const;\n\nexport const RelayAgentActivityPublishProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  state: Schema.NullOr(RelayAgentActivityState),\n});\nexport type RelayAgentActivityPublishProofPayload =\n  typeof RelayAgentActivityPublishProofPayload.Type;\nexport type RelayAgentActivityPublishProof = string;\n\nexport const RelayAgentActivityPublishRequest = Schema.Struct({\n  state: Schema.NullOr(RelayAgentActivityState).annotate({\n    description: \"Current agent-awareness state, or null to remove the published state.\",\n  }),\n  proof: TrimmedNonEmptyString.annotate({\n    description: \"Environment-signed JWT covering this published activity state.\",\n  }),\n}).annotate({ description: \"Publishes a signed agent-awareness update from an environment.\" });\nexport type RelayAgentActivityPublishRequest = typeof RelayAgentActivityPublishRequest.Type;\n\nexport const RelayEnvironmentLinkScope = Schema.Literals([\n  \"agent_activity_notifications\",\n  \"managed_tunnels\",\n]);\nexport type RelayEnvironmentLinkScope = typeof RelayEnvironmentLinkScope.Type;\n\nexport const RelayEnvironmentLinkProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  challenge: TrimmedNonEmptyString,\n  descriptor: ExecutionEnvironmentDescriptor,\n  environmentId: EnvironmentId,\n  environmentPublicKey: TrimmedNonEmptyString,\n  endpoint: RelayManagedEndpoint,\n  origin: RelayManagedEndpointOrigin,\n  scopes: Schema.Array(RelayEnvironmentLinkScope),\n});\nexport type RelayEnvironmentLinkProofPayload = typeof RelayEnvironmentLinkProofPayload.Type;\n\nexport const RelayEnvironmentLinkProof = TrimmedNonEmptyString;\nexport type RelayEnvironmentLinkProof = typeof RelayEnvironmentLinkProof.Type;\n\nexport const RelayEnvironmentLinkChallengeRequest = Schema.Struct({\n  notificationsEnabled: Schema.Boolean.annotate({\n    description: \"Whether this link may deliver push notifications.\",\n  }),\n  liveActivitiesEnabled: Schema.Boolean.annotate({\n    description: \"Whether this link may update Live Activities.\",\n  }),\n  managedTunnelsEnabled: Schema.Boolean.annotate({\n    description: \"Whether the relay should provision a managed tunnel for this environment.\",\n  }),\n}).annotate({ description: \"Requested capabilities for a new environment-link challenge.\" });\nexport type RelayEnvironmentLinkChallengeRequest = typeof RelayEnvironmentLinkChallengeRequest.Type;\n\nexport const RelayEnvironmentLinkChallengeResponse = Schema.Struct({\n  challenge: TrimmedNonEmptyString,\n  expiresAt: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentLinkChallengeResponse =\n  typeof RelayEnvironmentLinkChallengeResponse.Type;\n\nexport const RelayEnvironmentLinkRequest = Schema.Struct({\n  deviceId: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Optional client device identifier associated with this link.\",\n    }),\n  ),\n  proof: RelayEnvironmentLinkProof.annotate({\n    description: \"Environment-signed proof bound to a previously issued link challenge.\",\n  }),\n  notificationsEnabled: Schema.Boolean,\n  liveActivitiesEnabled: Schema.Boolean,\n  managedTunnelsEnabled: Schema.Boolean,\n}).annotate({ description: \"Links an authenticated cloud user to a T3 environment.\" });\nexport type RelayEnvironmentLinkRequest = typeof RelayEnvironmentLinkRequest.Type;\n\nexport const RelayEnvironmentLinkResponse = Schema.Struct({\n  ok: Schema.Boolean,\n  cloudUserId: TrimmedNonEmptyString,\n  environmentId: EnvironmentId,\n  endpoint: RelayManagedEndpoint,\n  endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig),\n  relayIssuer: TrimmedNonEmptyString,\n  environmentCredential: TrimmedNonEmptyString,\n  cloudMintPublicKey: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentLinkResponse = typeof RelayEnvironmentLinkResponse.Type;\n\nexport const RelayEnvironmentLinkProofInvalidReason = Schema.Literals([\n  \"invalid_signature_or_scope\",\n  \"descriptor_mismatch\",\n  \"replayed_nonce\",\n  \"challenge_invalid\",\n  \"origin_not_allowed\",\n  \"endpoint_not_secure\",\n]);\nexport type RelayEnvironmentLinkProofInvalidReason =\n  typeof RelayEnvironmentLinkProofInvalidReason.Type;\n\nexport const RelayEnvironmentLinkFailedReason = Schema.Literals([\n  \"link_persistence_failed\",\n  \"credential_persistence_failed\",\n  \"replay_persistence_failed\",\n  \"internal_error\",\n]);\nexport type RelayEnvironmentLinkFailedReason = typeof RelayEnvironmentLinkFailedReason.Type;\n\nexport const RelayEnvironmentLinkUnavailableReason = Schema.Literals([\n  \"managed_endpoint_not_configured\",\n  \"managed_endpoint_provisioning_failed\",\n]);\nexport type RelayEnvironmentLinkUnavailableReason =\n  typeof RelayEnvironmentLinkUnavailableReason.Type;\n\nexport const RelayEnvironmentEndpointUnavailableReason = Schema.Literals([\n  \"endpoint_request_failed\",\n  \"endpoint_response_invalid\",\n]);\nexport type RelayEnvironmentEndpointUnavailableReason =\n  typeof RelayEnvironmentEndpointUnavailableReason.Type;\n\nexport const RelayAgentActivityPublishProofInvalidReason = Schema.Literals([\n  \"invalid_signature_or_payload\",\n  \"replayed_nonce\",\n]);\nexport type RelayAgentActivityPublishProofInvalidReason =\n  typeof RelayAgentActivityPublishProofInvalidReason.Type;\n\nexport const RelayAuthInvalidReason = Schema.Literals([\n  \"missing_bearer\",\n  \"invalid_bearer\",\n  \"invalid_dpop\",\n  \"not_authorized\",\n]);\nexport type RelayAuthInvalidReason = typeof RelayAuthInvalidReason.Type;\n\nexport const RelayInternalErrorReason = Schema.Literals([\n  \"database_unavailable\",\n  \"persistence_failed\",\n  \"upstream_unavailable\",\n  \"internal_error\",\n]);\nexport type RelayInternalErrorReason = typeof RelayInternalErrorReason.Type;\n\nexport class RelayAuthInvalidError extends Schema.TaggedErrorClass<RelayAuthInvalidError>()(\n  \"RelayAuthInvalidError\",\n  {\n    code: Schema.Literal(\"auth_invalid\"),\n    reason: RelayAuthInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return `Relay authentication failed: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofExpiredError>()(\n  \"RelayEnvironmentLinkProofExpiredError\",\n  {\n    code: Schema.Literal(\"environment_link_proof_expired\"),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return \"Relay environment link proof expired\";\n  }\n}\n\nexport class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofInvalidError>()(\n  \"RelayEnvironmentLinkProofInvalidError\",\n  {\n    code: Schema.Literal(\"environment_link_proof_invalid\"),\n    reason: RelayEnvironmentLinkProofInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 400 },\n) {\n  override get message(): string {\n    return `Relay environment link proof is invalid: ${this.reason}`;\n  }\n}\n\nexport const RelayEnvironmentConnectNotAuthorizedReason = Schema.Literals([\n  \"client_proof_key_thumbprint_missing\",\n  \"environment_link_not_found\",\n  \"endpoint_provider_not_managed\",\n  \"managed_endpoint_allocation_not_found\",\n  \"managed_endpoint_base_domain_not_configured\",\n  \"managed_endpoint_allocation_not_ready\",\n  \"managed_endpoint_hostname_invalid\",\n  \"managed_endpoint_mismatch\",\n]);\nexport type RelayEnvironmentConnectNotAuthorizedReason =\n  typeof RelayEnvironmentConnectNotAuthorizedReason.Type;\n\nexport class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass<RelayEnvironmentConnectNotAuthorizedError>()(\n  \"RelayEnvironmentConnectNotAuthorizedError\",\n  {\n    code: Schema.Literal(\"environment_connect_not_authorized\"),\n    // Optional so responses from relays deployed before the reason was\n    // threaded through still decode.\n    reason: Schema.optional(RelayEnvironmentConnectNotAuthorizedReason),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  override get message(): string {\n    return this.reason\n      ? `Relay environment connection is not authorized: ${this.reason}`\n      : \"Relay environment connection is not authorized\";\n  }\n}\n\nexport class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointUnavailableError>()(\n  \"RelayEnvironmentEndpointUnavailableError\",\n  {\n    code: Schema.Literal(\"environment_endpoint_unavailable\"),\n    reason: RelayEnvironmentEndpointUnavailableReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 502 },\n) {\n  override get message(): string {\n    return `Relay environment endpoint is unavailable: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointTimedOutError>()(\n  \"RelayEnvironmentEndpointTimedOutError\",\n  {\n    code: Schema.Literal(\"environment_endpoint_timed_out\"),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 504 },\n) {\n  override get message(): string {\n    return \"Relay environment endpoint request timed out\";\n  }\n}\n\nexport class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<RelayEnvironmentLinkFailedError>()(\n  \"RelayEnvironmentLinkFailedError\",\n  {\n    code: Schema.Literal(\"environment_link_failed\"),\n    reason: RelayEnvironmentLinkFailedReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 500 },\n) {\n  override get message(): string {\n    return `Relay environment link failed: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentLinkUnavailableError>()(\n  \"RelayEnvironmentLinkUnavailableError\",\n  {\n    code: Schema.Literal(\"environment_link_unavailable\"),\n    reason: RelayEnvironmentLinkUnavailableReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 503 },\n) {\n  override get message(): string {\n    return `Relay environment link is unavailable: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentLinkLimitExceededError extends Schema.TaggedErrorClass<RelayEnvironmentLinkLimitExceededError>()(\n  \"RelayEnvironmentLinkLimitExceededError\",\n  {\n    code: Schema.Literal(\"environment_link_limit_exceeded\"),\n    maxTunnels: Schema.Number,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  override get message(): string {\n    return `Relay managed tunnel limit reached: this account allows at most ${this.maxTunnels} tunnels`;\n  }\n}\n\nexport class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofExpiredError>()(\n  \"RelayAgentActivityPublishProofExpiredError\",\n  {\n    code: Schema.Literal(\"agent_activity_publish_proof_expired\"),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return \"Relay agent activity publish proof expired\";\n  }\n}\n\nexport class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofInvalidError>()(\n  \"RelayAgentActivityPublishProofInvalidError\",\n  {\n    code: Schema.Literal(\"agent_activity_publish_proof_invalid\"),\n    reason: RelayAgentActivityPublishProofInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return `Relay agent activity publish proof is invalid: ${this.reason}`;\n  }\n}\n\nexport class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(\n  \"RelayInternalError\",\n  {\n    code: Schema.Literal(\"internal_error\"),\n    reason: RelayInternalErrorReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 500 },\n) {\n  override get message(): string {\n    return `Relay internal error: ${this.reason}`;\n  }\n}\n\nexport const RelayProtectedError = Schema.Union([\n  RelayAuthInvalidError,\n  RelayEnvironmentLinkProofExpiredError,\n  RelayEnvironmentLinkProofInvalidError,\n  RelayEnvironmentConnectNotAuthorizedError,\n  RelayEnvironmentEndpointUnavailableError,\n  RelayEnvironmentEndpointTimedOutError,\n  RelayEnvironmentLinkFailedError,\n  RelayEnvironmentLinkUnavailableError,\n  RelayEnvironmentLinkLimitExceededError,\n  RelayAgentActivityPublishProofExpiredError,\n  RelayAgentActivityPublishProofInvalidError,\n  RelayInternalError,\n]);\nexport type RelayProtectedError = typeof RelayProtectedError.Type;\n\nconst RelayAuthAndInternalErrors = [RelayAuthInvalidError, RelayInternalError] as const;\n\nconst RelayEnvironmentLinkErrors = [\n  RelayAuthInvalidError,\n  RelayEnvironmentLinkProofExpiredError,\n  RelayEnvironmentLinkProofInvalidError,\n  RelayEnvironmentLinkUnavailableError,\n  RelayEnvironmentLinkLimitExceededError,\n  RelayEnvironmentLinkFailedError,\n  RelayInternalError,\n] as const;\n\nconst RelayEnvironmentConnectErrors = [\n  RelayAuthInvalidError,\n  RelayEnvironmentConnectNotAuthorizedError,\n  RelayEnvironmentEndpointUnavailableError,\n  RelayEnvironmentEndpointTimedOutError,\n  RelayInternalError,\n] as const;\n\nconst RelayAgentActivityPublishErrors = [\n  RelayAuthInvalidError,\n  RelayAgentActivityPublishProofExpiredError,\n  RelayAgentActivityPublishProofInvalidError,\n  RelayInternalError,\n] as const;\n\nexport class RelayClientPrincipal extends Context.Service<\n  RelayClientPrincipal,\n  {\n    readonly userId: string;\n    readonly token: string;\n    readonly proofKeyThumbprint?: string;\n    readonly dpopScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;\n  }\n>()(\"@t3tools/contracts/relay/RelayClientPrincipal\") {}\n\nexport class RelayEnvironmentPrincipal extends Context.Service<\n  RelayEnvironmentPrincipal,\n  {\n    readonly environmentId: string;\n    readonly environmentPublicKey: string;\n  }\n>()(\"@t3tools/contracts/relay/RelayEnvironmentPrincipal\") {}\n\nconst RelayClientBearerAuthorization = HttpApiSecurity.http({ scheme: \"bearer\" }).pipe(\n  HttpApiSecurity.annotate(\n    OpenApi.Description,\n    \"Clerk session or OAuth bearer token for the signed-in T3 Connect user.\",\n  ),\n);\n\nexport class RelayClientAuth extends HttpApiMiddleware.Service<\n  RelayClientAuth,\n  { provides: RelayClientPrincipal }\n>()(\"RelayClientAuth\", {\n  error: RelayAuthInvalidError,\n  security: { clientBearer: RelayClientBearerAuthorization },\n}) {}\n\nconst RelayEnvironmentBearerAuthorization = HttpApiSecurity.http({ scheme: \"bearer\" }).pipe(\n  HttpApiSecurity.annotate(\n    OpenApi.Description,\n    \"Relay-issued environment credential installed when the environment is linked.\",\n  ),\n);\n\nexport class RelayEnvironmentAuth extends HttpApiMiddleware.Service<\n  RelayEnvironmentAuth,\n  { provides: RelayEnvironmentPrincipal }\n>()(\"RelayEnvironmentAuth\", {\n  error: [RelayAuthInvalidError, RelayInternalError],\n  security: { environmentBearer: RelayEnvironmentBearerAuthorization },\n}) {}\n\nconst RelayDpopAuthorization = HttpApiSecurity.http({ scheme: \"DPoP\" }).pipe(\n  HttpApiSecurity.annotate(\n    OpenApi.Description,\n    \"DPoP-bound access token. Requests must also include the DPoP proof JWT header.\",\n  ),\n);\n\nexport class RelayDpopClientAuth extends HttpApiMiddleware.Service<\n  RelayDpopClientAuth,\n  { provides: RelayClientPrincipal }\n>()(\"RelayDpopClientAuth\", {\n  error: RelayAuthInvalidError,\n  security: { relayDpop: RelayDpopAuthorization },\n}) {}\n\nexport const RelayClientEnvironmentRecord = Schema.Struct({\n  environmentId: EnvironmentId,\n  label: TrimmedNonEmptyString,\n  endpoint: RelayManagedEndpoint,\n  linkedAt: TrimmedNonEmptyString,\n});\nexport type RelayClientEnvironmentRecord = typeof RelayClientEnvironmentRecord.Type;\n\nexport const RelayListEnvironmentsResponse = Schema.Struct({\n  environments: Schema.Array(RelayClientEnvironmentRecord),\n});\nexport type RelayListEnvironmentsResponse = typeof RelayListEnvironmentsResponse.Type;\n\nexport const RelayEnvironmentConnectRequest = Schema.Struct({\n  deviceId: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Optional client device identifier requesting the connection.\",\n    }),\n  ),\n  clientKeyThumbprint: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Deprecated alias for clientProofKeyThumbprint.\",\n    }),\n  ),\n  clientProofKeyThumbprint: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"JWK thumbprint that the minted environment credential must be bound to.\",\n    }),\n  ),\n}).annotate({ description: \"Requests a short-lived credential for connecting to an environment.\" });\nexport type RelayEnvironmentConnectRequest = typeof RelayEnvironmentConnectRequest.Type;\n\nexport const RelayEnvironmentConnectScope = \"environment:connect\" as const;\nexport const RelayEnvironmentStatusScope = \"environment:status\" as const;\nexport const RelayMobileRegistrationScope = \"mobile:registration\" as const;\nexport const RelayDpopAccessTokenScope = Schema.Literals([\n  RelayEnvironmentConnectScope,\n  RelayEnvironmentStatusScope,\n  RelayMobileRegistrationScope,\n]);\nexport type RelayDpopAccessTokenScope = typeof RelayDpopAccessTokenScope.Type;\n\nexport const RelayDpopTokenExchangeGrantType =\n  \"urn:ietf:params:oauth:grant-type:token-exchange\" as const;\nexport const RelayJwtSubjectTokenType = \"urn:ietf:params:oauth:token-type:jwt\" as const;\nexport const RelayAccessTokenType = \"urn:ietf:params:oauth:token-type:access_token\" as const;\nexport const RelayPublicClientId = Schema.Literals([\"t3-mobile\", \"t3-web\"]);\nexport type RelayPublicClientId = typeof RelayPublicClientId.Type;\nexport const RelayMobileClientId = \"t3-mobile\" as const;\nexport const RelayWebClientId = \"t3-web\" as const;\n\nexport const RelayDpopAccessTokenRequest = Schema.Struct({\n  grant_type: Schema.Literal(RelayDpopTokenExchangeGrantType),\n  subject_token: TrimmedNonEmptyString.annotate({\n    description: \"Clerk bearer token for the signed-in cloud user.\",\n  }),\n  subject_token_type: Schema.Literal(RelayJwtSubjectTokenType),\n  requested_token_type: Schema.Literal(RelayAccessTokenType),\n  resource: TrimmedNonEmptyString.annotate({\n    description: \"Relay issuer URL that will receive the DPoP-bound access token.\",\n  }),\n  scope: TrimmedNonEmptyString.annotate({\n    description: \"Space-separated relay scopes requested by the client.\",\n  }),\n  client_id: RelayPublicClientId,\n})\n  .annotate({ description: \"OAuth token exchange request for a DPoP-bound relay access token.\" })\n  .pipe(HttpApiSchema.asFormUrlEncoded());\nexport type RelayDpopAccessTokenRequest = typeof RelayDpopAccessTokenRequest.Type;\n\nexport const RelayDpopAccessTokenResponse = Schema.Struct({\n  access_token: TrimmedNonEmptyString,\n  issued_token_type: Schema.Literal(RelayAccessTokenType),\n  token_type: Schema.Literal(\"DPoP\"),\n  expires_in: Schema.Int.check(Schema.isGreaterThan(0)),\n  scope: TrimmedNonEmptyString,\n});\nexport type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.Type;\n\nexport const RelayBearerRequestHeaders = Schema.Struct({\n  authorization: TrimmedNonEmptyString,\n});\n\nexport const RelayDpopProofRequestHeaders = Schema.Struct({\n  dpop: TrimmedNonEmptyString,\n});\n\nexport const RelayDpopRequestHeaders = Schema.Struct({\n  authorization: TrimmedNonEmptyString,\n  dpop: TrimmedNonEmptyString,\n});\n\nexport const RelayAuthorizationServerMetadata = Schema.Struct({\n  issuer: TrimmedNonEmptyString,\n  token_endpoint: TrimmedNonEmptyString,\n  grant_types_supported: Schema.Array(Schema.Literal(RelayDpopTokenExchangeGrantType)),\n  token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal(\"none\")),\n  dpop_signing_alg_values_supported: Schema.Array(Schema.Literal(\"ES256\")),\n  scopes_supported: Schema.Array(RelayDpopAccessTokenScope),\n});\n\nexport const RelayProtectedResourceMetadata = Schema.Struct({\n  resource: TrimmedNonEmptyString,\n  authorization_servers: Schema.Array(TrimmedNonEmptyString),\n  scopes_supported: Schema.Array(RelayDpopAccessTokenScope),\n  dpop_bound_access_tokens_required: Schema.Boolean,\n  dpop_signing_alg_values_supported: Schema.Array(Schema.Literal(\"ES256\")),\n});\n\nexport const RelayEnvironmentUnlinkParams = Schema.Struct({\n  environmentId: EnvironmentId,\n});\nexport type RelayEnvironmentUnlinkParams = typeof RelayEnvironmentUnlinkParams.Type;\n\nexport const RelayEnvironmentConnectResponse = Schema.Struct({\n  environmentId: EnvironmentId,\n  endpoint: RelayManagedEndpoint,\n  credential: TrimmedNonEmptyString,\n  expiresAt: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentConnectResponse = typeof RelayEnvironmentConnectResponse.Type;\n\nexport const RelayEnvironmentStatusValue = Schema.Literals([\"online\", \"offline\"]);\nexport type RelayEnvironmentStatusValue = typeof RelayEnvironmentStatusValue.Type;\n\nexport const RelayEnvironmentStatusResponse = Schema.Struct({\n  environmentId: EnvironmentId,\n  endpoint: RelayManagedEndpoint,\n  status: RelayEnvironmentStatusValue,\n  checkedAt: TrimmedNonEmptyString,\n  descriptor: Schema.optional(ExecutionEnvironmentDescriptor),\n  error: Schema.optional(TrimmedNonEmptyString),\n  traceId: Schema.optional(TrimmedNonEmptyString),\n});\nexport type RelayEnvironmentStatusResponse = typeof RelayEnvironmentStatusResponse.Type;\n\nexport const RelayCloudMintCredentialProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  clientProofKeyThumbprint: TrimmedNonEmptyString,\n  cnf: Schema.Struct({\n    jkt: TrimmedNonEmptyString,\n  }),\n  deviceId: Schema.optional(TrimmedNonEmptyString),\n  nonce: TrimmedNonEmptyString,\n  scope: Schema.Array(Schema.Literal(\"environment:connect\")),\n});\nexport type RelayCloudMintCredentialProofPayload = typeof RelayCloudMintCredentialProofPayload.Type;\n\nexport const RelayCloudMintCredentialProof = TrimmedNonEmptyString;\nexport type RelayCloudMintCredentialProof = typeof RelayCloudMintCredentialProof.Type;\n\nexport const RelayCloudMintCredentialRequest = Schema.Struct({\n  proof: RelayCloudMintCredentialProof,\n});\nexport type RelayCloudMintCredentialRequest = typeof RelayCloudMintCredentialRequest.Type;\n\nexport const RelayCloudEnvironmentHealthProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  nonce: TrimmedNonEmptyString,\n  scope: Schema.Array(Schema.Literal(\"environment:status\")),\n});\nexport type RelayCloudEnvironmentHealthProofPayload =\n  typeof RelayCloudEnvironmentHealthProofPayload.Type;\n\nexport const RelayCloudEnvironmentHealthProof = TrimmedNonEmptyString;\nexport type RelayCloudEnvironmentHealthProof = typeof RelayCloudEnvironmentHealthProof.Type;\n\nexport const RelayCloudEnvironmentHealthRequest = Schema.Struct({\n  proof: RelayCloudEnvironmentHealthProof,\n});\nexport type RelayCloudEnvironmentHealthRequest = typeof RelayCloudEnvironmentHealthRequest.Type;\n\nexport const RelayEnvironmentHealthResponseProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  requestNonce: TrimmedNonEmptyString,\n  status: Schema.Literal(\"online\"),\n  descriptor: ExecutionEnvironmentDescriptor,\n  checkedAt: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentHealthResponseProofPayload =\n  typeof RelayEnvironmentHealthResponseProofPayload.Type;\n\nexport const RelayEnvironmentHealthResponse = Schema.Struct({\n  environmentId: EnvironmentId,\n  status: Schema.Literal(\"online\"),\n  descriptor: ExecutionEnvironmentDescriptor,\n  checkedAt: TrimmedNonEmptyString,\n  proof: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentHealthResponse = typeof RelayEnvironmentHealthResponse.Type;\n\nexport const RelayEnvironmentMintResponseProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  clientProofKeyThumbprint: TrimmedNonEmptyString,\n  requestNonce: TrimmedNonEmptyString,\n  credential: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentMintResponseProofPayload =\n  typeof RelayEnvironmentMintResponseProofPayload.Type;\n\nexport const RelayEnvironmentMintResponse = Schema.Struct({\n  credential: TrimmedNonEmptyString,\n  expiresAt: TrimmedNonEmptyString,\n  proof: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentMintResponse = typeof RelayEnvironmentMintResponse.Type;\n\nexport const RelayDeliveryKind = Schema.Literals([\n  \"live_activity_start\",\n  \"live_activity_update\",\n  \"live_activity_end\",\n  \"push_notification\",\n]);\nexport type RelayDeliveryKind = typeof RelayDeliveryKind.Type;\n\nexport const RelayDeliveryResult = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  kind: RelayDeliveryKind,\n  ok: Schema.Boolean,\n  queued: Schema.optional(Schema.Boolean),\n  apnsStatus: Schema.NullOr(Schema.Number),\n  apnsReason: Schema.NullOr(Schema.String),\n  apnsId: Schema.NullOr(Schema.String),\n});\nexport type RelayDeliveryResult = typeof RelayDeliveryResult.Type;\n\nexport const RelayOkResponse = Schema.Struct({\n  ok: Schema.Boolean,\n});\nexport type RelayOkResponse = typeof RelayOkResponse.Type;\n\nexport const RelayPublishResponse = Schema.Struct({\n  ok: Schema.Boolean,\n  deliveries: Schema.Array(RelayDeliveryResult),\n});\nexport type RelayPublishResponse = typeof RelayPublishResponse.Type;\n\nexport const RelayHealthResponse = Schema.Struct({\n  ok: Schema.Boolean,\n  service: Schema.Literal(\"relay\"),\n});\nexport type RelayHealthResponse = typeof RelayHealthResponse.Type;\n\nexport const RelayHealthGroup = HttpApiGroup.make(\"health\")\n  .add(\n    HttpApiEndpoint.get(\"health\", \"/health\", {\n      success: RelayHealthResponse,\n      error: RelayInternalError,\n    }).annotate(OpenApi.Summary, \"Check relay health\"),\n  )\n  .annotate(OpenApi.Description, \"Service health and readiness.\");\n\nexport const RelayMetadataGroup = HttpApiGroup.make(\"metadata\")\n  .add(\n    HttpApiEndpoint.get(\"authorizationServer\", \"/.well-known/oauth-authorization-server\", {\n      success: RelayAuthorizationServerMetadata,\n    }).annotate(OpenApi.Summary, \"Read OAuth authorization-server metadata\"),\n    HttpApiEndpoint.get(\"protectedResource\", \"/.well-known/oauth-protected-resource\", {\n      success: RelayProtectedResourceMetadata,\n    }).annotate(OpenApi.Summary, \"Read OAuth protected-resource metadata\"),\n  )\n  .annotate(OpenApi.Description, \"OAuth and DPoP discovery metadata.\");\n\nexport const RelayRegisterDeviceEndpoint = HttpApiEndpoint.post(\n  \"registerDevice\",\n  \"/v1/mobile/devices\",\n  {\n    headers: RelayDpopRequestHeaders,\n    payload: RelayDeviceRegistrationRequest,\n    success: RelayOkResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Register or update a mobile device\");\n\nexport const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post(\n  \"registerLiveActivity\",\n  \"/v1/mobile/live-activities\",\n  {\n    headers: RelayDpopRequestHeaders,\n    payload: RelayLiveActivityRegistrationRequest,\n    success: RelayOkResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Register a Live Activity push token\");\n\nexport const RelayAgentActivitySnapshotResponse = Schema.Struct({\n  aggregate: Schema.NullOr(RelayAgentActivityAggregateState),\n});\nexport type RelayAgentActivitySnapshotResponse = typeof RelayAgentActivitySnapshotResponse.Type;\n\n// Lets the app decide whether arming a Live Activity is worthwhile before\n// creating one (no empty lock-screen card when nothing is running) and seed\n// the card with the real aggregate instead of a placeholder.\nexport const RelayAgentActivitySnapshotEndpoint = HttpApiEndpoint.get(\n  \"getAgentActivitySnapshot\",\n  \"/v1/mobile/agent-activity\",\n  {\n    headers: RelayDpopRequestHeaders,\n    success: RelayAgentActivitySnapshotResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Read the current Live Activity aggregate\");\n\nexport const RelayUnregisterDeviceEndpoint = HttpApiEndpoint.delete(\n  \"unregisterDevice\",\n  \"/v1/mobile/devices/:deviceId\",\n  {\n    headers: RelayDpopRequestHeaders,\n    params: RelayDeviceUnregistrationParams,\n    success: RelayOkResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Unregister a mobile device\");\n\nexport const RelayMobileGroup = HttpApiGroup.make(\"mobile\")\n  .add(\n    RelayRegisterDeviceEndpoint,\n    RelayRegisterLiveActivityEndpoint,\n    RelayAgentActivitySnapshotEndpoint,\n    RelayUnregisterDeviceEndpoint,\n  )\n  .annotate(OpenApi.Description, \"Mobile push-notification and Live Activity registration.\")\n  .middleware(RelayDpopClientAuth);\n\nexport const RelayClientGroup = HttpApiGroup.make(\"client\")\n  .add(\n    HttpApiEndpoint.get(\"listEnvironments\", \"/v1/environments\", {\n      headers: RelayBearerRequestHeaders,\n      success: RelayListEnvironmentsResponse,\n      error: RelayAuthAndInternalErrors,\n    }).annotate(OpenApi.Summary, \"List linked environments\"),\n    HttpApiEndpoint.get(\"listDevices\", \"/v1/client/devices\", {\n      headers: RelayBearerRequestHeaders,\n      success: RelayListDevicesResponse,\n      error: RelayAuthAndInternalErrors,\n    }).annotate(OpenApi.Summary, \"List registered mobile devices\"),\n    HttpApiEndpoint.post(\"linkEnvironment\", \"/v1/client/environment-links\", {\n      headers: RelayBearerRequestHeaders,\n      payload: RelayEnvironmentLinkRequest,\n      success: RelayEnvironmentLinkResponse,\n      error: RelayEnvironmentLinkErrors,\n    }).annotate(OpenApi.Summary, \"Link an environment\"),\n    HttpApiEndpoint.post(\n      \"createEnvironmentLinkChallenge\",\n      \"/v1/client/environment-link-challenges\",\n      {\n        headers: RelayBearerRequestHeaders,\n        payload: RelayEnvironmentLinkChallengeRequest,\n        success: RelayEnvironmentLinkChallengeResponse,\n        error: RelayAuthAndInternalErrors,\n      },\n    ).annotate(OpenApi.Summary, \"Create an environment-link challenge\"),\n    HttpApiEndpoint.delete(\"unlinkEnvironment\", \"/v1/client/environment-links/:environmentId\", {\n      headers: RelayBearerRequestHeaders,\n      params: RelayEnvironmentUnlinkParams,\n      success: RelayOkResponse,\n      error: RelayAuthAndInternalErrors,\n    }).annotate(OpenApi.Summary, \"Unlink an environment\"),\n    HttpApiEndpoint.delete(\n      \"releaseEnvironmentTunnel\",\n      \"/v1/client/environment-links/:environmentId/tunnel\",\n      {\n        headers: RelayBearerRequestHeaders,\n        params: RelayEnvironmentUnlinkParams,\n        success: RelayOkResponse,\n        error: RelayAuthAndInternalErrors,\n      },\n    )\n      .annotate(OpenApi.Summary, \"Release an environment's managed tunnel\")\n      .annotate(\n        OpenApi.Description,\n        \"Deletes the provisioned Cloudflare tunnel while keeping the environment link and its hostname reservation, so a later link re-provisions the tunnel under the same URL. Environments call this when they shut down; Cloudflare bills per provisioned tunnel, so idle tunnels should not outlive their environment.\",\n      ),\n  )\n  .annotate(OpenApi.Description, \"Cloud-user environment links and registered devices.\")\n  .middleware(RelayClientAuth);\n\nexport const RelayExchangeDpopAccessTokenEndpoint = HttpApiEndpoint.post(\n  \"exchangeDpopAccessToken\",\n  \"/v1/client/dpop-token\",\n  {\n    headers: RelayDpopProofRequestHeaders,\n    payload: RelayDpopAccessTokenRequest,\n    success: RelayDpopAccessTokenResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n)\n  .annotate(OpenApi.Summary, \"Exchange a Clerk token for a DPoP access token\")\n  .annotate(\n    OpenApi.Description,\n    \"Bootstrap endpoint. Send the DPoP proof JWT in the dpop header and the Clerk token in subject_token. The returned access token is bound to the proof key.\",\n  );\n\nexport const RelayTokenGroup = HttpApiGroup.make(\"token\")\n  .add(RelayExchangeDpopAccessTokenEndpoint)\n  .annotate(OpenApi.Description, \"OAuth token exchange for DPoP-bound client access.\");\n\nexport const RelayConnectEnvironmentEndpoint = HttpApiEndpoint.post(\n  \"connectEnvironment\",\n  \"/v1/environments/:environmentId/connect\",\n  {\n    headers: RelayDpopRequestHeaders,\n    params: Schema.Struct({\n      environmentId: EnvironmentId,\n    }),\n    payload: RelayEnvironmentConnectRequest,\n    success: RelayEnvironmentConnectResponse,\n    error: RelayEnvironmentConnectErrors,\n  },\n).annotate(OpenApi.Summary, \"Connect to an environment\");\n\nexport const RelayGetEnvironmentStatusEndpoint = HttpApiEndpoint.post(\n  \"getEnvironmentStatus\",\n  \"/v1/environments/:environmentId/status\",\n  {\n    headers: RelayDpopRequestHeaders,\n    params: Schema.Struct({\n      environmentId: EnvironmentId,\n    }),\n    success: RelayEnvironmentStatusResponse,\n    error: RelayEnvironmentConnectErrors,\n  },\n).annotate(OpenApi.Summary, \"Check environment status\");\n\nexport const RelayDpopClientGroup = HttpApiGroup.make(\"dpopClient\")\n  .add(RelayConnectEnvironmentEndpoint, RelayGetEnvironmentStatusEndpoint)\n  .annotate(OpenApi.Description, \"DPoP-authenticated client access to linked environments.\")\n  .middleware(RelayDpopClientAuth);\n\nexport const RelayServerGroup = HttpApiGroup.make(\"server\")\n  .add(\n    HttpApiEndpoint.post(\n      \"publishAgentActivity\",\n      \"/v1/environments/:environmentId/threads/:threadId/agent-activity\",\n      {\n        params: Schema.Struct({\n          environmentId: EnvironmentId,\n          threadId: ThreadId,\n        }),\n        payload: RelayAgentActivityPublishRequest,\n        success: RelayPublishResponse,\n        error: RelayAgentActivityPublishErrors,\n      },\n    ).annotate(OpenApi.Summary, \"Publish agent activity\"),\n  )\n  .annotate(OpenApi.Description, \"Environment-authenticated activity publication.\")\n  .middleware(RelayEnvironmentAuth);\n\nexport const RelayApi = HttpApi.make(\"RelayApi\")\n  .add(\n    RelayHealthGroup,\n    RelayMetadataGroup,\n    RelayMobileGroup,\n    RelayClientGroup,\n    RelayTokenGroup,\n    RelayDpopClientGroup,\n    RelayServerGroup,\n  )\n  .annotate(OpenApi.Title, \"AgentLink Relay API\")\n  .annotate(OpenApi.Version, \"1.0.0\")\n  .annotate(\n    OpenApi.Description,\n    \"Control-plane API for linking T3 environments, connecting authorized clients, and publishing agent activity.\",\n  );\nexport type RelayApi = typeof RelayApi;\n","import * as Context from \"effect/Context\";\nimport type * as DateTime from \"effect/DateTime\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpApi from \"effect/unstable/httpapi/HttpApi\";\nimport * as HttpApiEndpoint from \"effect/unstable/httpapi/HttpApiEndpoint\";\nimport * as HttpApiGroup from \"effect/unstable/httpapi/HttpApiGroup\";\nimport * as HttpApiMiddleware from \"effect/unstable/httpapi/HttpApiMiddleware\";\nimport * as HttpServerRespondable from \"effect/unstable/http/HttpServerRespondable\";\nimport * as HttpServerResponse from \"effect/unstable/http/HttpServerResponse\";\n\nimport {\n  AuthAccessTokenResult,\n  AuthBrowserSessionRequest,\n  AuthBrowserSessionResult,\n  AuthClientSession,\n  AuthCreatePairingCredentialInput,\n  AuthPairingCredentialResult,\n  AuthPairingLink,\n  AuthRevokeClientSessionInput,\n  AuthRevokePairingLinkInput,\n  AuthEnvironmentScope,\n  AuthTokenExchangeRequest,\n  AuthSessionState,\n  AuthWebSocketTicketResult,\n  ServerAuthSessionMethod,\n} from \"./auth.ts\";\nimport { AuthSessionId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { ExecutionEnvironmentDescriptor } from \"./environment.ts\";\nimport {\n  ClientOrchestrationCommand,\n  DispatchResult,\n  OrchestrationReadModel,\n  OrchestrationShellSnapshot,\n  OrchestrationThreadDetailSnapshot,\n} from \"./orchestration.ts\";\nimport {\n  RelayCloudEnvironmentHealthRequest,\n  RelayCloudMintCredentialRequest,\n  RelayEnvironmentConfigRequest,\n  RelayEnvironmentHealthResponse,\n  RelayEnvironmentLinkProof,\n  RelayEnvironmentMintResponse,\n  RelayLinkProofRequest,\n} from \"./relay.ts\";\n\nconst OptionalBearerHeaders = Schema.Struct({\n  authorization: Schema.optionalKey(Schema.String),\n  dpop: Schema.optionalKey(Schema.String),\n});\n\nconst OptionalDpopProofHeaders = Schema.Struct({\n  dpop: Schema.optionalKey(Schema.String),\n});\n\nexport const EnvironmentRequestInvalidReason = Schema.Literals([\n  \"invalid_scope\",\n  \"scope_not_granted\",\n  \"invalid_command\",\n]);\nexport type EnvironmentRequestInvalidReason = typeof EnvironmentRequestInvalidReason.Type;\n\nexport const EnvironmentAuthInvalidReason = Schema.Literals([\n  \"missing_credential\",\n  \"invalid_credential\",\n]);\nexport type EnvironmentAuthInvalidReason = typeof EnvironmentAuthInvalidReason.Type;\n\nexport const EnvironmentOperationForbiddenReason = Schema.Literals([\n  \"current_session_revoke_not_allowed\",\n]);\nexport type EnvironmentOperationForbiddenReason = typeof EnvironmentOperationForbiddenReason.Type;\n\nexport const EnvironmentInternalErrorReason = Schema.Literals([\n  \"bootstrap_validation_failed\",\n  \"browser_session_issuance_failed\",\n  \"browser_session_cookie_failed\",\n  \"access_token_issuance_failed\",\n  \"websocket_ticket_issuance_failed\",\n  \"pairing_credential_issuance_failed\",\n  \"pairing_links_load_failed\",\n  \"pairing_link_revoke_failed\",\n  \"client_sessions_load_failed\",\n  \"client_session_revoke_failed\",\n  \"orchestration_snapshot_failed\",\n  \"orchestration_thread_snapshot_failed\",\n  \"orchestration_dispatch_failed\",\n  \"internal_error\",\n]);\nexport type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type;\n\nexport class EnvironmentRequestInvalidError extends Schema.TaggedErrorClass<EnvironmentRequestInvalidError>()(\n  \"EnvironmentRequestInvalidError\",\n  {\n    code: Schema.Literal(\"invalid_request\"),\n    reason: EnvironmentRequestInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 400 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentRequestInvalidError)(this, { status: 400 });\n  }\n}\n\nexport class EnvironmentAuthInvalidError extends Schema.TaggedErrorClass<EnvironmentAuthInvalidError>()(\n  \"EnvironmentAuthInvalidError\",\n  {\n    code: Schema.Literal(\"auth_invalid\"),\n    reason: EnvironmentAuthInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentAuthInvalidError)(this, { status: 401 });\n  }\n}\n\nexport class EnvironmentScopeRequiredError extends Schema.TaggedErrorClass<EnvironmentScopeRequiredError>()(\n  \"EnvironmentScopeRequiredError\",\n  {\n    code: Schema.Literal(\"insufficient_scope\"),\n    requiredScope: AuthEnvironmentScope,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentScopeRequiredError)(this, { status: 403 });\n  }\n}\n\nexport class EnvironmentOperationForbiddenError extends Schema.TaggedErrorClass<EnvironmentOperationForbiddenError>()(\n  \"EnvironmentOperationForbiddenError\",\n  {\n    code: Schema.Literal(\"operation_forbidden\"),\n    reason: EnvironmentOperationForbiddenReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentOperationForbiddenError)(this, { status: 403 });\n  }\n}\n\nexport class EnvironmentInternalError extends Schema.TaggedErrorClass<EnvironmentInternalError>()(\n  \"EnvironmentInternalError\",\n  {\n    code: Schema.Literal(\"internal_error\"),\n    reason: EnvironmentInternalErrorReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 500 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentInternalError)(this, { status: 500 });\n  }\n}\n\nexport const EnvironmentResourceNotFoundReason = Schema.Literals([\"thread_not_found\"]);\nexport type EnvironmentResourceNotFoundReason = typeof EnvironmentResourceNotFoundReason.Type;\n\nexport class EnvironmentResourceNotFoundError extends Schema.TaggedErrorClass<EnvironmentResourceNotFoundError>()(\n  \"EnvironmentResourceNotFoundError\",\n  {\n    code: Schema.Literal(\"not_found\"),\n    reason: EnvironmentResourceNotFoundReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 404 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentResourceNotFoundError)(this, { status: 404 });\n  }\n}\n\nexport const EnvironmentHttpCommonError = Schema.Union([\n  EnvironmentRequestInvalidError,\n  EnvironmentAuthInvalidError,\n  EnvironmentScopeRequiredError,\n  EnvironmentOperationForbiddenError,\n  EnvironmentResourceNotFoundError,\n  EnvironmentInternalError,\n]);\nexport type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;\n\nconst EnvironmentAuthenticationErrors = [\n  EnvironmentAuthInvalidError,\n  EnvironmentInternalError,\n] as const;\n\nexport class EnvironmentHttpBadRequestError extends Schema.TaggedErrorClass<EnvironmentHttpBadRequestError>()(\n  \"EnvironmentHttpBadRequestError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 400 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpBadRequestError)(this, { status: 400 });\n  }\n}\n\nexport class EnvironmentHttpUnauthorizedError extends Schema.TaggedErrorClass<EnvironmentHttpUnauthorizedError>()(\n  \"EnvironmentHttpUnauthorizedError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 401 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpUnauthorizedError)(this, { status: 401 });\n  }\n}\n\nexport class EnvironmentHttpForbiddenError extends Schema.TaggedErrorClass<EnvironmentHttpForbiddenError>()(\n  \"EnvironmentHttpForbiddenError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 403 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpForbiddenError)(this, { status: 403 });\n  }\n}\n\nexport class EnvironmentHttpInternalServerError extends Schema.TaggedErrorClass<EnvironmentHttpInternalServerError>()(\n  \"EnvironmentHttpInternalServerError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 500 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpInternalServerError)(this, { status: 500 });\n  }\n}\n\nexport class EnvironmentHttpConflictError extends Schema.TaggedErrorClass<EnvironmentHttpConflictError>()(\n  \"EnvironmentHttpConflictError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 409 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpConflictError)(this, { status: 409 });\n  }\n}\n\nexport class EnvironmentCloudEndpointUnavailableError extends Schema.TaggedErrorClass<EnvironmentCloudEndpointUnavailableError>()(\n  \"EnvironmentCloudEndpointUnavailableError\",\n  {\n    message: Schema.String,\n    endpointRuntimeStatus: Schema.Unknown,\n  },\n  { httpApiStatus: 503 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentCloudEndpointUnavailableError)(this, {\n      status: 503,\n    });\n  }\n}\nconst EnvironmentSessionCreationErrors = [\n  EnvironmentAuthInvalidError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentTokenExchangeErrors = [\n  EnvironmentRequestInvalidError,\n  EnvironmentAuthInvalidError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentScopedOperationErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentPairingCredentialErrors = [\n  EnvironmentRequestInvalidError,\n  ...EnvironmentScopedOperationErrors,\n] as const;\nconst EnvironmentSessionRevokeErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentOperationForbiddenError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentOrchestrationSnapshotErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentOrchestrationThreadSnapshotErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentResourceNotFoundError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentOrchestrationDispatchErrors = [\n  EnvironmentRequestInvalidError,\n  EnvironmentScopeRequiredError,\n  EnvironmentInternalError,\n] as const;\n\nexport interface EnvironmentSessionPrincipalShape {\n  readonly sessionId: AuthSessionId;\n  readonly subject: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly scopes: ReadonlySet<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt?: DateTime.DateTime;\n}\n\nexport class EnvironmentAuthenticatedPrincipal extends Context.Service<\n  EnvironmentAuthenticatedPrincipal,\n  EnvironmentSessionPrincipalShape\n>()(\"@t3tools/contracts/environmentHttp/EnvironmentAuthenticatedPrincipal\") {}\n\nexport class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service<\n  EnvironmentAuthenticatedAuth,\n  { provides: EnvironmentAuthenticatedPrincipal }\n>()(\"EnvironmentAuthenticatedAuth\", {\n  error: EnvironmentAuthenticationErrors,\n}) {}\n\nconst EnvironmentHttpCloudErrors = [\n  EnvironmentHttpBadRequestError,\n  EnvironmentHttpUnauthorizedError,\n  EnvironmentHttpForbiddenError,\n  EnvironmentHttpConflictError,\n  EnvironmentHttpInternalServerError,\n  EnvironmentScopeRequiredError,\n] as const;\n\nexport const EnvironmentCloudRelayConfigResult = Schema.Struct({\n  ok: Schema.Boolean,\n  endpointRuntimeStatus: Schema.Unknown,\n});\nexport type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type;\n\nexport const EnvironmentCloudLinkStateResult = Schema.Struct({\n  linked: Schema.Boolean,\n  cloudUserId: Schema.NullOr(Schema.String),\n  relayUrl: Schema.NullOr(Schema.String),\n  relayIssuer: Schema.NullOr(Schema.String),\n  // A managed Cloudflare tunnel is provisioned for this link. False for a\n  // publish-only link (activity publishing without a relay-managed tunnel), so\n  // clients can present the two capabilities as independent settings.\n  // Optional so newer clients tolerate older environment servers.\n  managedTunnelActive: Schema.optional(Schema.Boolean),\n  publishAgentActivity: Schema.Boolean,\n});\nexport type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;\n\nexport const EnvironmentCloudPreferencesRequest = Schema.Struct({\n  publishAgentActivity: Schema.Boolean,\n});\nexport type EnvironmentCloudPreferencesRequest = typeof EnvironmentCloudPreferencesRequest.Type;\n\nexport const AuthPairingLinkRevokeResult = Schema.Struct({\n  revoked: Schema.Boolean,\n});\nexport type AuthPairingLinkRevokeResult = typeof AuthPairingLinkRevokeResult.Type;\n\nexport const AuthClientSessionRevokeResult = Schema.Struct({\n  revoked: Schema.Boolean,\n});\nexport type AuthClientSessionRevokeResult = typeof AuthClientSessionRevokeResult.Type;\n\nexport const AuthOtherClientSessionsRevokeResult = Schema.Struct({\n  revokedCount: Schema.Number,\n});\nexport type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;\n\nexport class EnvironmentMetadataHttpApi extends HttpApiGroup.make(\"metadata\").add(\n  HttpApiEndpoint.get(\"descriptor\", \"/.well-known/t3/environment\", {\n    success: ExecutionEnvironmentDescriptor,\n  }),\n) {}\n\nexport class EnvironmentAuthHttpApi extends HttpApiGroup.make(\"auth\")\n  .add(\n    HttpApiEndpoint.get(\"session\", \"/api/auth/session\", {\n      headers: OptionalBearerHeaders,\n      success: AuthSessionState,\n      error: [EnvironmentInternalError],\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"browserSession\", \"/api/auth/browser-session\", {\n      payload: AuthBrowserSessionRequest,\n      success: AuthBrowserSessionResult,\n      error: EnvironmentSessionCreationErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"token\", \"/oauth/token\", {\n      headers: OptionalDpopProofHeaders,\n      payload: AuthTokenExchangeRequest,\n      success: AuthAccessTokenResult,\n      error: EnvironmentTokenExchangeErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"webSocketTicket\", \"/api/auth/websocket-ticket\", {\n      headers: OptionalBearerHeaders,\n      success: AuthWebSocketTicketResult,\n      error: [EnvironmentInternalError],\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"pairingCredential\", \"/api/auth/pairing-token\", {\n      headers: OptionalBearerHeaders,\n      payload: AuthCreatePairingCredentialInput,\n      success: AuthPairingCredentialResult,\n      error: EnvironmentPairingCredentialErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"pairingLinks\", \"/api/auth/pairing-links\", {\n      headers: OptionalBearerHeaders,\n      success: Schema.Array(AuthPairingLink),\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"revokePairingLink\", \"/api/auth/pairing-links/revoke\", {\n      headers: OptionalBearerHeaders,\n      payload: AuthRevokePairingLinkInput,\n      success: AuthPairingLinkRevokeResult,\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"clients\", \"/api/auth/clients\", {\n      headers: OptionalBearerHeaders,\n      success: Schema.Array(AuthClientSession),\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"revokeClient\", \"/api/auth/clients/revoke\", {\n      headers: OptionalBearerHeaders,\n      payload: AuthRevokeClientSessionInput,\n      success: AuthClientSessionRevokeResult,\n      error: EnvironmentSessionRevokeErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"revokeOtherClients\", \"/api/auth/clients/revoke-others\", {\n      headers: OptionalBearerHeaders,\n      success: AuthOtherClientSessionsRevokeResult,\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  ) {}\n\nconst EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({\n  threadId: ThreadId,\n});\n\nexport class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make(\"orchestration\")\n  .add(\n    HttpApiEndpoint.get(\"snapshot\", \"/api/orchestration/snapshot\", {\n      headers: OptionalBearerHeaders,\n      success: OrchestrationReadModel,\n      error: EnvironmentOrchestrationSnapshotErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"shellSnapshot\", \"/api/orchestration/shell\", {\n      headers: OptionalBearerHeaders,\n      success: OrchestrationShellSnapshot,\n      error: EnvironmentOrchestrationSnapshotErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"threadSnapshot\", \"/api/orchestration/threads/:threadId\", {\n      headers: OptionalBearerHeaders,\n      params: EnvironmentOrchestrationThreadSnapshotParams,\n      success: OrchestrationThreadDetailSnapshot,\n      error: EnvironmentOrchestrationThreadSnapshotErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"dispatch\", \"/api/orchestration/dispatch\", {\n      headers: OptionalBearerHeaders,\n      payload: ClientOrchestrationCommand,\n      success: DispatchResult,\n      error: EnvironmentOrchestrationDispatchErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  ) {}\n\nexport class EnvironmentConnectHttpApi extends HttpApiGroup.make(\"connect\")\n  .add(\n    HttpApiEndpoint.post(\"linkProof\", \"/api/connect/link-proof\", {\n      headers: OptionalBearerHeaders,\n      payload: RelayLinkProofRequest,\n      success: RelayEnvironmentLinkProof,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"relayConfig\", \"/api/connect/relay-config\", {\n      headers: OptionalBearerHeaders,\n      payload: RelayEnvironmentConfigRequest,\n      success: EnvironmentCloudRelayConfigResult,\n      error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"linkState\", \"/api/connect/link-state\", {\n      headers: OptionalBearerHeaders,\n      success: EnvironmentCloudLinkStateResult,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"unlink\", \"/api/connect/unlink\", {\n      headers: OptionalBearerHeaders,\n      success: EnvironmentCloudRelayConfigResult,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"preferences\", \"/api/connect/preferences\", {\n      headers: OptionalBearerHeaders,\n      payload: EnvironmentCloudPreferencesRequest,\n      success: EnvironmentCloudLinkStateResult,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"health\", \"/api/t3-connect/health\", {\n      payload: RelayCloudEnvironmentHealthRequest,\n      success: RelayEnvironmentHealthResponse,\n      error: EnvironmentHttpCloudErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"mintCredential\", \"/api/connect/mint-credential\", {\n      payload: RelayCloudMintCredentialRequest,\n      success: RelayEnvironmentMintResponse,\n      error: EnvironmentHttpCloudErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"t3MintCredential\", \"/api/t3-connect/mint-credential\", {\n      payload: RelayCloudMintCredentialRequest,\n      success: RelayEnvironmentMintResponse,\n      error: EnvironmentHttpCloudErrors,\n    }),\n  ) {}\n\nexport class EnvironmentHttpApi extends HttpApi.make(\"environment\")\n  .add(EnvironmentMetadataHttpApi)\n  .add(EnvironmentAuthHttpApi)\n  .add(EnvironmentOrchestrationHttpApi)\n  .add(EnvironmentConnectHttpApi) {}\n","import * as Schema from \"effect/Schema\";\n\nexport const RelayClientStatusSchema = Schema.Union([\n  Schema.Struct({\n    status: Schema.Literal(\"available\"),\n    executablePath: Schema.String,\n    source: Schema.Literals([\"override\", \"managed\", \"path\"]),\n    version: Schema.String,\n  }),\n  Schema.Struct({\n    status: Schema.Literal(\"missing\"),\n    version: Schema.String,\n  }),\n  Schema.Struct({\n    status: Schema.Literal(\"unsupported\"),\n    platform: Schema.String,\n    arch: Schema.String,\n    version: Schema.String,\n  }),\n]);\nexport type RelayClientStatus = typeof RelayClientStatusSchema.Type;\n\nexport const RelayClientInstallProgressStageSchema = Schema.Literals([\n  \"checking\",\n  \"waiting_for_lock\",\n  \"downloading\",\n  \"verifying\",\n  \"installing\",\n  \"validating\",\n  \"activating\",\n]);\nexport type RelayClientInstallProgressStage = typeof RelayClientInstallProgressStageSchema.Type;\n\nexport const RelayClientInstallProgressEventSchema = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"progress\"),\n    stage: RelayClientInstallProgressStageSchema,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"complete\"),\n    status: RelayClientStatusSchema,\n  }),\n]);\nexport type RelayClientInstallProgressEvent = typeof RelayClientInstallProgressEventSchema.Type;\n\nexport const RelayClientInstallFailureReasonSchema = Schema.Literals([\n  \"download_failed\",\n  \"invalid_checksum\",\n  \"install_locked\",\n  \"override_missing\",\n  \"unsupported_platform\",\n  \"validation_failed\",\n  \"write_failed\",\n]);\nexport type RelayClientInstallFailureReason = typeof RelayClientInstallFailureReasonSchema.Type;\n\nexport class RelayClientInstallFailedError extends Schema.TaggedErrorClass<RelayClientInstallFailedError>()(\n  \"RelayClientInstallFailedError\",\n  {\n    reason: RelayClientInstallFailureReasonSchema,\n    message: Schema.String,\n  },\n) {}\n","import * as Schema from \"effect/Schema\";\n\nimport { PortSchema, PositiveInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const DesktopBackendBootstrap = Schema.Struct({\n  mode: Schema.Literal(\"desktop\"),\n  noBrowser: Schema.Boolean,\n  port: PortSchema,\n  // Omitted when the desktop launches the backend inside WSL, since the\n  // Windows-side baseDir maps to /mnt/c/... and the Linux side should use its\n  // own home directory instead.\n  t3Home: Schema.optional(Schema.String),\n  host: Schema.String,\n  desktopBootstrapToken: Schema.String,\n  tailscaleServeEnabled: Schema.Boolean,\n  tailscaleServePort: PortSchema,\n  otlpTracesUrl: Schema.optional(Schema.String),\n  otlpMetricsUrl: Schema.optional(Schema.String),\n  desktopTelemetryFd: Schema.optionalKey(PositiveInt),\n  desktopTelemetryControlFd: Schema.optionalKey(PositiveInt),\n  resourceMonitorPath: Schema.optionalKey(TrimmedNonEmptyString),\n});\n\nexport type DesktopBackendBootstrap = typeof DesktopBackendBootstrap.Type;\n","import * as Schema from \"effect/Schema\";\n\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const AdvertisedEndpointProviderKind = Schema.Literals([\n  \"core\",\n  \"private-network\",\n  \"tunnel\",\n  \"manual\",\n]);\nexport type AdvertisedEndpointProviderKind = typeof AdvertisedEndpointProviderKind.Type;\n\nexport const AdvertisedEndpointReachability = Schema.Literals([\n  \"loopback\",\n  \"lan\",\n  \"private-network\",\n  \"public\",\n]);\nexport type AdvertisedEndpointReachability = typeof AdvertisedEndpointReachability.Type;\n\nexport const AdvertisedEndpointHostedHttpsCompatibility = Schema.Literals([\n  \"compatible\",\n  \"mixed-content-blocked\",\n  \"requires-configuration\",\n  \"unknown\",\n]);\nexport type AdvertisedEndpointHostedHttpsCompatibility =\n  typeof AdvertisedEndpointHostedHttpsCompatibility.Type;\n\nexport const AdvertisedEndpointStatus = Schema.Literals([\"available\", \"unavailable\", \"unknown\"]);\nexport type AdvertisedEndpointStatus = typeof AdvertisedEndpointStatus.Type;\n\nexport const AdvertisedEndpointSource = Schema.Literals([\n  \"desktop-core\",\n  \"desktop-addon\",\n  \"server\",\n  \"user\",\n]);\nexport type AdvertisedEndpointSource = typeof AdvertisedEndpointSource.Type;\n\nexport const AdvertisedEndpointProvider = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  kind: AdvertisedEndpointProviderKind,\n  isAddon: Schema.Boolean,\n});\nexport type AdvertisedEndpointProvider = typeof AdvertisedEndpointProvider.Type;\n\nexport const AdvertisedEndpointCompatibility = Schema.Struct({\n  hostedHttpsApp: AdvertisedEndpointHostedHttpsCompatibility,\n  desktopApp: Schema.Literals([\"compatible\", \"unknown\"]),\n});\nexport type AdvertisedEndpointCompatibility = typeof AdvertisedEndpointCompatibility.Type;\n\nexport const AdvertisedEndpoint = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  provider: AdvertisedEndpointProvider,\n  httpBaseUrl: TrimmedNonEmptyString,\n  wsBaseUrl: TrimmedNonEmptyString,\n  reachability: AdvertisedEndpointReachability,\n  compatibility: AdvertisedEndpointCompatibility,\n  source: AdvertisedEndpointSource,\n  status: AdvertisedEndpointStatus,\n  isDefault: Schema.optional(Schema.Boolean),\n  description: Schema.optional(TrimmedNonEmptyString),\n});\nexport type AdvertisedEndpoint = typeof AdvertisedEndpoint.Type;\n","import * as Channel from \"./Channel.js\";\nimport * as Effect from \"./Effect.js\";\nimport { dual } from \"./Function.js\";\nimport * as Schema from \"./Schema.js\";\n/**\n * Creates a channel that encodes non-empty chunks of schema values into the\n * schema's encoded representation.\n *\n * **When to use**\n *\n * Use to encode typed channel input into the schema's encoded representation\n * before passing chunks to an encoded downstream boundary.\n *\n * **Details**\n *\n * Encoding failures are emitted as `SchemaError`, and any encoding services\n * required by the schema become channel requirements.\n *\n * @see {@link encodeUnknown} for encoded output chunks that should be typed as `unknown`\n * @see {@link decode} for the inverse channel that decodes encoded chunks into schema values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const encode = schema => () => {\n  const encode = Schema.encodeEffect(Schema.NonEmptyArray(schema));\n  return Channel.fromTransform((upstream, _scope) => Effect.succeed(Effect.flatMap(upstream, chunk => encode(chunk))));\n};\n/**\n * Creates an `encode` channel variant whose encoded output chunks are typed as\n * `unknown`.\n *\n * **When to use**\n *\n * Use when a channel boundary should encode typed input chunks while the encoded\n * output representation is intentionally untyped.\n *\n * @see {@link encode} for the variant that preserves the schema encoded type\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const encodeUnknown = encode;\n/**\n * Creates a channel that decodes non-empty chunks from the schema's encoded\n * representation into schema values.\n *\n * **When to use**\n *\n * Use to validate and decode encoded channel output into typed schema values\n * before application code consumes it.\n *\n * **Details**\n *\n * Decoding failures are emitted as `SchemaError`, and any decoding services\n * required by the schema become channel requirements.\n *\n * @see {@link decodeUnknown} for boundaries where the encoded input side is intentionally untyped\n * @see {@link encode} for the inverse adapter that encodes typed schema values\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const decode = schema => () => {\n  const decode = Schema.decodeEffect(Schema.NonEmptyArray(schema));\n  return Channel.fromTransform((upstream, _scope) => Effect.succeed(Effect.flatMap(upstream, chunk => decode(chunk))));\n};\n/**\n * Creates a `decode` channel variant for schema-decoding channel boundaries.\n *\n * **When to use**\n *\n * Use when you need an intentionally unknown or untyped encoded input while\n * keeping only the decoded output statically typed according to the schema.\n *\n * **Details**\n *\n * The channel decodes non-empty encoded chunks into schema values, emits\n * `SchemaError` when decoding fails, and requires the schema's decoding\n * services.\n *\n * @see {@link decode} for the typed variant that preserves the schema's encoded type\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const decodeUnknown = decode;\n/**\n * Wraps a channel so callers work with typed input and output chunks while the\n * wrapped channel uses encoded chunks.\n *\n * **When to use**\n *\n * Use to expose typed input and output at a bidirectional channel boundary\n * while the wrapped channel continues to operate on schema-encoded chunks.\n *\n * **Details**\n *\n * Values sent into the resulting channel are encoded with `inputSchema` before\n * reaching the wrapped channel. Values emitted by the wrapped channel are\n * decoded with `outputSchema` before they are emitted downstream. Schema\n * failures are surfaced as `SchemaError`.\n *\n * @see {@link duplexUnknown} for the variant whose encoded side is intentionally untyped\n * @see {@link encode} for encoding typed chunks at one-way channel boundaries\n * @see {@link decode} for decoding encoded chunks at one-way channel boundaries\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const duplex = /*#__PURE__*/dual(2, (self, options) => encode(options.inputSchema)().pipe(Channel.pipeTo(self), Channel.pipeTo(decode(options.outputSchema)())));\n/**\n * Wraps a bidirectional channel whose encoded chunks are typed as `unknown`.\n *\n * **When to use**\n *\n * Use when you need a bidirectional channel to cross an encoded boundary whose\n * chunk types are intentionally erased, while callers send and receive\n * schema-typed chunks.\n *\n * **Details**\n *\n * The resulting channel accepts typed input chunks, encodes them with\n * `inputSchema`, decodes unknown output chunks with `outputSchema`, and\n * surfaces schema failures as `SchemaError`.\n *\n * @see {@link duplex} for the variant that preserves the schema encoded types on the wrapped channel\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const duplexUnknown = duplex;\n//# sourceMappingURL=ChannelSchema.js.map","/**\n * The `PrimaryKey` module defines a small protocol for values that can expose\n * a stable, string-based identifier. A value participates by implementing a\n * method at {@link symbol}; consumers can check unknown values with\n * {@link isPrimaryKey} and read the key with {@link value}.\n *\n * @since 2.0.0\n */\nimport { hasProperty } from \"./Predicate.js\";\n/**\n * Defines the unique identifier used to identify objects that implement the `PrimaryKey` interface.\n *\n * **When to use**\n *\n * Use to implement the `PrimaryKey` protocol as a computed property key on\n * classes or object literals that expose a stable string identifier.\n *\n * @see {@link PrimaryKey} for the protocol interface that declares the method keyed by this symbol\n * @see {@link value} for reading the string key from a `PrimaryKey` value\n * @see {@link isPrimaryKey} for checking whether an unknown value carries this method\n *\n * @category symbols\n * @since 2.0.0\n */\nexport const symbol = \"~effect/interfaces/PrimaryKey\";\n/**\n * Checks whether a value implements the `PrimaryKey` protocol.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before treating it as a `PrimaryKey`.\n *\n * **Details**\n *\n * This is a structural guard for the `PrimaryKey.symbol` property.\n *\n * **Gotchas**\n *\n * This guard does not call the method or verify that it returns a string.\n *\n * @see {@link PrimaryKey} for the protocol being checked\n * @see {@link value} for extracting the string value after narrowing\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isPrimaryKey = u => hasProperty(u, symbol);\n/**\n * Extracts the string value from a `PrimaryKey`.\n *\n * **When to use**\n *\n * Use to read the stable string identifier from a value that implements\n * `PrimaryKey`.\n *\n * **Example** (Reading primary key values)\n *\n * ```ts import.meta.vitest\n * import { PrimaryKey } from \"effect\"\n *\n * class OrderId implements PrimaryKey.PrimaryKey {\n *   constructor(private timestamp: number, private sequence: number) {}\n *\n *   [PrimaryKey.symbol](): string {\n *     return `order_${this.timestamp}_${this.sequence}`\n *   }\n * }\n *\n * const orderId = new OrderId(1640995200000, 1)\n * PrimaryKey.value(orderId) // => \"order_1640995200000_1\"\n *\n * // Can also be used with simple string-based implementations\n * const simpleKey = {\n *   [PrimaryKey.symbol]: () => \"simple-key-123\"\n * }\n * PrimaryKey.value(simpleKey) // => \"simple-key-123\"\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const value = self => self[symbol]();\n//# sourceMappingURL=PrimaryKey.js.map","/**\n * Caches scoped services selected by key and built from layers.\n *\n * A `LayerMap<K, I, E>` turns a key into a cached service `Context<I>` and\n * exposes that context as either a `Layer` or a scoped effect. Entries can be\n * invalidated explicitly or released after they sit unused. This is useful for\n * keyed resource families such as tenant clients, regional connections, or\n * environment-specific services.\n *\n * @since 3.14.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Effect from \"./Effect.js\";\nimport { identity } from \"./Function.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"./internal/stackTraceLimit.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as RcMap from \"./RcMap.js\";\nimport * as Scope from \"./Scope.js\";\nconst TypeId = \"~effect/LayerMap\";\n/**\n * Creates a `LayerMap` that dynamically provides resources based on a key.\n *\n * **Example** (Creating a layer map)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, LayerMap } from \"effect\"\n *\n * // Define a service key\n * const DatabaseService = Context.Service<{\n *   readonly query: (sql: string) => Effect.Effect<string>\n * }>(\"Database\")\n *\n * // Create a LayerMap that provides different database configurations\n * const program = Effect.gen(function*() {\n *   const layerMap = yield* LayerMap.make(\n *     (env: string) =>\n *       Layer.succeed(DatabaseService)({\n *         query: Effect.fn(\"DatabaseService.query\")((sql) => Effect.succeed(`${env}: ${sql}`))\n *       }),\n *     { idleTimeToLive: \"5 seconds\" }\n *   )\n *\n *   // Get a layer for a specific environment\n *   const devLayer = layerMap.get(\"development\")\n *\n *   // Use the layer to provide the service\n *   return yield* Effect.provide(\n *     Effect.gen(function*() {\n *       const db = yield* DatabaseService\n *       return yield* db.query(\"SELECT * FROM users\")\n *     }),\n *     devLayer\n *   )\n * })\n *\n * await Effect.runPromise(Effect.scoped(program)) // => \"development: SELECT * FROM users\"\n * ```\n *\n * @category constructors\n * @since 3.14.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (lookup, options) {\n  const context = yield* Effect.context();\n  const memoMap = Layer.CurrentMemoMap.forkOrCreate(context);\n  const rcMap = yield* RcMap.make({\n    lookup: key => Effect.contextWith(_ => Layer.buildWithMemoMap(lookup(key), memoMap, Context.get(_, Scope.Scope))),\n    idleTimeToLive: options?.idleTimeToLive\n  });\n  if (options?.preloadKeys) {\n    for (const key of options.preloadKeys) {\n      yield* Effect.scoped(RcMap.get(rcMap, key));\n    }\n  }\n  return identity({\n    [TypeId]: TypeId,\n    rcMap,\n    get: key => Layer.effectContext(RcMap.get(rcMap, key)),\n    contextEffect: key => RcMap.get(rcMap, key),\n    invalidate: key => RcMap.invalidate(rcMap, key)\n  });\n});\n/**\n * Creates a `LayerMap` from a record of predefined layers.\n *\n * **Details**\n *\n * The record keys become the keys accepted by the returned `LayerMap`, and the\n * record values are the layers built for those keys.\n *\n * **Example** (Creating a layer map from a record)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, LayerMap } from \"effect\"\n *\n * // Define a service key\n * const Database = Context.Service<{\n *   readonly query: (sql: string) => Effect.Effect<string>\n * }>(\"Database\")\n *\n * // Create predefined layers\n * const layers = {\n *   development: Layer.succeed(Database)({\n *     query: Effect.fn(\"DevDatabase.query\")((sql) => Effect.succeed(`DEV: ${sql}`))\n *   }),\n *   production: Layer.succeed(Database)({\n *     query: Effect.fn(\"ProdDatabase.query\")((sql) => Effect.succeed(`PROD: ${sql}`))\n *   })\n * } as const\n *\n * // Create a LayerMap from the record\n * const program = Effect.gen(function*() {\n *   const layerMap = yield* LayerMap.fromRecord(layers, {\n *     idleTimeToLive: \"10 seconds\"\n *   })\n *\n *   const development = yield* Effect.provide(\n *     Database.use((database) => database.query(\"SELECT 1\")),\n *     layerMap.get(\"development\")\n *   )\n *   const production = yield* Effect.provide(\n *     Database.use((database) => database.query(\"SELECT 1\")),\n *     layerMap.get(\"production\")\n *   )\n *\n *   return { development, production }\n * })\n *\n * await Effect.runPromise(Effect.scoped(program)) // => { development: \"DEV: SELECT 1\", production: \"PROD: SELECT 1\" }\n * ```\n *\n * @category constructors\n * @since 3.14.0\n */\nexport const fromRecord = (layers, options) => make(key => layers[key], {\n  ...options,\n  preloadKeys: options?.preload ? Object.keys(layers) : undefined\n});\n/**\n * Create a `LayerMap` service that provides a dynamic set of resources based on\n * a key.\n *\n * **Example** (Defining a layer map service)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, LayerMap } from \"effect\"\n *\n * // Define a service key\n * const Greeter = Context.Service<{\n *   readonly greet: Effect.Effect<string>\n * }>(\"Greeter\")\n *\n * // Create a service that wraps a LayerMap\n * class GreeterMap extends LayerMap.Service<GreeterMap>()(\"GreeterMap\", {\n *   // Define the lookup function for the layer map\n *   lookup: (name: string) =>\n *     Layer.succeed(Greeter)({\n *       greet: Effect.succeed(`Hello, ${name}!`)\n *     }),\n *\n *   // If a layer is not used for a certain amount of time, it can be removed\n *   idleTimeToLive: \"5 seconds\"\n * }) {}\n *\n * // Usage\n * const program = Effect.gen(function*() {\n *   // Access and use the Greeter service\n *   const greeter = yield* Greeter\n *   return yield* greeter.greet\n * }).pipe(\n *   // Use the GreeterMap service to provide a variant of the Greeter service\n *   Effect.provide(GreeterMap.get(\"John\"))\n * ).pipe(\n *   // Provide the GreeterMap layer\n *   Effect.provide(GreeterMap.layer)\n * )\n *\n * await Effect.runPromise(program) // => \"Hello, John!\"\n * ```\n *\n * @category services\n * @since 3.14.0\n */\nexport const Service = () => (id, options) => {\n  const Err = globalThis.Error;\n  const limit = getStackTraceLimit();\n  setStackTraceLimit(2);\n  const creationError = new Err();\n  setStackTraceLimit(limit);\n  function TagClass() {}\n  const TagClass_ = TagClass;\n  Object.setPrototypeOf(TagClass, Object.getPrototypeOf(Context.Service(id)));\n  TagClass.key = id;\n  Object.defineProperty(TagClass, \"stack\", {\n    get() {\n      return creationError.stack;\n    }\n  });\n  TagClass_.layerNoDeps = Layer.effect(TagClass_)(\"lookup\" in options ? make(options.lookup, options) : fromRecord(options.layers, options));\n  TagClass_.layer = options.dependencies && options.dependencies.length > 0 ? Layer.provide(TagClass_.layerNoDeps, options.dependencies) : TagClass_.layerNoDeps;\n  TagClass_.get = key => Layer.unwrap(Effect.map(TagClass_, layerMap => layerMap.get(key)));\n  TagClass_.contextEffect = key => Effect.flatMap(TagClass_, layerMap => layerMap.contextEffect(key));\n  TagClass_.invalidate = key => Effect.flatMap(TagClass_, layerMap => layerMap.invalidate(key));\n  return TagClass;\n};\n//# sourceMappingURL=LayerMap.js.map","/**\n * Defines loggers and log-event data for Effect programs.\n *\n * A `Logger<Message, Output>` receives each log event as `Options` and turns it\n * into output such as a formatted string, structured object, console write,\n * file write, JSON line, or trace span event. This module also includes active\n * logger references, console routing helpers, built-in formatters, batching,\n * file logging, and layers for installing loggers.\n *\n * @since 2.0.0\n */\nimport * as Array from \"./Array.js\";\nimport * as FileSystem from \"./FileSystem.js\";\nimport * as Formatter from \"./Formatter.js\";\nimport { dual } from \"./Function.js\";\nimport { isEffect, withFiber } from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport { CurrentLogAnnotations, CurrentLogSpans } from \"./References.js\";\nconst TypeId = \"~effect/Logger\";\n/**\n * Returns `true` if the specified value is a `Logger`, otherwise returns `false`.\n *\n * **Example** (Checking logger values)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * const myLogger = Logger.make(() => undefined)\n *\n * Logger.isLogger(myLogger) // => true\n * Logger.isLogger(\"not a logger\") // => false\n * Logger.isLogger({ log: () => {} }) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isLogger = u => Predicate.hasProperty(u, TypeId);\n/**\n * Context reference containing the active loggers for the current fiber.\n *\n * **Details**\n *\n * By default this set includes the default logger and the tracer logger.\n * Providing `Logger.layer` replaces or merges with this set depending on its\n * options.\n *\n * **Example** (Accessing current loggers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const customLogger = Logger.make((options) => {\n *   messages.push(options.message)\n * })\n * const program = Effect.gen(function*() {\n *   const currentLoggers = yield* Effect.service(Logger.CurrentLoggers)\n *   yield* Effect.log(\"Hello from custom logger\").pipe(\n *     Effect.provide(Logger.layer([customLogger]))\n *   )\n *   return currentLoggers.has(Logger.defaultLogger)\n * })\n *\n * Effect.runSync(program) // => true\n * messages // => [[\"Hello from custom logger\"]]\n * ```\n *\n * @category services\n * @since 4.0.0\n */\nexport const CurrentLoggers = effect.CurrentLoggers;\n/**\n * Context reference that routes the built-in default logger and TTY pretty\n * console logger to stderr.\n *\n * **When to use**\n *\n * Use to route built-in logger output to stderr while keeping stdout reserved\n * for protocol messages or data output.\n *\n * **Details**\n *\n * The reference defaults to `false`. Providing `true` makes the affected\n * loggers call `console.error` instead of `console.log`.\n *\n * @see {@link defaultLogger} for the runtime logger affected by this reference\n * @see {@link consolePretty} for the TTY-mode pretty console logger affected by this reference\n * @see {@link withConsoleError} for routing a specific formatter logger to `console.error`\n *\n * @category services\n * @since 4.0.0\n */\nexport const LogToStderr = effect.LogToStderr;\n/**\n * Transforms the output of a `Logger` using the provided function.\n *\n * **When to use**\n *\n * Use when an existing logger's output should be transformed without recreating the\n * logging logic.\n *\n * **Example** (Transforming logger output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const outputs: Array<unknown> = []\n * const structuredLogger = Logger.make((options) => ({\n *   message: options.message\n * }))\n *\n * // Transform to uppercase messages\n * const uppercaseLogger = Logger.map(\n *   structuredLogger,\n *   (output) => ({ ...output, message: String(output.message).toUpperCase() })\n * )\n *\n * const collector = Logger.make((options) => outputs.push(uppercaseLogger.log(options)))\n * const program = Effect.log(\"hello\").pipe(Effect.provide(Logger.layer([collector])))\n * Effect.runSync(program)\n * outputs // => [{ message: \"HELLO\" }]\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => effect.loggerMake(options => f(self.log(options))));\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console using `console.log`.\n *\n * **When to use**\n *\n * Use when a logger's string or object output should be routed to `console.log` for\n * development or debugging.\n *\n * **Example** (Writing logger output with console.log)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Create a custom formatter\n * const customFormatter = Logger.make((options) =>\n *   `${options.logLevel}: ${options.message}`\n * )\n *\n * const consoleLogger = Logger.withConsoleLog(customFormatter)\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"Hello World\").pipe(Effect.provide(Logger.layer([consoleLogger])))\n *   return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"Info: Hello World\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const withConsoleLog = self => effect.loggerMake(options => {\n  const console = options.fiber.getRef(effect.ConsoleRef);\n  return console.log(self.log(options));\n});\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console using `console.error`.\n *\n * **When to use**\n *\n * Use when logger output should be routed to `console.error`, such as error logs that\n * should appear on stderr instead of stdout.\n *\n * **Example** (Writing logger output with console.error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Create an error-specific formatter\n * const errorFormatter = Logger.make((options) =>\n *   `ERROR: ${options.message}`\n * )\n *\n * const errorLogger = Logger.withConsoleError(errorFormatter)\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.logError(\"Database connection failed\").pipe(Effect.provide(Logger.layer([errorLogger])))\n *   return yield* TestConsole.errorLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"ERROR: Database connection failed\"]\n * ```\n *\n * @category logging\n * @since 2.0.0\n */\nexport const withConsoleError = self => effect.loggerMake(options => {\n  const console = options.fiber.getRef(effect.ConsoleRef);\n  return console.error(self.log(options));\n});\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console.\n *\n * **Details**\n *\n * Will use the appropriate console method (i.e. `console.log`, `console.error`,\n * etc.) based upon the current `LogLevel`.\n *\n * `Debug` uses `console.debug`, `Info` uses `console.info`, `Trace` uses\n * `console.trace`, `Warn` uses `console.warn`, `Error` and `Fatal` use\n * `console.error`, and all other levels use `console.log`.\n *\n * **Example** (Writing logs with level-based console methods)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Logger } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n *   info: (message: unknown) => messages.push([\"info\", message]),\n *   warn: (message: unknown) => messages.push([\"warn\", message]),\n *   error: (message: unknown) => messages.push([\"error\", message])\n * })\n * const formatter = Logger.make((options) =>\n *   `[${options.logLevel}] ${options.message}`\n * )\n *\n * const leveledLogger = Logger.withLeveledConsole(formatter)\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.logInfo(\"Info message\") // -> console.info\n *   yield* Effect.logWarning(\"Warning\") // -> console.warn\n *   yield* Effect.logError(\"Error occurred\") // -> console.error\n * }).pipe(Effect.provide(Logger.layer([leveledLogger])))\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n *   [\"info\", \"[Info] Info message\"],\n *   [\"warn\", \"[Warn] Warning\"],\n *   [\"error\", \"[Error] Error occurred\"]\n * ]\n * messages // => expected\n * ```\n *\n * @category logging\n * @since 3.8.0\n */\nexport const withLeveledConsole = self => effect.loggerMake(options => {\n  const console = options.fiber.getRef(effect.ConsoleRef);\n  const output = self.log(options);\n  switch (options.logLevel) {\n    case \"Debug\":\n      return console.debug(output);\n    case \"Info\":\n      return console.info(output);\n    case \"Trace\":\n      return console.trace(output);\n    case \"Warn\":\n      return console.warn(output);\n    case \"Error\":\n    case \"Fatal\":\n      return console.error(output);\n    default:\n      return console.log(output);\n  }\n});\n/**\n * Match strings that do not contain any whitespace characters, double quotes,\n * or equal signs.\n */\nconst textOnly = /^[^\\s\"=]*$/;\n/**\n * Escapes double quotes in a string.\n */\nconst escapeDoubleQuotes = s => `\"${s.replace(/\\\\([\\s\\S])|(\")/g, \"\\\\$1$2\")}\"`;\n/**\n * Formats the identifier of a `Fiber` by prefixing it with a hash tag.\n */\nconst formatFiberId = fiberId => `#${fiberId}`;\n/**\n * Used by both {@link formatSimple} and {@link formatLogFmt} to render a log\n * message.\n *\n * @internal\n */\nconst format = (quoteValue, space) => ({\n  cause,\n  date,\n  fiber,\n  logLevel,\n  message\n}) => {\n  const formatUnknown = value => typeof value === \"string\" ? value : Formatter.format(value, {\n    space\n  });\n  const formatValue = value => value.match(textOnly) ? value : quoteValue(value);\n  const format = (label, value) => `${effect.formatLabel(label)}=${formatValue(value)}`;\n  const append = (label, value) => \" \" + format(label, value);\n  let out = format(\"timestamp\", date.toISOString());\n  out += append(\"level\", logLevel);\n  out += append(\"fiber\", formatFiberId(fiber.id));\n  const messages = Array.ensure(message);\n  for (let i = 0; i < messages.length; i++) {\n    out += append(\"message\", formatUnknown(messages[i]));\n  }\n  if (cause.reasons.length > 0) {\n    out += append(\"cause\", effect.causePretty(cause));\n  }\n  const now = date.getTime();\n  const spans = fiber.getRef(CurrentLogSpans);\n  for (const span of spans) {\n    out += \" \" + effect.formatLogSpan(span, now);\n  }\n  const annotations = fiber.getRef(CurrentLogAnnotations);\n  for (const [label, value] of Object.entries(annotations)) {\n    out += append(label, formatUnknown(value));\n  }\n  return out;\n};\n/**\n * Creates a new `Logger` from a log function.\n *\n * **Details**\n *\n * The log function receives an options object containing the message, log level,\n * cause, fiber information, and timestamp, and should return the desired output.\n *\n * **Example** (Creating loggers from functions)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const outputs: Array<string> = []\n * const textLogger = Logger.make((options) =>\n *   `${options.logLevel}: ${options.message}`\n * )\n * const collector = Logger.make((options) => outputs.push(textLogger.log(options)))\n *\n * const program = Effect.log(\"Hello World\").pipe(\n *   Effect.provide(Logger.layer([collector]))\n * )\n * Effect.runSync(program)\n * outputs // => [\"Info: Hello World\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = effect.loggerMake;\n/**\n * The default logging implementation used by the Effect runtime.\n *\n * **Example** (Referencing the default logger)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.defaultLogger) // => true\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const defaultLogger = effect.defaultLogger;\n/**\n * A `Logger` which outputs logs as a string.\n *\n * **Details**\n *\n * For example, a simple log entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`.\n *\n * **Example** (Formatting logs as simple strings)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Use the simple format logger\n * const stableSimple = Logger.map(Logger.formatSimple, (output) =>\n *   output\n *     .replace(/timestamp=\\S+ /, \"\")\n *     .replace(/fiber=#\\d+ /, \"\")\n * )\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"Application started\").pipe(\n *     Effect.provide(Logger.layer([Logger.withConsoleLog(stableSimple)]))\n *   )\n *   return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"level=Info message=\\\"Application started\\\"\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formatSimple = /*#__PURE__*/effect.loggerMake(/*#__PURE__*/format(escapeDoubleQuotes));\n/**\n * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt)\n * style.\n *\n * **Details**\n *\n * For example, a logfmt entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`.\n *\n * **Example** (Formatting logs as logfmt)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableLogFmt = Logger.map(Logger.formatLogFmt, (output) =>\n *   output\n *     .replace(/timestamp=\\S+ /, \"\")\n *     .replace(/fiber=#\\d+ /, \"\")\n * )\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"User login\").pipe(\n *     Effect.provide(Logger.layer([Logger.withConsoleLog(stableLogFmt)]))\n *   )\n *   return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"level=Info message=\\\"User login\\\"\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formatLogFmt = /*#__PURE__*/effect.loggerMake(/*#__PURE__*/format(JSON.stringify, 0));\n/**\n * A `Logger` which outputs logs using a structured format.\n *\n * **Details**\n *\n * For example, a structured entry can contain `message: [ \"hello\" ]`,\n * `level: \"INFO\"`, `timestamp: \"2025-01-03T14:25:39.666Z\"`,\n * `annotations: { key: \"value\" }`, `spans: { label: 0 }`, and\n * `fiberId: \"#1\"`.\n *\n * **Example** (Formatting logs as structured objects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableStructured = Logger.map(Logger.formatStructured, (output) => ({\n *   message: output.message,\n *   level: output.level\n * }))\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"User action\").pipe(\n *     Effect.provide(Logger.layer([Logger.withConsoleLog(stableStructured)]))\n *   )\n *   return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [{ message: \"User action\", level: \"INFO\" }]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formatStructured = /*#__PURE__*/effect.loggerMake(({\n  cause,\n  date,\n  fiber,\n  logLevel,\n  message\n}) => {\n  const annotationsObj = {};\n  const spansObj = {};\n  const annotations = fiber.getRef(CurrentLogAnnotations);\n  for (const [key, value] of Object.entries(annotations)) {\n    InternalRecord.assignProperty(annotationsObj, key, effect.structuredMessage(value));\n  }\n  const now = date.getTime();\n  const spans = fiber.getRef(CurrentLogSpans);\n  for (const [label, timestamp] of spans) {\n    InternalRecord.assignProperty(spansObj, label, now - timestamp);\n  }\n  const messageArr = Array.ensure(message);\n  return {\n    message: messageArr.length === 1 ? effect.structuredMessage(messageArr[0]) : messageArr.map(effect.structuredMessage),\n    level: logLevel.toUpperCase(),\n    timestamp: date.toISOString(),\n    cause: cause.reasons.length > 0 ? effect.causePretty(cause) : undefined,\n    annotations: annotationsObj,\n    spans: spansObj,\n    fiberId: formatFiberId(fiber.id)\n  };\n});\n/**\n * A `Logger` which outputs logs using a structured format serialized as JSON\n * on a single line.\n *\n * **Details**\n *\n * For example, a JSON entry can render as `{\"message\":[\"hello\"],\"level\":\"INFO\",\n * \"timestamp\":\"2025-01-03T14:28:57.508Z\",\"annotations\":{\"key\":\"value\"},\n * \"spans\":{\"label\":0},\"fiberId\":\"#1\"}`.\n *\n * **Example** (Formatting logs as JSON)\n *\n * ```ts import.meta.vitest\n * import { Effect, Formatter, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableJson = Logger.map(Logger.formatJson, (json) => {\n *   const output = JSON.parse(json)\n *   return Formatter.formatJson({ message: output.message, level: output.level })\n * })\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"Server started\").pipe(\n *     Effect.provide(Logger.layer([Logger.withConsoleLog(stableJson)]))\n *   )\n *   return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"{\\\"message\\\":\\\"Server started\\\",\\\"level\\\":\\\"INFO\\\"}\"]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const formatJson = /*#__PURE__*/map(formatStructured, Formatter.formatJson);\n/**\n * Creates a scoped logger that batches the output of another logger.\n *\n * **Details**\n *\n * The returned effect starts a scoped background process that periodically\n * passes buffered outputs to `flush`. When the scope closes, the background\n * process is interrupted and any remaining buffered entries are flushed.\n *\n * **Example** (Batching logger output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const flushed: Array<ReadonlyArray<string>> = []\n * const messageLogger = Logger.make((options) => String(options.message))\n * const batchedLogger = Logger.batched(messageLogger, {\n *   window: \"1 hour\",\n *   flush: (messages) =>\n *     Effect.sync(() => {\n *       flushed.push(messages)\n *     })\n * })\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n *   const logger = yield* batchedLogger\n *   yield* Effect.log(\"Event 1\").pipe(Effect.provide(Logger.layer([logger])))\n *   yield* Effect.log(\"Event 2\").pipe(Effect.provide(Logger.layer([logger])))\n * }))\n * await Effect.runPromise(program)\n * flushed // => [[\"Event 1\", \"Event 2\"]]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const batched = /*#__PURE__*/dual(2, (self, options) => effect.flatMap(effect.scope, scope => {\n  let buffer = [];\n  const flush = effect.suspend(() => {\n    if (buffer.length === 0) {\n      return effect.void;\n    }\n    const arr = buffer;\n    buffer = [];\n    return options.flush(arr);\n  });\n  return effect.uninterruptibleMask(restore => restore(effect.sleep(options.window).pipe(effect.andThen(flush), effect.forever)).pipe(effect.forkDetach, effect.flatMap(fiber => effect.scopeAddFinalizerExit(scope, () => effect.fiberInterrupt(fiber))), effect.andThen(effect.addFinalizer(() => flush)), effect.as(effect.loggerMake(options => {\n    buffer.push(self.log(options));\n  }))));\n}));\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * const prettyLogger = Logger.consolePretty({ colors: false })\n * Logger.isLogger(prettyLogger) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePretty = effect.consolePretty;\n/**\n * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt)\n * style and writes them to the console.\n *\n * **Details**\n *\n * For example, a console logfmt entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=info`.\n *\n * **Example** (Logging logfmt output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleLogFmt) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleLogFmt = /*#__PURE__*/withConsoleLog(formatLogFmt);\n/**\n * A `Logger` which outputs logs using a structured format and writes them to\n * the console.\n *\n * **Details**\n *\n * For example, console structured output can contain\n * `message: [ \"info\", \"message\" ]`, `level: \"INFO\"`,\n * `timestamp: \"2025-01-03T14:25:39.666Z\"`,\n * `annotations: { key: \"value\" }`, `spans: { label: 0 }`, and\n * `fiberId: \"#1\"`.\n *\n * **Example** (Logging structured output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleStructured) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleStructured = /*#__PURE__*/withConsoleLog(formatStructured);\n/**\n * A `Logger` which outputs logs using a structured format serialized as JSON\n * on a single line and writes them to the console.\n *\n * **Details**\n *\n * For example, console JSON output can render as\n * `{\"message\":[\"hello\"],\"level\":\"INFO\",\"timestamp\":\"2025-01-03T14:28:57.508Z\",\n * \"annotations\":{\"key\":\"value\"},\"spans\":{\"label\":0},\"fiberId\":\"#1\"}`.\n *\n * **Example** (Logging JSON output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleJson) // => true\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleJson = /*#__PURE__*/withConsoleLog(formatJson);\n/**\n * A `Logger` which includes log messages as tracer span events.\n *\n * **Details**\n *\n * This logger integrates logging with distributed tracing by recording\n * all log messages as events on the current trace span, making them visible\n * in tracing tools like OpenTelemetry, Jaeger, or Zipkin.\n *\n * This logger is included in the default set of loggers for all Effect programs,\n * so log messages automatically appear as span events unless you override the\n * default loggers.\n *\n * **Example** (Recording logs as trace span events)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"span event\").pipe(\n *   Effect.withSpan(\"operation\"),\n *   Effect.provide(Logger.layer([Logger.tracerLogger]))\n * )\n * Effect.runSync(program)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const tracerLogger = effect.tracerLogger;\n/**\n * Creates a `Layer` which will overwrite the current set of loggers with the\n * specified array of `loggers`.\n *\n * **Details**\n *\n * If the specified array of `loggers` should be _merged_ with the current set\n * of loggers (instead of overwriting them), set `mergeWithExisting` to `true`.\n *\n * **Example** (Providing logger layers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const customLogger = Logger.make((options) => {\n *   messages.push(options.message)\n * })\n * const CustomLoggerLive = Logger.layer([customLogger])\n *\n * const program = Effect.log(\"Application started\").pipe(\n *   Effect.provide(CustomLoggerLive)\n * )\n * Effect.runSync(program)\n * messages // => [[\"Application started\"]]\n * ```\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (loggers, options) => Layer.effect(CurrentLoggers, withFiber(effect.fnUntraced(function* (fiber) {\n  const currentLoggers = new Set(options?.mergeWithExisting === true ? fiber.getRef(effect.CurrentLoggers) : []);\n  for (const logger of loggers) {\n    currentLoggers.add(isEffect(logger) ? yield* logger : logger);\n  }\n  return currentLoggers;\n})));\n/**\n * Creates a scoped logger that writes string logger output to a file.\n *\n * **Details**\n *\n * The returned effect requires `FileSystem` and `Scope`. The file logger batches\n * string output, writes each batch to the specified path, and flushes remaining\n * entries when the scope closes.\n *\n * **Example** (Writing JSON logs to a file)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Logger } from \"effect\"\n *\n * const writes: Array<string> = []\n * const file = {\n *   write: (buffer: Uint8Array) => Effect.sync(() => {\n *     writes.push(new TextDecoder().decode(buffer).trim())\n *     return FileSystem.Size(buffer.length)\n *   })\n * } as unknown as FileSystem.File\n * const fileSystem = FileSystem.makeNoop({ open: () => Effect.succeed(file) })\n * const messageLogger = Logger.make((options) => String(options.message))\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n *   const fileLogger = yield* Logger.toFile(messageLogger, \"/tmp/log.txt\")\n *   yield* Effect.log(\"a\").pipe(Effect.provide(Logger.layer([fileLogger])))\n *   yield* Effect.log(\"b\").pipe(Effect.provide(Logger.layer([fileLogger])))\n *   yield* Effect.log(\"c\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * })).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem))\n *\n * await Effect.runPromise(program)\n * writes // => [\"a\\nb\\nc\"]\n * ```\n *\n * **Example** (Writing logs to files)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Logger } from \"effect\"\n *\n * const writes: Array<string> = []\n * const file = {\n *   write: (buffer: Uint8Array) => Effect.sync(() => {\n *     writes.push(new TextDecoder().decode(buffer).trim())\n *     return FileSystem.Size(buffer.length)\n *   })\n * } as unknown as FileSystem.File\n * const fileSystem = FileSystem.makeNoop({ open: () => Effect.succeed(file) })\n * const messageLogger = Logger.make((options) => String(options.message))\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n *   const fileLogger = yield* Logger.toFile(messageLogger, \"/tmp/app.log\", {\n *     batchWindow: \"1 hour\"\n *   })\n *   yield* Effect.log(\"Application started\").pipe(\n *     Effect.provide(Logger.layer([fileLogger]))\n *   )\n * })).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem))\n *\n * await Effect.runPromise(program)\n * writes // => [\"Application started\"]\n * ```\n *\n * @category logging\n * @since 4.0.0\n */\nexport const toFile = /*#__PURE__*/dual(args => isLogger(args[0]), (self, path, options) => effect.gen(function* () {\n  const fs = yield* FileSystem.FileSystem;\n  const logFile = yield* fs.open(path, {\n    flag: \"a+\",\n    ...options\n  });\n  const encoder = new TextEncoder();\n  return yield* batched(self, {\n    window: options?.batchWindow ?? 1000,\n    flush: output => effect.ignore(logFile.write(encoder.encode(output.join(\"\\n\") + \"\\n\")))\n  });\n}));\n//# sourceMappingURL=Logger.js.map","/**\n * Stores mutable state whose updates run one at a time.\n *\n * A `SynchronizedRef<A>` behaves like a `Ref<A>` for reading and simple state\n * storage, but update and modify operations are serialized so each change sees\n * a consistent current value. This is especially useful when the next value is\n * computed by an effect, because the effectful transition is still protected\n * from concurrent updates. This module includes constructors, reads, writes,\n * updates, partial updates, and effectful update helpers.\n *\n * @since 2.0.0\n */\nimport * as Effect from \"./Effect.js\";\nimport { dual } from \"./Function.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as Option from \"./Option.js\";\nimport * as Ref from \"./Ref.js\";\nimport * as Semaphore from \"./Semaphore.js\";\nconst TypeId = \"~effect/SynchronizedRef\";\nconst Proto = {\n  ...PipeInspectableProto,\n  [TypeId]: TypeId,\n  toJSON() {\n    return {\n      _id: \"SynchronizedRef\",\n      value: this.backing.ref.current\n    };\n  }\n};\n/**\n * Creates a `SynchronizedRef` synchronously from an initial value.\n *\n * **When to use**\n *\n * Use when you need synchronous `SynchronizedRef` construction outside an\n * Effect workflow.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = value => {\n  const self = Object.create(Proto);\n  self.semaphore = Semaphore.makeUnsafe(1);\n  self.backing = Ref.makeUnsafe(value);\n  return self;\n};\n/**\n * Creates a `SynchronizedRef` from an initial value, wrapped in an `Effect`.\n *\n * **When to use**\n *\n * Use to create a `SynchronizedRef` inside an Effect program when later updates\n * may run effects and must be serialized.\n *\n * **Details**\n *\n * The returned effect constructs a fresh `SynchronizedRef` by delegating to\n * `makeUnsafe` when the effect is evaluated.\n *\n * @see {@link makeUnsafe} for synchronous construction when the caller controls safe initialization\n * @see {@link Ref.make} for a plain `Ref` when updates do not need effectful synchronization\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = value => Effect.sync(() => makeUnsafe(value));\n/**\n * Reads the current value synchronously, bypassing the `Effect` API and the\n * ref's semaphore.\n *\n * **When to use**\n *\n * Use when you need immediate synchronous access to a `SynchronizedRef` value\n * in low-level code that can safely read outside an `Effect`.\n *\n * @see {@link get} for the Effect-wrapped read when composing inside Effect programs\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getUnsafe = self => self.backing.ref.current;\n/**\n * Returns an `Effect` that reads the current value of the `SynchronizedRef`.\n *\n * **When to use**\n *\n * Use to read the current value of a `SynchronizedRef` inside an `Effect`\n * program without changing it.\n *\n * @see {@link getUnsafe} for synchronous reads when the caller controls safe access outside `Effect`\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get = self => Effect.sync(() => getUnsafe(self));\n/**\n * Sets a new value atomically and returns the previous value, serialized by the\n * ref's semaphore.\n *\n * **When to use**\n *\n * Use to replace a `SynchronizedRef` with a known value when the previous value\n * is also needed.\n *\n * @see {@link set} for setting a value without returning the previous value\n * @see {@link setAndGet} for setting a value and returning the new value\n * @see {@link getAndUpdate} for deriving the new value from the current value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndSet = /*#__PURE__*/dual(2, (self, value) => self.semaphore.withPermit(Ref.getAndSet(self.backing, value)));\n/**\n * Updates the current value atomically with a function and returns the previous\n * value, serialized by the ref's semaphore.\n *\n * **When to use**\n *\n * Use to run a pure `SynchronizedRef` state update when the previous stored\n * value is also needed.\n *\n * @see {@link update} for updating without returning a value\n * @see {@link updateAndGet} for updating and returning the new value\n * @see {@link getAndUpdateEffect} for effectful updates that return the previous value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdate = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Ref.getAndUpdate(self.backing, f)));\n/**\n * Runs an effectful update atomically while holding the ref's semaphore, sets\n * the new value if the effect succeeds, and returns the previous value.\n *\n * **When to use**\n *\n * Use when you need an effectful `SynchronizedRef` state transition to return\n * the previous stored value.\n *\n * @see {@link getAndUpdate} for pure updates that return the previous value\n * @see {@link updateEffect} for effectful updates without returning a value\n * @see {@link updateAndGetEffect} for effectful updates that return the new value\n * @see {@link modifyEffect} for effectful updates with a custom return value\n * @see {@link getAndUpdateSomeEffect} for conditional effectful updates that return the previous value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdateEffect = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.map(f(value), newValue => {\n    self.backing.ref.current = newValue;\n    return value;\n  });\n})));\n/**\n * Applies a partial update atomically and returns the previous value. If the\n * function returns `Option.some`, the ref is updated; if it returns\n * `Option.none`, the ref is left unchanged.\n *\n * **When to use**\n *\n * Use to return the previous `SynchronizedRef` value while applying a pure\n * conditional update.\n *\n * @see {@link getAndUpdate} for always applying a pure update\n * @see {@link updateSome} for applying a pure conditional update without returning the previous value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdateSome = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Ref.getAndUpdateSome(self, pf)));\n/**\n * Runs an effectful partial update atomically while holding the ref's semaphore\n * and returns the previous value. `Option.some` updates the ref; `Option.none`\n * leaves it unchanged.\n *\n * **When to use**\n *\n * Use to return the previous `SynchronizedRef` value while running an effectful\n * conditional update.\n *\n * @see {@link getAndUpdateSome} for the pure conditional variant\n * @see {@link updateSomeEffect} for effectful conditional updates without returning the previous value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdateSomeEffect = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.flatMap(pf(value), option => {\n    if (Option.isNone(option)) {\n      return Effect.succeed(value);\n    }\n    self.backing.ref.current = option.value;\n    return Effect.succeed(value);\n  });\n})));\n/**\n * Computes a return value and a new ref value atomically, stores the new value,\n * and returns the computed result.\n *\n * **When to use**\n *\n * Use to derive a separate result and the next stored `SynchronizedRef` value\n * from the same current value in one serialized pure update.\n *\n * @see {@link modifyEffect} for effectfully deriving both the result and next stored value\n * @see {@link modifySome} for deriving a result and optionally updating the stored value\n * @see {@link updateAndGet} for returning the new stored value instead of a separate result\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Ref.modify(self.backing, f)));\n/**\n * Runs an effectful modification atomically while holding the ref's semaphore,\n * stores the new value if the effect succeeds, and returns the computed result.\n *\n * **When to use**\n *\n * Use to effectfully compute both a separate return value and the next stored\n * `SynchronizedRef` value in one serialized update.\n *\n * @see {@link modify} for the pure variant\n * @see {@link updateEffect} for effectfully storing a new value without a separate result\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const modifyEffect = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.map(f(value), ([b, a]) => {\n    self.backing.ref.current = a;\n    return b;\n  });\n})));\n/**\n * Computes a return value and an optional new ref value atomically.\n * `Option.some` updates the ref; `Option.none` leaves it unchanged.\n *\n * **When to use**\n *\n * Use to compute a return value while optionally updating a `SynchronizedRef`\n * under its semaphore.\n *\n * @see {@link modify} for always storing a new value\n * @see {@link updateSome} for optional updates without a separate return value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const modifySome = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Ref.modifySome(self.backing, pf)));\n/**\n * Runs an effectful modification atomically while holding the ref's semaphore.\n * The effect computes a return value and an optional new ref value;\n * `Option.some` updates the ref and `Option.none` leaves it unchanged.\n *\n * **When to use**\n *\n * Use to effectfully compute a return value while optionally updating the\n * stored `SynchronizedRef` value.\n *\n * @see {@link modifySome} for the pure variant\n * @see {@link updateSomeEffect} for effectful optional updates without a separate return value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const modifySomeEffect = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.flatMap(pf(value), ([b, maybeA]) => {\n    if (Option.isNone(maybeA)) {\n      return Effect.succeed(b);\n    }\n    self.backing.ref.current = maybeA.value;\n    return Effect.succeed(b);\n  });\n})));\n/**\n * Sets the value of the `SynchronizedRef`, serialized by the ref's semaphore.\n *\n * **When to use**\n *\n * Use to replace the current value of a `SynchronizedRef` with a known value\n * while keeping the write serialized with other synchronized updates.\n *\n * @see {@link getAndSet} for replacing the value when the previous value is needed\n * @see {@link setAndGet} for replacing the value when the new value should be returned\n * @see {@link update} for deriving the next value from the current value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(2, (self, value) => self.semaphore.withPermit(Ref.set(self.backing, value)));\n/**\n * Sets the value of the `SynchronizedRef` and returns the new value.\n *\n * **When to use**\n *\n * Use to replace the current `SynchronizedRef` value with a known value and\n * return that new value.\n *\n * @see {@link set} for setting without returning a value\n * @see {@link getAndSet} for setting while returning the previous value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const setAndGet = /*#__PURE__*/dual(2, (self, value) => self.semaphore.withPermit(Ref.setAndGet(self.backing, value)));\n/**\n * Updates the value of the `SynchronizedRef` with a function, serialized by the\n * ref's semaphore.\n *\n * **When to use**\n *\n * Use to apply a pure state transition to a `SynchronizedRef` as a serialized\n * `Effect`.\n *\n * @see {@link updateEffect} for effectfully deriving the next value\n * @see {@link updateAndGet} for returning the new stored value\n * @see {@link getAndUpdate} for returning the previous stored value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Ref.update(self.backing, f)));\n/**\n * Runs an effectful update while holding the ref's semaphore and stores the new\n * value if the effect succeeds.\n *\n * **When to use**\n *\n * Use to run an effectful state transition on a `SynchronizedRef` when storing\n * the new value is the only result you need.\n *\n * @see {@link update} for a pure state transition\n * @see {@link getAndUpdateEffect} for returning the previous stored value\n * @see {@link updateAndGetEffect} for returning the new stored value\n * @see {@link modifyEffect} for returning a separate result while storing a new value\n * @see {@link updateSomeEffect} for effectfully applying only some state transitions\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateEffect = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.map(f(value), newValue => {\n    self.backing.ref.current = newValue;\n  });\n})));\n/**\n * Updates the value of the `SynchronizedRef` with a function and returns the\n * new value.\n *\n * **When to use**\n *\n * Use to apply a pure `SynchronizedRef` state transition and return the new\n * stored value.\n *\n * @see {@link update} for updating without returning the new value\n * @see {@link getAndUpdate} for updating while returning the previous value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateAndGet = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Ref.updateAndGet(self.backing, f)));\n/**\n * Runs an effectful update while holding the ref's semaphore, stores the new\n * value if the effect succeeds, and returns that new value.\n *\n * **When to use**\n *\n * Use to run an effectful `SynchronizedRef` state transition and return the new\n * stored value.\n *\n * @see {@link updateEffect} for effectful updates without returning the new value\n * @see {@link updateAndGet} for the pure variant\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateAndGetEffect = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.map(f(value), newValue => {\n    self.backing.ref.current = newValue;\n    return newValue;\n  });\n})));\n/**\n * Applies a partial update to the current value. `Option.some` stores the new\n * value; `Option.none` leaves the ref unchanged.\n *\n * **When to use**\n *\n * Use to apply a pure conditional `SynchronizedRef` update without returning a\n * value.\n *\n * @see {@link update} for always applying a pure update\n * @see {@link updateSomeAndGet} for returning the resulting current value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSome = /*#__PURE__*/dual(2, (self, f) => self.semaphore.withPermit(Ref.updateSome(self.backing, f)));\n/**\n * Runs an effectful partial update while holding the ref's semaphore.\n * `Option.some` stores the new value; `Option.none` leaves the ref unchanged.\n *\n * **When to use**\n *\n * Use to run an effectful conditional `SynchronizedRef` update without\n * returning a value.\n *\n * @see {@link updateSome} for the pure conditional variant\n * @see {@link updateEffect} for effectful updates that always store a new value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSomeEffect = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.map(pf(value), option => {\n    if (Option.isNone(option)) {\n      return;\n    }\n    self.backing.ref.current = option.value;\n  });\n})));\n/**\n * Applies a partial update and returns the resulting current value.\n * `Option.some` stores and returns the new value; `Option.none` returns the\n * unchanged value.\n *\n * **When to use**\n *\n * Use to apply a pure conditional `SynchronizedRef` update and return the\n * resulting current value.\n *\n * @see {@link updateSome} for conditional updates without returning a value\n * @see {@link updateAndGet} for always applying a pure update and returning the new value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSomeAndGet = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Ref.updateSomeAndGet(self.backing, pf)));\n/**\n * Runs an effectful partial update while holding the ref's semaphore and\n * returns the resulting current value. `Option.some` stores and returns the new\n * value; `Option.none` returns the unchanged value.\n *\n * **When to use**\n *\n * Use to run an effectful conditional `SynchronizedRef` update and return the\n * resulting current value.\n *\n * @see {@link updateSomeEffect} for effectful conditional updates without returning a value\n * @see {@link updateAndGetEffect} for effectful updates that always store and return a new value\n *\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSomeAndGetEffect = /*#__PURE__*/dual(2, (self, pf) => self.semaphore.withPermit(Effect.suspend(() => {\n  const value = getUnsafe(self);\n  return Effect.flatMap(pf(value), option => {\n    if (Option.isNone(option)) {\n      return Effect.succeed(value);\n    }\n    self.backing.ref.current = option.value;\n    return Effect.succeed(option.value);\n  });\n})));\n//# sourceMappingURL=SynchronizedRef.js.map","/**\n * Transactional references for coordinating mutable state with Effect\n * transactions. A `TxRef` stores a current value, but reads and writes inside\n * `Effect.tx` are recorded in a transaction journal and committed together only\n * when the outermost transaction succeeds.\n *\n * This is the basic building block behind the other transactional collections\n * in Effect. The module provides effectful and unsafe constructors plus the\n * core operations for reading, setting, updating, and modifying a transactional\n * value while returning a separate result.\n *\n * @since 4.0.0\n */\nimport * as Effect from \"./Effect.js\";\nimport { dual } from \"./Function.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nconst TypeId = \"~effect/transactions/TxRef\";\n/**\n * Creates a new `TxRef` with the specified initial value.\n *\n * **When to use**\n *\n * Use to create a `TxRef` inside an `Effect` workflow.\n *\n * **Example** (Creating transactional references)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxRef } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a transactional reference with initial value\n *   const counter = yield* TxRef.make(0)\n *   const name = yield* TxRef.make(\"Alice\")\n *\n *   // Use in transactions\n *   yield* Effect.tx(Effect.gen(function*() {\n *     yield* TxRef.set(counter, 42)\n *     yield* TxRef.set(name, \"Bob\")\n *   }))\n *\n *   return [yield* TxRef.get(counter), yield* TxRef.get(name)]\n * })\n *\n * await Effect.runPromise(program) // => [42, \"Bob\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = initial => Effect.sync(() => makeUnsafe(initial));\n/**\n * Creates a new `TxRef` synchronously with the specified initial value.\n *\n * **When to use**\n *\n * Use to construct a `TxRef` synchronously when it must be created outside an\n * `Effect` workflow.\n *\n * **Example** (Creating transactional references unsafely)\n *\n * ```ts import.meta.vitest\n * import { TxRef } from \"effect\"\n *\n * // Create a TxRef synchronously (unsafe - use make instead in Effect contexts)\n * const counter = TxRef.makeUnsafe(0)\n * const config = TxRef.makeUnsafe({ timeout: 5000, retries: 3 })\n *\n * // These are now ready to use in transactions\n * counter.value // => 0\n * config.value // => { timeout: 5000, retries: 3 }\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = initial => ({\n  [TypeId]: TypeId,\n  pending: new Map(),\n  pipe() {\n    return pipeArguments(this, arguments);\n  },\n  version: 0,\n  value: initial\n});\n/**\n * Modifies the value of the `TxRef` using the provided function.\n *\n * **When to use**\n *\n * Use to update a `TxRef` and return a computed result from the same\n * transaction step.\n *\n * **Example** (Modifying transactional references)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxRef } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const counter = yield* TxRef.make(0)\n *\n *   // Modify and return both old and new value\n *   const result = yield* TxRef.modify(counter, (current) => [current * 2, current + 1])\n *\n *   return [result, yield* TxRef.get(counter)]\n * })\n *\n * await Effect.runPromise(program) // => [0, 1]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, f) => Effect.Transaction.pipe(Effect.flatMap(state => Effect.sync(() => {\n  if (!state.journal.has(self)) {\n    state.journal.set(self, {\n      version: self.version,\n      value: self.value\n    });\n  }\n  const current = state.journal.get(self);\n  const [returnValue, next] = f(current.value);\n  current.value = next;\n  return returnValue;\n})), Effect.tx));\n/**\n * Updates the value of the `TxRef` using the provided function.\n *\n * **When to use**\n *\n * Use to transform a `TxRef` when no result value is needed.\n *\n * **Example** (Updating transactional references)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxRef } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const counter = yield* TxRef.make(10)\n *\n *   // Update the value using a function\n *   yield* Effect.tx(\n *     TxRef.update(counter, (current) => current * 2)\n *   )\n *\n *   return yield* TxRef.get(counter)\n * })\n *\n * await Effect.runPromise(program) // => 20\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, f) => modify(self, current => [void 0, f(current)]));\n/**\n * Reads the current value of the `TxRef`.\n *\n * **When to use**\n *\n * Use to read the current value of a `TxRef`.\n *\n * **Example** (Reading transactional references)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxRef } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const counter = yield* TxRef.make(42)\n *\n *   // Read the value within a transaction\n *   const value = yield* Effect.tx(\n *     TxRef.get(counter)\n *   )\n *\n *   return value\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const get = self => modify(self, current => [current, current]);\n/**\n * Sets the value of the `TxRef`.\n *\n * **When to use**\n *\n * Use to replace the value of a `TxRef`.\n *\n * **Example** (Setting transactional references)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxRef } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const counter = yield* TxRef.make(0)\n *\n *   // Set a new value within a transaction\n *   yield* Effect.tx(\n *     TxRef.set(counter, 100)\n *   )\n *\n *   return yield* TxRef.get(counter)\n * })\n *\n * await Effect.runPromise(program) // => 100\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(2, (self, value) => update(self, () => value));\n//# sourceMappingURL=TxRef.js.map","/**\n * Stores a `Chunk` inside transactional state.\n *\n * A `TxChunk<A>` keeps its current `Chunk<A>` in a `TxRef`, so reads and\n * updates can be committed atomically with other transactional operations. This\n * module offers a transactional version of common chunk workflows, including\n * creating collections, reading or replacing the current chunk, adding or\n * removing values, checking size, slicing, mapping, filtering, and combining\n * chunks.\n *\n * @since 4.0.0\n */\nimport * as Chunk from \"./Chunk.js\";\nimport * as Effect from \"./Effect.js\";\nimport { format } from \"./Formatter.js\";\nimport { dual } from \"./Function.js\";\nimport { NodeInspectSymbol, toJson } from \"./Inspectable.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport * as TxRef from \"./TxRef.js\";\nconst TypeId = \"~effect/transactions/TxChunk\";\nconst TxChunkProto = {\n  [NodeInspectSymbol]() {\n    return this.toJSON();\n  },\n  toString() {\n    return `TxChunk(${format(toJson(this.ref))})`;\n  },\n  toJSON() {\n    return {\n      _id: \"TxChunk\",\n      ref: toJson(this.ref)\n    };\n  },\n  pipe() {\n    return pipeArguments(this, arguments);\n  }\n};\n/**\n * Creates a new `TxChunk` with the specified initial chunk.\n *\n * **Details**\n *\n * This function returns a new TxChunk reference containing the provided initial chunk. No existing\n * TxChunk instances are modified.\n *\n * **Example** (Creating a TxChunk from a chunk)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a TxChunk with initial values\n *   const initialChunk = Chunk.fromIterable([1, 2, 3])\n *   const txChunk = yield* TxChunk.make(initialChunk)\n *\n *   // Read the value - automatically transactional\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = initial => Effect.map(TxRef.make(initial), ref => makeUnsafe(ref));\n/**\n * Creates a new empty `TxChunk`.\n *\n * **Details**\n *\n * This function returns a new TxChunk reference that is initially empty. No existing TxChunk\n * instances are modified.\n *\n * **Example** (Creating an empty TxChunk)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create an empty TxChunk\n *   const txChunk = yield* TxChunk.empty<number>()\n *\n *   // Check if it's empty - automatically transactional\n *   const isEmpty = yield* TxChunk.isEmpty(txChunk)\n *\n *   // Add elements - automatically transactional\n *   yield* TxChunk.append(txChunk, 42)\n *\n *   const isStillEmpty = yield* TxChunk.isEmpty(txChunk)\n *   return [isEmpty, isStillEmpty]\n * })\n *\n * await Effect.runPromise(program) // => [true, false]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = () => Effect.map(TxRef.make(Chunk.empty()), ref => makeUnsafe(ref));\n/**\n * Creates a new `TxChunk` from an iterable.\n *\n * **Details**\n *\n * This function returns a new TxChunk reference containing elements from the provided iterable. No\n * existing TxChunk instances are modified.\n *\n * **Example** (Creating from an iterable)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create TxChunk from array\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5])\n *\n *   // Read the contents - automatically transactional\n *   const chunk = yield* TxChunk.get(txChunk)\n *\n *   // Multi-step atomic modification - use explicit transaction\n *   yield* Effect.tx(\n *     Effect.gen(function*() {\n *       yield* TxChunk.append(txChunk, 6)\n *       yield* TxChunk.prepend(txChunk, 0)\n *     })\n *   )\n *\n *   const updated = yield* TxChunk.get(txChunk)\n *   return [Chunk.toArray(chunk), Chunk.toArray(updated)]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6]]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromIterable = iterable => Effect.map(TxRef.make(Chunk.fromIterable(iterable)), ref => makeUnsafe(ref));\n/**\n * Creates a new `TxChunk` with the specified TxRef.\n *\n * **Details**\n *\n * This function returns a new TxChunk reference wrapping the provided TxRef. No existing TxChunk\n * instances are modified.\n *\n * **Example** (Wrapping an existing TxRef)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk, TxRef } from \"effect\"\n *\n * // Create a TxChunk from an existing TxRef (advanced usage)\n * const ref = TxRef.makeUnsafe(Chunk.fromIterable([1, 2, 3]))\n * const txChunk = TxChunk.makeUnsafe(ref)\n * Chunk.toArray(await Effect.runPromise(TxChunk.get(txChunk))) // => [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = ref => {\n  const txChunk = Object.create(TxChunkProto);\n  txChunk[TypeId] = TypeId;\n  txChunk.ref = ref;\n  return txChunk;\n};\n/**\n * Modifies the value of the `TxChunk` using the provided function.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by updating its internal state. It does not return a\n * new TxChunk reference.\n *\n * **Example** (Modifying while returning a value)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Modify and return both old size and new chunk\n *   const oldSize = yield* TxChunk.modify(txChunk, (chunk) => [\n *     Chunk.size(chunk), // return value (old size)\n *     Chunk.append(chunk, 4) // new value\n *   ])\n *\n *   const newChunk = yield* TxChunk.get(txChunk)\n *   return [oldSize, Chunk.toArray(newChunk)]\n * })\n *\n * await Effect.runPromise(program) // => [3, [1, 2, 3, 4]]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, f) => TxRef.modify(self.ref, f));\n/**\n * Updates the value of the `TxChunk` using the provided function.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by updating its internal state. It does not return a\n * new TxChunk reference.\n *\n * **Example** (Updating the stored chunk)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Update the chunk by reversing it atomically\n *   yield* TxChunk.update(txChunk, (chunk) => Chunk.reverse(chunk))\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [3, 2, 1]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, f) => TxRef.update(self.ref, f));\n/**\n * Reads the current chunk from the `TxChunk`.\n *\n * **Example** (Reading the current chunk)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Read the current value within a transaction\n *   const chunk = yield* TxChunk.get(txChunk)\n *   return [Chunk.toArray(chunk), Chunk.size(chunk)]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3], 3]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const get = self => TxRef.get(self.ref);\n/**\n * Sets the value of the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by replacing its internal state with the provided\n * chunk. It does not return a new TxChunk reference.\n *\n * **Example** (Replacing the stored chunk)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Replace the entire chunk content\n *   const newChunk = Chunk.fromIterable([10, 20, 30, 40])\n *   yield* TxChunk.set(txChunk, newChunk)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [10, 20, 30, 40]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(2, (self, chunk) => TxRef.set(self.ref, chunk));\n/**\n * Appends an element to the end of the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by adding the element to the end. It does not return a\n * new TxChunk reference.\n *\n * **Example** (Appending an element)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Add element to the end atomically\n *   yield* TxChunk.append(txChunk, 4)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const append = /*#__PURE__*/dual(2, (self, element) => update(self, current => Chunk.append(current, element)));\n/**\n * Prepends an element to the beginning of the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by adding the element to the beginning. It does not\n * return a new TxChunk reference.\n *\n * **Example** (Prepending an element)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([2, 3, 4])\n *\n *   // Add element to the beginning atomically\n *   yield* TxChunk.prepend(txChunk, 1)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, element) => update(self, current => Chunk.prepend(current, element)));\n/**\n * Gets the size of the `TxChunk`.\n *\n * **Example** (Getting the size)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5])\n *\n *   // Get the current size - automatically transactional\n *   const currentSize = yield* TxChunk.size(txChunk)\n *\n *   // Size is tracked for conflict detection\n *   yield* TxChunk.append(txChunk, 6)\n *   const newSize = yield* TxChunk.size(txChunk)\n *   return [currentSize, newSize]\n * })\n *\n * await Effect.runPromise(program) // => [5, 6]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const size = self => modify(self, current => [Chunk.size(current), current]);\n/**\n * Checks whether the `TxChunk` is empty.\n *\n * **Example** (Checking for an empty chunk)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const emptyChunk = yield* TxChunk.empty<number>()\n *   const nonEmptyChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Check if chunks are empty - automatically transactional\n *   const isEmpty1 = yield* TxChunk.isEmpty(emptyChunk)\n *   const isEmpty2 = yield* TxChunk.isEmpty(nonEmptyChunk)\n *\n *   return [isEmpty1, isEmpty2]\n * })\n *\n * await Effect.runPromise(program) // => [true, false]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isEmpty = self => modify(self, current => [Chunk.isEmpty(current), current]);\n/**\n * Checks whether the `TxChunk` is non-empty.\n *\n * **Example** (Checking for a non-empty chunk)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const emptyChunk = yield* TxChunk.empty<number>()\n *   const nonEmptyChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *\n *   // Check if chunks are non-empty - automatically transactional\n *   const isNonEmpty1 = yield* TxChunk.isNonEmpty(emptyChunk)\n *   const isNonEmpty2 = yield* TxChunk.isNonEmpty(nonEmptyChunk)\n *\n *   return [isNonEmpty1, isNonEmpty2]\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isNonEmpty = self => modify(self, current => [Chunk.isNonEmpty(current), current]);\n/**\n * Takes the first `n` elements from the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by keeping only the first n elements. It does not\n * return a new TxChunk reference.\n *\n * **Example** (Taking leading elements)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5])\n *\n *   // Take only the first 3 elements - automatically transactional\n *   yield* TxChunk.take(txChunk, 3)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => update(self, current => Chunk.take(current, n)));\n/**\n * Drops the first `n` elements from the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by removing the first n elements. It does not return a\n * new TxChunk reference.\n *\n * **Example** (Dropping leading elements)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5])\n *\n *   // Drop the first 2 elements - automatically transactional\n *   yield* TxChunk.drop(txChunk, 2)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [3, 4, 5]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => update(self, current => Chunk.drop(current, n)));\n/**\n * Takes a slice of the `TxChunk` from `start` to `end` (exclusive).\n *\n * **Details**\n *\n * This function mutates the original TxChunk by keeping only the elements in the specified range. It\n * does not return a new TxChunk reference.\n *\n * **Example** (Taking a slice)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6, 7])\n *\n *   // Take elements from index 2 to 5 (exclusive) - automatically transactional\n *   yield* TxChunk.slice(txChunk, 2, 5)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [3, 4, 5]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const slice = /*#__PURE__*/dual(3, (self, start, end) => update(self, current => Chunk.take(Chunk.drop(current, start), end - start)));\n/**\n * Maps each element of the `TxChunk` using a function that returns the same\n * element type.\n *\n * **Details**\n *\n * This function mutates the original `TxChunk` by transforming each element in place. It does not\n * return a new `TxChunk` reference.\n *\n * **Example** (Mapping elements)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4])\n *\n *   // Transform each element atomically (must maintain same type)\n *   yield* TxChunk.map(txChunk, (n) => n * 2)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [2, 4, 6, 8]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => update(self, current => Chunk.map(current, f)));\n/**\n * Filters the `TxChunk` keeping only elements that satisfy the predicate.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by removing elements that don't match the predicate. It\n * does not return a new TxChunk reference.\n *\n * **Example** (Filtering elements)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6])\n *\n *   // Keep only even numbers atomically\n *   yield* TxChunk.filter(txChunk, (n) => n % 2 === 0)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [2, 4, 6]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => update(self, current => Chunk.filter(current, predicate)));\n/**\n * Concatenates another chunk to the end of the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by appending all elements from the other chunk. It does\n * not return a new TxChunk reference.\n *\n * **Example** (Appending another chunk)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([1, 2, 3])\n *   const otherChunk = Chunk.fromIterable([4, 5, 6])\n *\n *   // Append all elements from another chunk atomically\n *   yield* TxChunk.appendAll(txChunk, otherChunk)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, other) => update(self, current => Chunk.appendAll(current, other)));\n/**\n * Concatenates another chunk to the beginning of the `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by prepending all elements from the other chunk. It\n * does not return a new TxChunk reference.\n *\n * **Example** (Prepending another chunk)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk = yield* TxChunk.fromIterable([4, 5, 6])\n *   const otherChunk = Chunk.fromIterable([1, 2, 3])\n *\n *   // Prepend all elements from another chunk atomically\n *   yield* TxChunk.prependAll(txChunk, otherChunk)\n *\n *   const result = yield* TxChunk.get(txChunk)\n *   return Chunk.toArray(result)\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const prependAll = /*#__PURE__*/dual(2, (self, other) => update(self, current => Chunk.prependAll(current, other)));\n/**\n * Concatenates another `TxChunk` to the end of this `TxChunk`.\n *\n * **Details**\n *\n * This function mutates the original TxChunk by appending all elements from the other TxChunk. It\n * does not return a new TxChunk reference.\n *\n * **Example** (Concatenating TxChunks)\n *\n * ```ts import.meta.vitest\n * import { Chunk, Effect, TxChunk } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const txChunk1 = yield* TxChunk.fromIterable([1, 2, 3])\n *   const txChunk2 = yield* TxChunk.fromIterable([4, 5, 6])\n *\n *   // Concatenate atomically within a transaction\n *   yield* TxChunk.concat(txChunk1, txChunk2)\n *\n *   const result = yield* TxChunk.get(txChunk1)\n *\n *   // Original txChunk2 is unchanged\n *   const original = yield* TxChunk.get(txChunk2)\n *   return [Chunk.toArray(result), Chunk.toArray(original)]\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5, 6], [4, 5, 6]]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const concat = /*#__PURE__*/dual(2, (self, other) => Effect.gen(function* () {\n  const otherChunk = yield* get(other);\n  yield* appendAll(self, otherChunk);\n}).pipe(Effect.tx));\n//# sourceMappingURL=TxChunk.js.map","import * as Cause from \"./Cause.js\";\nimport * as Chunk from \"./Chunk.js\";\nimport * as Effect from \"./Effect.js\";\nimport { dual } from \"./Function.js\";\nimport { NodeInspectSymbol, toJson } from \"./Inspectable.js\";\nimport * as Option from \"./Option.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport { isDoneCause } from \"./Pull.js\";\nimport * as TxChunk from \"./TxChunk.js\";\nimport * as TxRef from \"./TxRef.js\";\nconst EnqueueTypeId = \"~effect/transactions/TxQueue/Enqueue\";\nconst DequeueTypeId = \"~effect/transactions/TxQueue/Dequeue\";\nconst TypeId = \"~effect/transactions/TxQueue\";\n/**\n * Checks whether the given value is a TxEnqueue.\n *\n * **Example** (Checking enqueue handles)\n *\n * ```ts import.meta.vitest\n * import { TxQueue } from \"effect\"\n *\n * const someValue: unknown = {}\n * TxQueue.isTxEnqueue(someValue) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isTxEnqueue = u => hasProperty(u, EnqueueTypeId);\n/**\n * Checks whether the given value is a TxDequeue.\n *\n * **Example** (Checking dequeue handles)\n *\n * ```ts import.meta.vitest\n * import { TxQueue } from \"effect\"\n *\n * const someValue: unknown = {}\n * TxQueue.isTxDequeue(someValue) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isTxDequeue = u => hasProperty(u, DequeueTypeId);\n/**\n * Checks whether the given value is a TxQueue.\n *\n * **Example** (Checking queue handles)\n *\n * ```ts import.meta.vitest\n * import { TxQueue } from \"effect\"\n *\n * const someValue: unknown = {}\n * TxQueue.isTxQueue(someValue) // => false\n * ```\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isTxQueue = u => hasProperty(u, TypeId);\n// =============================================================================\n// Proto\n// =============================================================================\nconst TxQueueProto = {\n  [EnqueueTypeId]: {\n    _A: _ => _,\n    _E: _ => _\n  },\n  [DequeueTypeId]: {\n    _A: _ => _,\n    _E: _ => _\n  },\n  [TypeId]: {\n    _A: _ => _,\n    _E: _ => _\n  },\n  [NodeInspectSymbol]() {\n    return toJson(this);\n  },\n  toString() {\n    return `TxQueue(${this.strategy}, ${this.capacity})`;\n  },\n  toJSON() {\n    return {\n      _id: \"TxQueue\",\n      strategy: this.strategy,\n      capacity: this.capacity\n    };\n  }\n};\n// =============================================================================\n// Constructors\n// =============================================================================\n/**\n * Creates a new bounded `TxQueue` with the specified capacity.\n *\n * **Details**\n *\n * This function returns a new TxQueue reference with the specified capacity. No existing TxQueue instances are modified.\n *\n * **Example** (Creating bounded queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a bounded queue (E defaults to never)\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   // Create a bounded queue with error channel\n *   const faultTolerantQueue = yield* TxQueue.bounded<number, string>(10)\n *\n *   // Offer items - will succeed until capacity is reached\n *   yield* TxQueue.offer(queue, 1)\n *   yield* TxQueue.offer(queue, 2)\n *\n *   return yield* TxQueue.take(queue)\n * })\n *\n * await Effect.runPromise(program) // => 1\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const bounded = capacity => Effect.gen(function* () {\n  const items = yield* TxChunk.empty();\n  const stateRef = yield* TxRef.make({\n    _tag: \"Open\"\n  });\n  const txQueue = Object.create(TxQueueProto);\n  txQueue.strategy = \"bounded\";\n  txQueue.capacity = capacity;\n  txQueue.items = items;\n  txQueue.stateRef = stateRef;\n  return txQueue;\n}).pipe(Effect.tx);\n/**\n * Creates a new unbounded `TxQueue` with unlimited capacity.\n *\n * **Details**\n *\n * This function returns a new TxQueue reference with unlimited capacity. No existing TxQueue instances are modified.\n *\n * **Example** (Creating unbounded queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create an unbounded queue (E defaults to never)\n *   const queue = yield* TxQueue.unbounded<string>()\n *\n *   // Create an unbounded queue with error channel\n *   const faultTolerantQueue = yield* TxQueue.unbounded<string, Error>()\n *\n *   // Can offer unlimited items\n *   yield* TxQueue.offer(queue, \"hello\")\n *   yield* TxQueue.offer(queue, \"world\")\n *\n *   return yield* TxQueue.size(queue)\n * })\n *\n * await Effect.runPromise(program) // => 2\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const unbounded = () => Effect.gen(function* () {\n  const items = yield* TxChunk.empty();\n  const stateRef = yield* TxRef.make({\n    _tag: \"Open\"\n  });\n  const txQueue = Object.create(TxQueueProto);\n  txQueue.strategy = \"unbounded\";\n  txQueue.capacity = Number.POSITIVE_INFINITY;\n  txQueue.items = items;\n  txQueue.stateRef = stateRef;\n  return txQueue;\n}).pipe(Effect.tx);\n/**\n * Creates a new dropping `TxQueue` with the specified capacity that drops new items when full.\n *\n * **Details**\n *\n * This function returns a new TxQueue reference with dropping strategy. No existing TxQueue instances are modified.\n *\n * **Example** (Creating dropping queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a dropping queue with capacity 2\n *   const queue = yield* TxQueue.dropping<number>(2)\n *\n *   // Fill to capacity\n *   yield* TxQueue.offer(queue, 1)\n *   yield* TxQueue.offer(queue, 2)\n *\n *   // This will be dropped (returns false)\n *   return yield* TxQueue.offer(queue, 3)\n * })\n *\n * await Effect.runPromise(program) // => false\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const dropping = capacity => Effect.gen(function* () {\n  const items = yield* TxChunk.empty();\n  const stateRef = yield* TxRef.make({\n    _tag: \"Open\"\n  });\n  const txQueue = Object.create(TxQueueProto);\n  txQueue.strategy = \"dropping\";\n  txQueue.capacity = capacity;\n  txQueue.items = items;\n  txQueue.stateRef = stateRef;\n  return txQueue;\n}).pipe(Effect.tx);\n/**\n * Creates a new sliding `TxQueue` with the specified capacity that evicts old items when full.\n *\n * **Details**\n *\n * This function returns a new TxQueue reference with sliding strategy. No existing TxQueue instances are modified.\n *\n * **Example** (Creating sliding queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a sliding queue with capacity 2\n *   const queue = yield* TxQueue.sliding<number>(2)\n *\n *   // Fill to capacity\n *   yield* TxQueue.offer(queue, 1)\n *   yield* TxQueue.offer(queue, 2)\n *\n *   // This will evict item 1 and add 3\n *   yield* TxQueue.offer(queue, 3)\n *\n *   return yield* TxQueue.take(queue)\n * })\n *\n * await Effect.runPromise(program) // => 2\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const sliding = capacity => Effect.gen(function* () {\n  const items = yield* TxChunk.empty();\n  const stateRef = yield* TxRef.make({\n    _tag: \"Open\"\n  });\n  const txQueue = Object.create(TxQueueProto);\n  txQueue.strategy = \"sliding\";\n  txQueue.capacity = capacity;\n  txQueue.items = items;\n  txQueue.stateRef = stateRef;\n  return txQueue;\n}).pipe(Effect.tx);\n// =============================================================================\n// Core Queue Operations\n// =============================================================================\n/**\n * Offers an item to the queue and returns whether it was accepted.\n *\n * **Details**\n *\n * Open unbounded queues always accept; open bounded queues retry while full; dropping queues return `false` when full; sliding queues evict the oldest item when full. Closing or done queues return `false`. This function mutates the original TxQueue by adding the item according to the queue's strategy. It does not return a new TxQueue reference.\n *\n * **Example** (Offering a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   // Offer an item - returns true if accepted\n *   return yield* TxQueue.offer(queue, 42)\n * })\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const offer = /*#__PURE__*/dual(2, (self, value) => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag === \"Done\" || state._tag === \"Closing\") {\n    return false;\n  }\n  const currentSize = yield* size(self);\n  // Unbounded - always accept\n  if (self.strategy === \"unbounded\") {\n    yield* TxChunk.append(self.items, value);\n    return true;\n  }\n  // For bounded queues, check capacity\n  if (currentSize < self.capacity) {\n    yield* TxChunk.append(self.items, value);\n    return true;\n  }\n  // Queue is at capacity, strategy-specific behavior\n  if (self.strategy === \"dropping\") {\n    return false; // Drop the new item\n  }\n  if (self.strategy === \"sliding\") {\n    yield* TxChunk.drop(self.items, 1); // Remove oldest item\n    yield* TxChunk.append(self.items, value); // Add new item\n    return true;\n  }\n  // bounded strategy - block until space is available\n  return yield* Effect.txRetry;\n}).pipe(Effect.tx));\n/**\n * Offers multiple items to the queue, returning the items that were not\n * accepted.\n *\n * **Details**\n *\n * Each item follows `offer` semantics: bounded queues retry while full, dropping queues reject new items when full, sliding queues evict old items to accept new items, and closing or done queues reject all items. This function mutates the original TxQueue by adding items according to the queue's strategy. It does not return a new TxQueue reference.\n *\n * **Example** (Offering multiple values)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   // Offer multiple items - returns rejected items as array\n *   return yield* TxQueue.offerAll(queue, [1, 2, 3, 4, 5])\n * })\n *\n * await Effect.runPromise(program) // => []\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const offerAll = /*#__PURE__*/dual(2, (self, values) => {\n  const valuesArray = Array.from(values);\n  return Effect.gen(function* () {\n    const rejected = [];\n    for (const value of valuesArray) {\n      const accepted = yield* offer(self, value);\n      if (!accepted) {\n        rejected.push(value);\n      }\n    }\n    return rejected;\n  }).pipe(Effect.tx);\n});\n/**\n * Takes the next item from the queue, retrying the transaction while the queue\n * is empty.\n *\n * **Details**\n *\n * If the queue is done, the effect fails with the queue's completion cause. This function mutates the original TxQueue by removing the first item. It does not return a new TxQueue reference.\n *\n * **Example** (Taking a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(10)\n *   yield* TxQueue.offer(queue, 42)\n *\n *   // Take an item - blocks if empty\n *   const item = yield* TxQueue.take(queue)\n *\n *   // When queue fails, take fails with the same error\n *   yield* TxQueue.fail(queue, \"queue error\")\n *   const result = yield* Effect.exit(TxQueue.take(queue))\n *   return [item, result] as const\n * })\n *\n * await Effect.runPromise(program) // => [42, Exit.fail(\"queue error\")]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const take = self => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  // Check if queue is done - forward the cause directly\n  if (state._tag === \"Done\") {\n    return yield* Effect.failCause(state.cause);\n  }\n  // If no items available, retry transaction\n  if (yield* isEmpty(self)) {\n    return yield* Effect.txRetry;\n  }\n  // Take item from queue\n  const chunk = yield* TxChunk.get(self.items);\n  const head = Chunk.head(chunk);\n  if (Option.isNone(head)) {\n    return yield* Effect.txRetry;\n  }\n  yield* TxChunk.drop(self.items, 1);\n  // Check if we need to transition Closing → Done\n  if (state._tag === \"Closing\" && (yield* isEmpty(self))) {\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause: state.cause\n    });\n  }\n  return head.value;\n}).pipe(Effect.tx);\n/**\n * Tries to take an item from the queue without blocking.\n *\n * **Example** (Polling without blocking)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   // Poll returns Option.none if empty\n *   const maybe = yield* TxQueue.poll(queue)\n *\n *   yield* TxQueue.offer(queue, 42)\n *   const item = yield* TxQueue.poll(queue)\n *   return [maybe, item] as const\n * })\n *\n * await Effect.runPromise(program) // => [Option.none(), Option.some(42)]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const poll = self => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag === \"Done\") {\n    return Option.none();\n  }\n  const chunk = yield* TxChunk.get(self.items);\n  const head = Chunk.head(chunk);\n  if (Option.isNone(head)) {\n    return Option.none();\n  }\n  yield* TxChunk.drop(self.items, 1);\n  if (state._tag === \"Closing\" && (yield* isEmpty(self))) {\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause: state.cause\n    });\n  }\n  return Option.some(head.value);\n}).pipe(Effect.tx);\n/**\n * Takes all items from the queue. Blocks if the queue is empty.\n *\n * **Details**\n *\n * If the queue is already in a failed state, the error is propagated through the E-channel. This follows the same patterns as `take` and waits when there are no elements. It returns a non-empty array because it blocks until at least one item is available. This function mutates the original TxQueue by removing all items. It does not return a new TxQueue reference.\n *\n * **Example** (Taking all queued values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(10)\n *   yield* TxQueue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n *   // Take all items atomically - returns NonEmptyArray\n *   return yield* TxQueue.takeAll(queue)\n * })\n *\n * // Error propagation example\n * const errorExample = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(5)\n *   yield* TxQueue.offerAll(queue, [1, 2])\n *   yield* TxQueue.fail(queue, \"processing error\")\n *\n *   // takeAll() propagates the queue error through E-channel\n *   return yield* Effect.exit(TxQueue.takeAll(queue))\n * })\n *\n * await Effect.runPromise(program) // => [1, 2, 3, 4, 5]\n * await Effect.runPromise(errorExample) // => Exit.fail(\"processing error\")\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const takeAll = self => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  // Handle done queue\n  if (state._tag === \"Done\") {\n    return yield* Effect.failCause(state.cause);\n  }\n  // Wait if empty - same pattern as take()\n  if (yield* isEmpty(self)) {\n    return yield* Effect.txRetry;\n  }\n  const chunk = yield* TxChunk.get(self.items);\n  // Take all items (guaranteed non-empty due to isEmpty check above)\n  const items = Chunk.toArray(chunk);\n  yield* TxChunk.set(self.items, Chunk.empty());\n  // Check if we need to transition Closing → Done\n  if (state._tag === \"Closing\") {\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause: state.cause\n    });\n  }\n  return items;\n}).pipe(Effect.tx);\n/**\n * Takes up to `n` items from the queue in a single transaction.\n *\n * **Details**\n *\n * For an open queue, waits until `min(n, capacity)` items are available, then removes that many items. If `n` is less than or equal to zero, returns an empty array without modifying the queue. If the queue is closing, drains the currently available items and transitions to `Done`. If the queue is already done, the effect fails with the queue's completion cause. This function mutates the original TxQueue by removing the taken items. It does not return a new TxQueue reference.\n *\n * **Example** (Taking a fixed number of values)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(5)\n *   yield* TxQueue.offerAll(queue, [1, 2, 3, 4])\n *\n *   const items = yield* TxQueue.takeN(queue, 4)\n *\n *   // This requests more than capacity (5), so takes all available (up to 5)\n *   yield* TxQueue.offerAll(queue, [5, 6, 7, 8, 9])\n *   const all = yield* TxQueue.takeN(queue, 10)\n *   return [items, all] as const\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3, 4], [5, 6, 7, 8, 9]]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const takeN = /*#__PURE__*/dual(2, (self, n) => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  // Check if queue is done - forward the cause directly\n  if (state._tag === \"Done\") {\n    return yield* Effect.failCause(state.cause);\n  }\n  const currentSize = yield* size(self);\n  // Determine how many items we can/should take\n  const requestedCount = n;\n  const maxPossible = Math.min(requestedCount, self.capacity);\n  // If we can't get the requested amount due to capacity constraints,\n  // take what the capacity allows. Otherwise, wait for the full amount.\n  const shouldWaitForFull = requestedCount <= self.capacity;\n  const minimumRequired = shouldWaitForFull ? requestedCount : maxPossible;\n  // If we don't have enough items available\n  if (currentSize < minimumRequired) {\n    // If queue is closing, transition to done and return what we have\n    if (state._tag === \"Closing\") {\n      if (yield* isEmpty(self)) {\n        yield* TxRef.set(self.stateRef, {\n          _tag: \"Done\",\n          cause: state.cause\n        });\n        return [];\n      }\n      // Take all remaining items when closing\n      const chunk = yield* TxChunk.get(self.items);\n      const taken = Chunk.toArray(chunk);\n      yield* TxChunk.set(self.items, Chunk.empty());\n      yield* TxRef.set(self.stateRef, {\n        _tag: \"Done\",\n        cause: state.cause\n      });\n      return taken;\n    }\n    // Queue is still open but not enough items - retry transaction\n    return yield* Effect.txRetry;\n  }\n  // Take the determined number of items\n  const toTake = minimumRequired;\n  const chunk = yield* TxChunk.get(self.items);\n  const taken = Chunk.take(chunk, toTake);\n  yield* TxChunk.drop(self.items, toTake);\n  // Check if we need to transition Closing → Done\n  if (state._tag === \"Closing\" && (yield* isEmpty(self))) {\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause: state.cause\n    });\n  }\n  return Chunk.toArray(taken);\n}).pipe(Effect.tx));\n/**\n * Takes between `min` and `max` currently available items, waiting for `min` on\n * an open queue.\n *\n * **Details**\n *\n * If the queue is closing, drains the currently available items even when fewer than `min` are available and transitions to `Done`. Invalid ranges (`min <= 0`, `max <= 0`, or `min > max`) return an empty array. If the queue is already done, the effect fails with the queue's completion cause.\n *\n * **Example** (Taking batches within bounds)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *   yield* TxQueue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7, 8])\n *\n *   // Take between 2 and 5 items\n *   const batch1 = yield* TxQueue.takeBetween(queue, 2, 5)\n *\n *   // Take between 1 and 10 items (but only 3 remain)\n *   const batch2 = yield* TxQueue.takeBetween(queue, 1, 10)\n *\n *   // Would wait for at least 1 item to be available\n *   // const batch3 = yield* TxQueue.takeBetween(queue, 1, 3)\n *   return [batch1, batch2] as const\n * })\n *\n * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5], [6, 7, 8]]\n * ```\n *\n * @category taking\n * @since 2.0.0\n */\nexport const takeBetween = /*#__PURE__*/dual(3, (self, min, max) => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  // Check if queue is done - forward the cause directly\n  if (state._tag === \"Done\") {\n    return yield* Effect.failCause(state.cause);\n  }\n  // Validate parameters\n  if (min <= 0 || max <= 0 || min > max) {\n    return [];\n  }\n  const currentSize = yield* size(self);\n  // If we have less than minimum required items\n  if (currentSize < min) {\n    // If queue is closing, transition to done and return what we have\n    if (state._tag === \"Closing\") {\n      if (yield* isEmpty(self)) {\n        yield* TxRef.set(self.stateRef, {\n          _tag: \"Done\",\n          cause: state.cause\n        });\n        return [];\n      }\n      // Take all remaining items when closing (if >= min or all available)\n      const chunk = yield* TxChunk.get(self.items);\n      const taken = Chunk.toArray(chunk);\n      yield* TxChunk.set(self.items, Chunk.empty());\n      yield* TxRef.set(self.stateRef, {\n        _tag: \"Done\",\n        cause: state.cause\n      });\n      return taken;\n    }\n    // Queue is still open but not enough items - retry transaction\n    return yield* Effect.txRetry;\n  }\n  // We have at least the minimum, take up to the maximum\n  const toTake = Math.min(currentSize, max);\n  const chunk = yield* TxChunk.get(self.items);\n  const taken = Chunk.take(chunk, toTake);\n  yield* TxChunk.drop(self.items, toTake);\n  // Check if we need to transition Closing → Done\n  if (state._tag === \"Closing\" && (yield* isEmpty(self))) {\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause: state.cause\n    });\n  }\n  return Chunk.toArray(taken);\n}).pipe(Effect.tx));\n/**\n * Waits transactionally for the next item and returns it without removing it.\n *\n * **Details**\n *\n * If the queue is open but empty, the transaction retries until an item is available or the queue completes. If the queue is done, the queue's completion cause is propagated through the error channel.\n *\n * **Example** (Peeking without removing values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(10)\n *   yield* TxQueue.offer(queue, 42)\n *\n *   // Peek at the next item without removing it\n *   const item = yield* TxQueue.peek(queue)\n *\n *   // Item is still in the queue\n *   const size = yield* TxQueue.size(queue)\n *   return [item, size] as const\n * })\n *\n * // Error handling example\n * const errorExample = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(5)\n *   yield* TxQueue.fail(queue, \"queue failed\")\n *\n *   // peek() propagates the queue error through E-channel\n *   return yield* Effect.exit(TxQueue.peek(queue))\n * })\n *\n * await Effect.runPromise(program) // => [42, 1]\n * await Effect.runPromise(errorExample) // => Exit.fail(\"queue failed\")\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const peek = self => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag === \"Done\") {\n    return yield* Effect.failCause(state.cause);\n  }\n  const chunk = yield* TxChunk.get(self.items);\n  const head = Chunk.head(chunk);\n  if (Option.isNone(head)) {\n    return yield* Effect.txRetry;\n  }\n  return head.value;\n}).pipe(Effect.tx);\n/**\n * Gets the current size of the queue.\n *\n * **Example** (Reading queue size)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *   yield* TxQueue.offerAll(queue, [1, 2, 3])\n *\n *   return yield* TxQueue.size(queue)\n * })\n *\n * await Effect.runPromise(program) // => 3\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const size = self => TxChunk.size(self.items);\n/**\n * Checks whether the queue is empty.\n *\n * **Example** (Checking whether a queue is empty)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   const empty = yield* TxQueue.isEmpty(queue)\n *\n *   yield* TxQueue.offer(queue, 42)\n *   const stillEmpty = yield* TxQueue.isEmpty(queue)\n *   return [empty, stillEmpty] as const\n * })\n *\n * await Effect.runPromise(program) // => [true, false]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isEmpty = self => TxChunk.isEmpty(self.items);\n/**\n * Checks whether the queue is at capacity.\n *\n * **Example** (Checking whether a queue is full)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(2)\n *\n *   const full = yield* TxQueue.isFull(queue)\n *\n *   yield* TxQueue.offerAll(queue, [1, 2])\n *   const nowFull = yield* TxQueue.isFull(queue)\n *   return [full, nowFull] as const\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isFull = self => self.capacity === Number.POSITIVE_INFINITY ? Effect.succeed(false) : Effect.map(size(self), currentSize => currentSize >= self.capacity);\n/**\n * Interrupts the queue gracefully with the current fiber's interruption cause.\n *\n * **Details**\n *\n * If the queue still contains items, it enters the closing state so buffered items can be drained before consumers observe the interruption. If it is empty, it transitions directly to done. Returns `false` if the queue was already closing or done.\n *\n * **Example** (Interrupting queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *   yield* TxQueue.offer(queue, 42)\n *\n *   // Interrupt gracefully - allows remaining items to be consumed\n *   return yield* TxQueue.interrupt(queue)\n * })\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const interrupt = self => Effect.withFiber(fiber => failCause(self, Cause.interrupt(fiber.id)));\n/**\n * Fails the queue with the specified error, discarding any buffered items.\n *\n * **Details**\n *\n * The queue transitions directly to done with `Cause.fail(error)`. Returns `false` if the queue was already closing or done.\n *\n * **Example** (Failing queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(10)\n *\n *   // Fail the queue with an error\n *   return yield* TxQueue.fail(queue, \"connection lost\")\n * })\n *\n * await Effect.runPromise(program) // => true\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const fail = /*#__PURE__*/dual(2, (self, error) => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag !== \"Open\") {\n    return false; // Already closing/done\n  }\n  // Fail transitions directly to Done, clearing items\n  yield* TxChunk.set(self.items, Chunk.empty());\n  yield* TxRef.set(self.stateRef, {\n    _tag: \"Done\",\n    cause: Cause.fail(error)\n  });\n  return true;\n}).pipe(Effect.tx));\n/**\n * Completes the queue with the specified cause.\n *\n * **Details**\n *\n * If the queue is empty, it transitions directly to done. If it still contains items, it enters the closing state so buffered items can be drained before the cause is observed. Returns `false` if the queue was already closing or done.\n *\n * **Example** (Failing queues with causes)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   // Complete with specific cause\n *   const cause = Cause.interrupt()\n *   const result = yield* TxQueue.failCause(queue, cause)\n *   return [cause, result] as const\n * })\n *\n * await Effect.runPromise(program) // => [Cause.interrupt(), true]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const failCause = /*#__PURE__*/dual(2, (self, cause) => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag !== \"Open\") {\n    return false; // Already closing/done\n  }\n  if (yield* isEmpty(self)) {\n    // Can transition directly to Done\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause\n    });\n  } else {\n    // Need to go through Closing state\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Closing\",\n      cause\n    });\n  }\n  return true;\n}).pipe(Effect.tx));\n/**\n * Ends a queue by signaling completion with a `Cause.Done` error.\n *\n * **Details**\n *\n * This is a convenience wrapper around `failCause` for queues whose error channel can contain `Cause.Done`. If buffered items remain, the queue enters the closing state and those items may still be consumed before later `take` or `peek` operations fail with `Cause.Done`.\n *\n * **Example** (Ending queues)\n *\n * ```ts import.meta.vitest\n * import { Cause, Effect, Exit, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, Cause.Done>(10)\n *\n *   // Signal the end of the queue\n *   const result = yield* TxQueue.end(queue)\n *\n *   // All operations will now fail with Done\n *   const takeResult = yield* Effect.exit(TxQueue.take(queue))\n *\n *   const peekResult = yield* Effect.exit(TxQueue.peek(queue))\n *   return [result, takeResult, peekResult] as const\n * })\n *\n * await Effect.runPromise(program) // => [true, Exit.fail(Cause.Done()), Exit.fail(Cause.Done())]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const end = self => failCause(self, Cause.fail(Cause.Done()));\n/**\n * Removes and returns all currently buffered elements.\n *\n * **Details**\n *\n * If the queue is closing, draining its buffered elements transitions it to done. If the queue is already done with a `Cause.Done` error, returns an empty array. If the queue is done for any other cause, including interruption or failure, that cause is propagated.\n *\n * **Example** (Clearing queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *   yield* TxQueue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n *   const sizeBefore = yield* TxQueue.size(queue)\n *\n *   const cleared = yield* TxQueue.clear(queue)\n *\n *   const sizeAfter = yield* TxQueue.size(queue)\n *   return [sizeBefore, cleared, sizeAfter] as const\n * })\n *\n * await Effect.runPromise(program) // => [5, [1, 2, 3, 4, 5], 0]\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const clear = self => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag === \"Done\") {\n    // Return empty array only for halt causes (like Cause.Done)\n    if (isDoneCause(state.cause)) {\n      return [];\n    }\n    return yield* Effect.failCause(state.cause);\n  }\n  const chunk = yield* TxChunk.get(self.items);\n  yield* TxChunk.set(self.items, Chunk.empty());\n  if (state._tag === \"Closing\") {\n    yield* TxRef.set(self.stateRef, {\n      _tag: \"Done\",\n      cause: state.cause\n    });\n  }\n  return Chunk.toArray(chunk);\n}).pipe(Effect.tx);\n/**\n * Shuts down the queue immediately by clearing all items and interrupting it (legacy compatibility).\n *\n * **Details**\n *\n * This operation clears all items from the queue using `clear`, then interrupts the queue using `interrupt`. This function mutates the original TxQueue by clearing its contents and marking it as shutdown. It does not return a new TxQueue reference.\n *\n * **Example** (Shutting down queues)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *   yield* TxQueue.offerAll(queue, [1, 2, 3, 4, 5])\n *\n *   const sizeBefore = yield* TxQueue.size(queue)\n *\n *   yield* TxQueue.shutdown(queue)\n *\n *   const sizeAfter = yield* TxQueue.size(queue)\n *\n *   const isShutdown = yield* TxQueue.isShutdown(queue)\n *   return [sizeBefore, sizeAfter, isShutdown] as const\n * })\n *\n * await Effect.runPromise(program) // => [5, 0, true]\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const shutdown = self => Effect.gen(function* () {\n  yield* Effect.ignore(clear(self));\n  return yield* interrupt(self);\n}).pipe(Effect.tx);\n/**\n * Checks whether the queue is in the open state.\n *\n * **Example** (Checking open state)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   const open = yield* TxQueue.isOpen(queue)\n *\n *   yield* TxQueue.interrupt(queue)\n *   const stillOpen = yield* TxQueue.isOpen(queue)\n *   return [open, stillOpen] as const\n * })\n *\n * await Effect.runPromise(program) // => [true, false]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isOpen = self => Effect.map(TxRef.get(self.stateRef), state => state._tag === \"Open\");\n/**\n * Checks whether the queue is in the closing state.\n *\n * **Example** (Checking closing state)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *   yield* TxQueue.offer(queue, 42)\n *\n *   const closing = yield* TxQueue.isClosing(queue)\n *\n *   yield* TxQueue.interrupt(queue)\n *   const nowClosing = yield* TxQueue.isClosing(queue)\n *   return [closing, nowClosing] as const\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isClosing = self => Effect.map(TxRef.get(self.stateRef), state => state._tag === \"Closing\");\n/**\n * Checks whether the queue is done (completed or failed).\n *\n * **Example** (Checking done state)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   const done = yield* TxQueue.isDone(queue)\n *\n *   yield* TxQueue.interrupt(queue)\n *   const nowDone = yield* TxQueue.isDone(queue)\n *   return [done, nowDone] as const\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 4.0.0\n */\nexport const isDone = self => Effect.map(TxRef.get(self.stateRef), state => state._tag === \"Done\");\n/**\n * Checks whether the queue is shutdown (legacy compatibility).\n *\n * **Example** (Checking shutdown state)\n *\n * ```ts import.meta.vitest\n * import { Effect, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number>(10)\n *\n *   const isShutdown = yield* TxQueue.isShutdown(queue)\n *\n *   yield* TxQueue.shutdown(queue)\n *   const nowShutdown = yield* TxQueue.isShutdown(queue)\n *   return [isShutdown, nowShutdown] as const\n * })\n *\n * await Effect.runPromise(program) // => [false, true]\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const isShutdown = self => isDone(self);\n/**\n * Waits for the queue to complete (either successfully or with failure).\n *\n * **Example** (Awaiting queue completion)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, TxQueue } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const queue = yield* TxQueue.bounded<number, string>(10)\n *\n *   const waiter = yield* Effect.forkChild(TxQueue.awaitCompletion(queue))\n *   yield* TxQueue.interrupt(queue)\n *\n *   yield* Fiber.join(waiter)\n *   return \"Queue completed successfully\"\n * })\n *\n * await Effect.runPromise(program) // => \"Queue completed successfully\"\n * ```\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const awaitCompletion = self => Effect.gen(function* () {\n  const state = yield* TxRef.get(self.stateRef);\n  if (state._tag === \"Done\") {\n    return void 0;\n  }\n  // Not done yet, retry transaction\n  return yield* Effect.txRetry;\n}).pipe(Effect.tx);\n//# sourceMappingURL=TxQueue.js.map","/**\n * Preview - Schemas for the in-app browser preview surface.\n *\n * The preview is desktop-only (Chromium <webview>); the server tracks per-thread\n * tab metadata so it survives client reconnects and multi-window. The desktop\n * renderer mediates: it owns the actual <webview> and reports navigation back to\n * the server via these RPCs, the server fans events to all subscribers.\n *\n * @module Preview\n */\nimport { Schema } from \"effect\";\nimport { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst Url = TrimmedNonEmptyString.check(Schema.isMaxLength(2048));\nconst Title = Schema.String.check(Schema.isMaxLength(512));\n\nexport const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));\nexport type PreviewTabId = typeof PreviewTabId.Type;\n\nexport const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;\nexport const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;\nexport const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;\n\nconst PreviewViewportDimension = Schema.Int.check(\n  Schema.isBetween({\n    minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,\n    maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,\n  }),\n);\n\nconst viewportAreaFilter = Schema.makeFilter(\n  ({ width, height }: { readonly width: number; readonly height: number }) =>\n    width * height <= PREVIEW_VIEWPORT_MAX_AREA ||\n    `Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,\n);\n\nexport const PreviewViewportSize = Schema.Struct({\n  width: PreviewViewportDimension,\n  height: PreviewViewportDimension,\n}).check(viewportAreaFilter);\nexport type PreviewViewportSize = typeof PreviewViewportSize.Type;\n\n/**\n * The page's measured viewport can be smaller than the minimum selectable\n * fixed size while fill mode follows a narrow panel. Keep measurement\n * validation separate from the stricter user-selectable size constraints.\n */\nexport const PreviewRenderedViewportSize = Schema.Struct({\n  width: Schema.Int.check(Schema.isGreaterThan(0)),\n  height: Schema.Int.check(Schema.isGreaterThan(0)),\n});\nexport type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;\n\nexport const PREVIEW_VIEWPORT_PRESET_IDS = [\n  \"iphone-se\",\n  \"iphone-xr\",\n  \"iphone-12-pro\",\n  \"iphone-14-pro-max\",\n  \"pixel-7\",\n  \"samsung-galaxy-s8-plus\",\n  \"samsung-galaxy-s20-ultra\",\n  \"ipad-mini\",\n  \"ipad-air\",\n  \"ipad-pro\",\n  \"surface-pro-7\",\n  \"surface-duo\",\n  \"galaxy-z-fold-5\",\n  \"asus-zenbook-fold\",\n  \"samsung-galaxy-a51-71\",\n  \"nest-hub\",\n  \"nest-hub-max\",\n] as const;\n\nexport const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);\nexport type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;\n\n/**\n * Preset IDs shipped before the Chrome-compatible catalog. Existing sessions\n * can still reconnect with these values, but new resize requests only expose\n * PREVIEW_VIEWPORT_PRESET_IDS.\n */\nconst LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [\n  \"desktop-1920x1080\",\n  \"desktop-1440x900\",\n  \"laptop-1366x768\",\n  \"laptop-1280x800\",\n  \"ipad-pro-11\",\n  \"iphone-15-pro\",\n  \"pixel-8\",\n  \"galaxy-s24\",\n] as const;\n\nconst StoredPreviewViewportPresetId = Schema.Literals([\n  ...PREVIEW_VIEWPORT_PRESET_IDS,\n  ...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,\n]);\n\nexport const PreviewViewportSetting = Schema.Union([\n  Schema.TaggedStruct(\"fill\", {}),\n  Schema.TaggedStruct(\"freeform\", {\n    ...PreviewViewportSize.fields,\n  }).check(viewportAreaFilter),\n  Schema.TaggedStruct(\"preset\", {\n    ...PreviewViewportSize.fields,\n    presetId: StoredPreviewViewportPresetId,\n  }).check(viewportAreaFilter),\n]);\nexport type PreviewViewportSetting = typeof PreviewViewportSetting.Type;\n\nexport const FILL_PREVIEW_VIEWPORT = {\n  _tag: \"fill\",\n} as const satisfies PreviewViewportSetting;\n\nexport const PreviewNavStatus = Schema.Union([\n  Schema.TaggedStruct(\"Idle\", {}),\n  Schema.TaggedStruct(\"Loading\", {\n    url: Url,\n    title: Title,\n  }),\n  Schema.TaggedStruct(\"Success\", {\n    url: Url,\n    title: Title,\n  }),\n  Schema.TaggedStruct(\"LoadFailed\", {\n    url: Url,\n    title: Title,\n    code: Schema.Int,\n    description: Schema.String,\n  }),\n]);\nexport type PreviewNavStatus = typeof PreviewNavStatus.Type;\n\nexport const PreviewSessionSnapshot = Schema.Struct({\n  threadId: TrimmedNonEmptyString,\n  tabId: PreviewTabId,\n  navStatus: PreviewNavStatus,\n  canGoBack: Schema.Boolean,\n  canGoForward: Schema.Boolean,\n  /** Missing snapshots from older servers are treated as fill-panel mode. */\n  viewport: Schema.optional(PreviewViewportSetting),\n  updatedAt: Schema.String,\n});\nexport type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;\n\nexport const PreviewOpenInput = Schema.Struct({\n  threadId: ThreadId,\n  /** Omit to create an empty (Idle) tab the user can type into. */\n  url: Schema.optional(Url),\n});\nexport type PreviewOpenInput = typeof PreviewOpenInput.Type;\n\nexport const PreviewNavigateInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n  url: Url,\n  resolvedTitle: Schema.optional(Title),\n});\nexport type PreviewNavigateInput = typeof PreviewNavigateInput.Type;\n\nexport const PreviewReportStatusInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n  navStatus: PreviewNavStatus,\n  canGoBack: Schema.Boolean,\n  canGoForward: Schema.Boolean,\n});\nexport type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;\n\nexport const PreviewRefreshInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n});\nexport type PreviewRefreshInput = typeof PreviewRefreshInput.Type;\n\nexport const PreviewResizeInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n  viewport: PreviewViewportSetting,\n});\nexport type PreviewResizeInput = typeof PreviewResizeInput.Type;\n\nexport const PreviewCloseInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: Schema.optional(PreviewTabId),\n});\nexport type PreviewCloseInput = typeof PreviewCloseInput.Type;\n\nexport const PreviewListInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type PreviewListInput = typeof PreviewListInput.Type;\n\nexport const PreviewListResult = Schema.Struct({\n  sessions: Schema.Array(PreviewSessionSnapshot),\n  /** Identifies the current server process so revision resets are safe. */\n  serverEpoch: TrimmedNonEmptyString,\n  /** Monotonic server state revision used to reject stale list responses. */\n  revision: NonNegativeInt,\n});\nexport type PreviewListResult = typeof PreviewListResult.Type;\n\nconst PreviewEventBaseSchema = Schema.Struct({\n  threadId: TrimmedNonEmptyString,\n  tabId: PreviewTabId,\n  createdAt: Schema.String,\n  /** Identifies the server process that emitted this event. */\n  serverEpoch: TrimmedNonEmptyString,\n  /** Monotonic server state revision shared with PreviewListResult. */\n  revision: PositiveInt,\n});\n\nconst PreviewOpenedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"opened\"),\n  snapshot: PreviewSessionSnapshot,\n});\n\nconst PreviewNavigatedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"navigated\"),\n  snapshot: PreviewSessionSnapshot,\n});\n\nconst PreviewResizedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"resized\"),\n  snapshot: PreviewSessionSnapshot,\n});\n\nconst PreviewFailedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"failed\"),\n  url: Url,\n  title: Title,\n  code: Schema.Int,\n  description: Schema.String,\n});\n\nconst PreviewClosedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"closed\"),\n});\n\nexport const PreviewEvent = Schema.Union([\n  PreviewOpenedEvent,\n  PreviewNavigatedEvent,\n  PreviewResizedEvent,\n  PreviewFailedEvent,\n  PreviewClosedEvent,\n]);\nexport type PreviewEvent = typeof PreviewEvent.Type;\n\n/**\n * A localhost server detected by the port scanner. Used to populate the\n * \"Local\" recommendations in the empty-state of the preview panel.\n */\nexport const DiscoveredLocalServer = Schema.Struct({\n  host: TrimmedNonEmptyString,\n  port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),\n  url: Url,\n  processName: Schema.NullOr(TrimmedNonEmptyString),\n  pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),\n  terminal: Schema.NullOr(\n    Schema.Struct({\n      threadId: ThreadId,\n      terminalId: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;\n\nexport const DiscoveredLocalServerList = Schema.Struct({\n  servers: Schema.Array(DiscoveredLocalServer),\n  scannedAt: Schema.String,\n});\nexport type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;\n\nexport class PreviewSessionLookupError extends Schema.TaggedErrorClass<PreviewSessionLookupError>()(\n  \"PreviewSessionLookupError\",\n  {\n    threadId: Schema.String,\n    tabId: Schema.String,\n  },\n) {\n  override get message() {\n    return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;\n  }\n}\n\nexport class PreviewInvalidUrlError extends Schema.TaggedErrorClass<PreviewInvalidUrlError>()(\n  \"PreviewInvalidUrlError\",\n  {\n    inputLength: Schema.Number,\n    reason: Schema.Literals([\"empty\", \"parse\", \"unsupported-protocol\", \"unexpected\"]),\n    protocol: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    const protocol = this.protocol === undefined ? \"\" : `: ${this.protocol}`;\n    return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;\n  }\n}\n\nexport const PreviewError = Schema.Union([PreviewSessionLookupError, PreviewInvalidUrlError]);\nexport type PreviewError = typeof PreviewError.Type;\n","import { Schema } from \"effect\";\n\nimport { EnvironmentId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport {\n  PREVIEW_VIEWPORT_MAX_AREA,\n  PreviewRenderedViewportSize,\n  PreviewTabId,\n  PreviewViewportPresetId,\n  PreviewViewportSetting,\n  PreviewViewportSize,\n} from \"./preview.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\n\nconst BoundedUrl = Schema.String.check(Schema.isTrimmed())\n  .check(Schema.isNonEmpty())\n  .check(Schema.isMaxLength(2048));\nconst URL_GUIDANCE =\n  \"Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.\";\nconst OptionalTimeoutMs = Schema.optional(\n  Schema.Int.check(Schema.isGreaterThan(0))\n    .check(Schema.isLessThanOrEqualTo(60_000))\n    .annotate({ description: \"Maximum wait in milliseconds. Defaults to 15000; maximum 60000.\" }),\n).annotate({ description: \"Maximum wait in milliseconds. Defaults to 15000; maximum 60000.\" });\n\n/** Operations understood by desktop hosts predating viewport resizing. */\nexport const PREVIEW_AUTOMATION_V1_OPERATIONS = [\n  \"status\",\n  \"open\",\n  \"navigate\",\n  \"snapshot\",\n  \"click\",\n  \"type\",\n  \"press\",\n  \"scroll\",\n  \"evaluate\",\n  \"waitFor\",\n  \"recordingStart\",\n  \"recordingStop\",\n] as const;\n\n/** Advertised by current desktop hosts for mixed-version routing. */\nexport const PREVIEW_AUTOMATION_OPERATIONS = [\n  ...PREVIEW_AUTOMATION_V1_OPERATIONS,\n  \"resize\",\n  \"setColorScheme\",\n] as const;\n\nexport const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_OPERATIONS);\nexport type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;\n\nconst PreviewAutomationTabTargetFields = {\n  tabId: Schema.optional(\n    PreviewTabId.annotate({\n      description:\n        \"Exact collaborative browser tab to target. Omit to use this agent session's current tab.\",\n    }),\n  ).annotate({\n    description:\n      \"Exact collaborative browser tab to target. Omit to use this agent session's current tab.\",\n  }),\n};\n\nexport const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);\nexport type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;\n\nexport const PreviewAutomationStatus = Schema.Struct({\n  available: Schema.Boolean,\n  visible: Schema.Boolean,\n  tabId: Schema.NullOr(PreviewTabId),\n  url: Schema.NullOr(Schema.String),\n  title: Schema.NullOr(Schema.String),\n  loading: Schema.Boolean,\n  /** Optional for compatibility with desktop hosts predating viewport sizing. */\n  viewportSetting: Schema.optional(PreviewViewportSetting),\n  /** Measured guest-page viewport in CSS pixels when a webview is ready. */\n  viewport: Schema.optional(PreviewRenderedViewportSize),\n});\nexport type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;\n\nexport const PreviewAutomationOpenInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  url: Schema.optional(BoundedUrl).annotate({\n    description: `Optional initial page URL. ${URL_GUIDANCE} Omit to open a blank tab.`,\n  }),\n  open: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether to open the thread-bound inline preview for the human. Defaults to true; set false for background-only automation.\",\n    }),\n  ),\n  show: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Deprecated alias for open. Whether to reveal the thread-bound inline preview to the human.\",\n    }),\n  ),\n  reuseExistingTab: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Reuse tabId when supplied, otherwise this agent session's current tab. Defaults to true; set false to create a new tab.\",\n    }),\n  ),\n})\n  .check(\n    Schema.makeFilter(\n      (input) =>\n        !(input.tabId !== undefined && input.reuseExistingTab === false) ||\n        \"tabId cannot be combined with reuseExistingTab=false.\",\n    ),\n  )\n  .annotate({\n    description:\n      \"Opens the collaborative browser for the current thread. Use preview_navigate afterward when readiness waiting matters.\",\n  });\nexport type PreviewAutomationOpenInput = typeof PreviewAutomationOpenInput.Type;\n\nexport const BrowserNavigationTarget = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"url\").annotate({\n      description: \"Selects direct URL navigation.\",\n    }),\n    url: BoundedUrl.annotate({\n      description: `Direct website URL. ${URL_GUIDANCE}`,\n    }),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"environment-port\").annotate({\n      description: \"Selects a dev-server port relative to the current execution environment.\",\n    }),\n    port: Schema.Int.check(Schema.isGreaterThan(0))\n      .check(Schema.isLessThan(65_536))\n      .annotate({ description: \"Dev-server TCP port inside the current environment.\" }),\n    protocol: Schema.optional(\n      Schema.Literals([\"http\", \"https\"]).annotate({\n        description: \"Dev-server protocol. Defaults to http.\",\n      }),\n    ),\n    path: Schema.optional(\n      Schema.String.annotate({\n        description: \"Optional path, query, and fragment, for example /settings?tab=account.\",\n      }),\n    ),\n  }),\n]);\nexport type BrowserNavigationTarget = typeof BrowserNavigationTarget.Type;\n\nexport const PreviewAutomationNavigateInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  url: Schema.optional(BoundedUrl).annotate({\n    description: `Website URL. ${URL_GUIDANCE} Use this for public pages and directly reachable URLs.`,\n  }),\n  target: Schema.optional(\n    BrowserNavigationTarget.annotate({\n      description:\n        \"Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.\",\n    }),\n  ).annotate({\n    description:\n      \"Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.\",\n  }),\n  readiness: Schema.optional(\n    Schema.Literals([\"load\", \"domContentLoaded\", \"none\"]).annotate({\n      description:\n        \"Readiness milestone before returning. 'load' waits for loading to stop (default), 'domContentLoaded' waits for an interactive document, and 'none' returns immediately.\",\n    }),\n  ).annotate({\n    description:\n      \"Readiness milestone before returning. 'load' is the default; use 'none' only when a later wait call will verify the page.\",\n  }),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter(\n      (input) =>\n        Number(input.url !== undefined) + Number(input.target !== undefined) === 1 ||\n        \"Provide exactly one of url or target.\",\n    ),\n  )\n  .annotate({\n    description:\n      \"Navigates the active browser tab. Provide exactly one of url or target; for most public pages use url.\",\n  });\nexport type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;\n\nexport const PreviewAutomationResizeInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  mode: Schema.Literals([\"fill\", \"freeform\", \"preset\"]).annotate({\n    description:\n      \"Viewport mode: fill follows the preview panel, freeform uses exact independently resizable dimensions, and preset uses a named device size.\",\n  }),\n  preset: Schema.optional(\n    PreviewViewportPresetId.annotate({\n      description: \"Named viewport from Chrome DevTools' standard device catalog.\",\n    }),\n  ).annotate({\n    description: \"Named device size. Required only when mode is preset.\",\n  }),\n  width: Schema.optional(\n    PreviewViewportSize.fields.width.annotate({\n      description: \"Freeform viewport width in CSS pixels. Required only in freeform mode.\",\n    }),\n  ).annotate({\n    description: \"Freeform viewport width in CSS pixels. Required only in freeform mode.\",\n  }),\n  height: Schema.optional(\n    PreviewViewportSize.fields.height.annotate({\n      description: \"Freeform viewport height in CSS pixels. Required only in freeform mode.\",\n    }),\n  ).annotate({\n    description: \"Freeform viewport height in CSS pixels. Required only in freeform mode.\",\n  }),\n  orientation: Schema.optional(\n    Schema.Literals([\"portrait\", \"landscape\"]).annotate({\n      description:\n        \"Orientation for a fixed device preset. Defaults to the preset's native orientation.\",\n    }),\n  ).annotate({\n    description:\n      \"Orientation for a named device preset. It is not accepted in fill or freeform mode.\",\n  }),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter((input) => {\n      const hasPreset = input.preset !== undefined;\n      const hasWidth = input.width !== undefined;\n      const hasHeight = input.height !== undefined;\n      if (hasWidth !== hasHeight) return \"Custom dimensions require both width and height.\";\n      if (input.mode === \"fill\") {\n        return !hasPreset && !hasWidth && input.orientation === undefined\n          ? true\n          : \"Fill mode does not accept a preset, dimensions, or orientation.\";\n      }\n      if (input.mode === \"freeform\") {\n        if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {\n          return \"Freeform mode requires width and height and does not accept a preset or orientation.\";\n        }\n      } else if (!hasPreset || hasWidth || hasHeight) {\n        return \"Preset mode requires a preset and does not accept custom dimensions.\";\n      }\n      if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {\n        return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;\n      }\n      return true;\n    }),\n  )\n  .annotate({\n    description:\n      \"Sets the active browser tab to fill-panel, independently resizable freeform, or named device-preset sizing.\",\n  });\nexport type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;\n\nexport const PreviewAutomationResizeResult = Schema.Struct({\n  tabId: PreviewTabId,\n  setting: PreviewViewportSetting,\n  viewport: PreviewRenderedViewportSize,\n});\nexport type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;\n\n/** Mirrors DesktopPreviewColorScheme; declared here to keep this module free of ipc.ts imports. */\nexport const PreviewAutomationColorScheme = Schema.Literals([\"system\", \"light\", \"dark\"]);\nexport type PreviewAutomationColorScheme = typeof PreviewAutomationColorScheme.Type;\n\nexport const PreviewAutomationSetColorSchemeInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  colorScheme: PreviewAutomationColorScheme.annotate({\n    description:\n      \"Emulated prefers-color-scheme for the page: light, dark, or system to follow the OS appearance.\",\n  }),\n}).annotate({\n  description:\n    \"Emulates prefers-color-scheme in the active browser tab without changing the OS or app theme.\",\n});\nexport type PreviewAutomationSetColorSchemeInput = typeof PreviewAutomationSetColorSchemeInput.Type;\n\nexport const PreviewAutomationSetColorSchemeResult = Schema.Struct({\n  tabId: PreviewTabId,\n  colorScheme: PreviewAutomationColorScheme,\n});\nexport type PreviewAutomationSetColorSchemeResult =\n  typeof PreviewAutomationSetColorSchemeResult.Type;\n\nconst Locator = TrimmedNonEmptyString.annotate({\n  description:\n    \"Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.\",\n});\n\nconst LegacySelector = TrimmedNonEmptyString.annotate({\n  description:\n    \"Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.\",\n});\n\nexport const PreviewAutomationClickInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  selector: Schema.optional(LegacySelector).annotate({\n    description:\n      \"Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description:\n      \"Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.\",\n  }),\n  x: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Viewport-relative X coordinate in CSS pixels. Must be paired with y.\",\n    }),\n  ),\n  y: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Viewport-relative Y coordinate in CSS pixels. Must be paired with x.\",\n    }),\n  ),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter((input) => {\n      const selectorModes =\n        Number(input.selector !== undefined) + Number(input.locator !== undefined);\n      const hasX = input.x !== undefined;\n      const hasY = input.y !== undefined;\n      if (hasX !== hasY) return \"Coordinates require both x and y.\";\n      const coordinateModes = hasX && hasY ? 1 : 0;\n      return selectorModes + coordinateModes === 1 || \"Provide exactly one click target.\";\n    }),\n  )\n  .annotate({\n    description:\n      \"Clicks one target. Provide exactly one of locator, selector, or the x/y coordinate pair.\",\n  });\nexport type PreviewAutomationClickInput = typeof PreviewAutomationClickInput.Type;\n\nexport const PreviewAutomationTypeInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  text: Schema.String.annotate({ description: \"Literal text to insert.\" }),\n  selector: Schema.optional(LegacySelector).annotate({\n    description: \"Legacy CSS selector for the input. Prefer locator.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description:\n      \"Playwright selector for the input, for example role=textbox[name='Message'] or textarea[placeholder*='Message'].\",\n  }),\n  clear: Schema.optional(\n    Schema.Boolean.annotate({\n      description: \"Clear the existing input value before inserting text. Defaults to false.\",\n    }),\n  ),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter(\n      (input) =>\n        !(input.selector !== undefined && input.locator !== undefined) ||\n        \"Provide at most one of selector or locator.\",\n    ),\n  )\n  .annotate({\n    description:\n      \"Types into locator/selector, or into the currently focused element when neither target is provided.\",\n  });\nexport type PreviewAutomationTypeInput = typeof PreviewAutomationTypeInput.Type;\n\nexport const PreviewAutomationPressInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  key: Schema.String.check(Schema.isTrimmed())\n    .check(\n      Schema.isNonEmpty({\n        description:\n          \"Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.\",\n      }),\n    )\n    .annotateKey({\n      description:\n        \"Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.\",\n    }),\n  modifiers: Schema.optional(\n    Schema.Array(Schema.Literals([\"Alt\", \"Control\", \"Meta\", \"Shift\"])).annotate({\n      description: \"Modifier keys held while pressing key.\",\n    }),\n  ),\n}).annotate({ description: \"Presses one keyboard key in the active browser tab.\" });\nexport type PreviewAutomationPressInput = typeof PreviewAutomationPressInput.Type;\n\nexport const PreviewAutomationScrollInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  deltaX: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Horizontal scroll delta in CSS pixels. Positive scrolls right. Defaults to 0.\",\n    }),\n  ),\n  deltaY: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Vertical scroll delta in CSS pixels. Positive scrolls down. Defaults to 0.\",\n    }),\n  ),\n  selector: Schema.optional(LegacySelector).annotate({\n    description: \"Legacy CSS selector for a scrollable container. Omit to scroll the viewport.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description: \"Playwright selector for a scrollable container. Omit to scroll the viewport.\",\n  }),\n})\n  .check(\n    Schema.makeFilter((input) => {\n      if (input.selector !== undefined && input.locator !== undefined) {\n        return \"Provide at most one of selector or locator.\";\n      }\n      return (\n        input.deltaX !== undefined || input.deltaY !== undefined || \"Provide deltaX or deltaY.\"\n      );\n    }),\n  )\n  .annotate({\n    description:\n      \"Scrolls the viewport, or a locator/selector container. Provide deltaX, deltaY, or both.\",\n  });\nexport type PreviewAutomationScrollInput = typeof PreviewAutomationScrollInput.Type;\n\nexport const PreviewAutomationEvaluateInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  expression: Schema.String.check(Schema.isTrimmed())\n    .check(\n      Schema.isNonEmpty({\n        description:\n          \"JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().\",\n      }),\n    )\n    .check(Schema.isMaxLength(64_000))\n    .annotateKey({\n      description:\n        \"JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().\",\n    }),\n  awaitPromise: Schema.optional(\n    Schema.Boolean.annotate({ description: \"Await a returned Promise. Defaults to true.\" }),\n  ),\n  returnByValue: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Serialize and return the value instead of a remote object reference. Defaults to true.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Evaluates JavaScript in the page. Prefer snapshot and semantic actions; use evaluate for inspection or unsupported interactions.\",\n});\nexport type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;\n\nexport const PreviewAutomationWaitForInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  selector: Schema.optional(LegacySelector).annotate({\n    description: \"Legacy CSS selector that must match an element. Prefer locator.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description:\n      \"Playwright selector that must match an element, for example role=button[name='Send'].\",\n  }),\n  text: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Case-sensitive substring that must appear in visible document text.\",\n    }),\n  ).annotate({\n    description: \"Case-sensitive substring that must appear in visible document text.\",\n  }),\n  urlIncludes: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Substring that must appear in the current absolute URL.\",\n    }),\n  ).annotate({ description: \"Substring that must appear in the current absolute URL.\" }),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter((input) => {\n      if (input.selector !== undefined && input.locator !== undefined) {\n        return \"Provide at most one of selector or locator.\";\n      }\n      return (\n        input.selector !== undefined ||\n        input.locator !== undefined ||\n        input.text !== undefined ||\n        input.urlIncludes !== undefined ||\n        \"Provide at least one wait condition.\"\n      );\n    }),\n  )\n  .annotate({\n    description:\n      \"Waits until all provided conditions match. Use after click/type when the page changes asynchronously.\",\n  });\nexport type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;\n\nexport const PreviewAutomationElement = Schema.Struct({\n  tag: Schema.String,\n  role: Schema.NullOr(Schema.String),\n  name: Schema.String,\n  selector: Schema.String,\n  x: Schema.Number,\n  y: Schema.Number,\n  width: Schema.Number,\n  height: Schema.Number,\n});\nexport type PreviewAutomationElement = typeof PreviewAutomationElement.Type;\n\nexport const PreviewAutomationConsoleEntry = Schema.Struct({\n  level: Schema.String,\n  text: Schema.String,\n  timestamp: Schema.String,\n  source: Schema.optional(Schema.String),\n});\nexport type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;\n\nexport const PreviewAutomationNetworkEntry = Schema.Struct({\n  url: Schema.String,\n  method: Schema.String,\n  status: Schema.NullOr(Schema.Number),\n  failed: Schema.Boolean,\n  errorText: Schema.optional(Schema.String),\n  timestamp: Schema.String,\n});\nexport type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;\n\nexport const PreviewAutomationActionEvent = Schema.Struct({\n  id: Schema.String,\n  action: Schema.String,\n  status: Schema.Literals([\"running\", \"succeeded\", \"failed\", \"interrupted\"]),\n  startedAt: Schema.String,\n  completedAt: Schema.optional(Schema.String),\n  error: Schema.optional(Schema.String),\n});\nexport type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;\n\nexport const PreviewAutomationSnapshot = Schema.Struct({\n  url: Schema.String,\n  title: Schema.String,\n  loading: Schema.Boolean,\n  visibleText: Schema.String,\n  interactiveElements: Schema.Array(PreviewAutomationElement),\n  accessibilityTree: Schema.Unknown,\n  consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),\n  networkEntries: Schema.Array(PreviewAutomationNetworkEntry),\n  actionTimeline: Schema.Array(PreviewAutomationActionEvent),\n  screenshot: Schema.Struct({\n    mimeType: Schema.Literal(\"image/png\"),\n    data: Schema.String,\n    width: Schema.Int,\n    height: Schema.Int,\n  }),\n});\nexport type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;\n\nexport const PreviewAutomationRecordingStatus = Schema.Struct({\n  tabId: PreviewTabId,\n  recording: Schema.Boolean,\n  startedAt: Schema.NullOr(Schema.String),\n});\nexport type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;\n\nexport const PreviewAutomationRecordingArtifact = Schema.Struct({\n  id: Schema.String,\n  tabId: PreviewTabId,\n  path: Schema.String,\n  mimeType: Schema.String,\n  sizeBytes: Schema.Int,\n  createdAt: Schema.String,\n});\nexport type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;\n\nexport const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));\nexport type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;\nexport const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));\nexport type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;\n\nexport const PreviewAutomationHostIdentity = Schema.Struct({\n  clientId: PreviewAutomationClientId,\n  environmentId: EnvironmentId,\n});\nexport type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;\n\nexport const PreviewAutomationHost = Schema.Struct({\n  ...PreviewAutomationHostIdentity.fields,\n  /**\n   * Missing means the pre-capability-negotiation V1 operation set. This lets\n   * a newer server safely coexist with an older desktop during rollout.\n   */\n  supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),\n});\nexport type PreviewAutomationHost = typeof PreviewAutomationHost.Type;\n\nexport const PreviewAutomationHostFocus = Schema.Struct({\n  ...PreviewAutomationHostIdentity.fields,\n  connectionId: PreviewAutomationConnectionId,\n  focused: Schema.Boolean,\n});\nexport type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;\n\nexport const PreviewAutomationRequest = Schema.Struct({\n  requestId: TrimmedNonEmptyString,\n  threadId: ThreadId,\n  tabId: Schema.optional(PreviewTabId),\n  tabIdExplicit: Schema.optional(Schema.Boolean),\n  operation: PreviewAutomationOperation,\n  input: Schema.Unknown,\n  timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),\n});\nexport type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;\n\nexport const PreviewAutomationStreamEvent = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"connected\"),\n    connectionId: PreviewAutomationConnectionId,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"request\"),\n    connectionId: PreviewAutomationConnectionId,\n    request: PreviewAutomationRequest,\n  }),\n]);\nexport type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;\n\nexport const PreviewAutomationResponse = Schema.Struct({\n  clientId: PreviewAutomationClientId,\n  connectionId: PreviewAutomationConnectionId,\n  requestId: TrimmedNonEmptyString,\n  ok: Schema.Boolean,\n  result: Schema.optional(Schema.Unknown),\n  error: Schema.optional(\n    Schema.Struct({\n      _tag: TrimmedNonEmptyString,\n      message: Schema.String,\n      detail: Schema.optional(Schema.Unknown),\n    }),\n  ),\n});\nexport type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;\n\nexport class PreviewAutomationUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationUnavailableError>()(\n  \"PreviewAutomationUnavailableError\",\n  {\n    capability: Schema.Literal(\"preview\"),\n    environmentId: EnvironmentId,\n    threadId: ThreadId,\n    providerSessionId: TrimmedNonEmptyString,\n    providerInstanceId: ProviderInstanceId,\n  },\n) {\n  override get message(): string {\n    return `MCP credential does not grant the ${this.capability} capability.`;\n  }\n}\n\nconst PreviewAutomationScopeErrorFields = {\n  operation: PreviewAutomationOperation,\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  providerSessionId: TrimmedNonEmptyString,\n  providerInstanceId: ProviderInstanceId,\n};\n\nconst PreviewAutomationRequestErrorFields = {\n  ...PreviewAutomationScopeErrorFields,\n  clientId: TrimmedNonEmptyString,\n  connectionId: PreviewAutomationConnectionId,\n  requestId: TrimmedNonEmptyString,\n  tabId: Schema.optional(PreviewTabId),\n  timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),\n};\n\nconst PreviewAutomationRemoteDiagnosticFields = {\n  remoteTag: TrimmedNonEmptyString,\n  remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n  remoteDetailKind: Schema.optional(\n    Schema.Literals([\"null\", \"array\", \"object\", \"string\", \"number\", \"boolean\"]),\n  ),\n  cause: Schema.Defect(),\n};\n\nconst PreviewAutomationOptionalRemoteDiagnosticFields = {\n  remoteTag: Schema.optional(TrimmedNonEmptyString),\n  remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n  remoteDetailKind: Schema.optional(\n    Schema.Literals([\"null\", \"array\", \"object\", \"string\", \"number\", \"boolean\"]),\n  ),\n  cause: Schema.optional(Schema.Defect()),\n};\n\nexport class PreviewAutomationNoAvailableHostError extends Schema.TaggedErrorClass<PreviewAutomationNoAvailableHostError>()(\n  \"PreviewAutomationNoAvailableHostError\",\n  {\n    ...PreviewAutomationScopeErrorFields,\n    clientId: Schema.optional(TrimmedNonEmptyString),\n    connectionId: Schema.optional(PreviewAutomationConnectionId),\n    requestId: Schema.optional(TrimmedNonEmptyString),\n    tabId: Schema.optional(PreviewTabId),\n    timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),\n    ...PreviewAutomationOptionalRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationUnsupportedClientError extends Schema.TaggedErrorClass<PreviewAutomationUnsupportedClientError>()(\n  \"PreviewAutomationUnsupportedClientError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} does not support ${this.operation}.`;\n  }\n}\n\nexport class PreviewAutomationTabNotFoundError extends Schema.TaggedErrorClass<PreviewAutomationTabNotFoundError>()(\n  \"PreviewAutomationTabNotFoundError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    const summary = this.tabId\n      ? `Preview tab ${this.tabId} was not found for ${this.operation}.`\n      : `No active preview tab was found for ${this.operation}.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationTimeoutError extends Schema.TaggedErrorClass<PreviewAutomationTimeoutError>()(\n  \"PreviewAutomationTimeoutError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationOptionalRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationControlInterruptedError extends Schema.TaggedErrorClass<PreviewAutomationControlInterruptedError>()(\n  \"PreviewAutomationControlInterruptedError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;\n  }\n}\n\nexport class PreviewAutomationExecutionError extends Schema.TaggedErrorClass<PreviewAutomationExecutionError>()(\n  \"PreviewAutomationExecutionError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation ${this.operation} failed on client ${this.clientId}.`;\n  }\n}\n\nexport class PreviewAutomationInvalidSelectorError extends Schema.TaggedErrorClass<PreviewAutomationInvalidSelectorError>()(\n  \"PreviewAutomationInvalidSelectorError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n    selectorKind: Schema.optional(Schema.Literals([\"locator\", \"selector\"])),\n    selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n  },\n) {\n  override get message(): string {\n    if (this.selectorKind !== undefined && this.selectorLength !== undefined) {\n      return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;\n    }\n    return `Preview automation ${this.operation} received an invalid selector.`;\n  }\n}\n\nexport class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(\n  \"PreviewAutomationTargetNotEditableError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n    selectorKind: Schema.optional(Schema.Literals([\"focused-element\", \"locator\", \"selector\"])),\n    selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n  },\n) {\n  override get message(): string {\n    if (this.selectorKind === \"focused-element\") {\n      return `Preview automation ${this.operation} requires an editable focused element.`;\n    }\n    if (this.selectorKind !== undefined && this.selectorLength !== undefined) {\n      return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;\n    }\n    return `Preview automation ${this.operation} requires an editable target.`;\n  }\n}\n\nexport class PreviewAutomationResultTooLargeError extends Schema.TaggedErrorClass<PreviewAutomationResultTooLargeError>()(\n  \"PreviewAutomationResultTooLargeError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n    maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),\n  },\n) {\n  override get message(): string {\n    const summary =\n      this.maximumBytes === undefined\n        ? `Preview automation ${this.operation} produced a result that is too large.`\n        : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationClientDisconnectedError extends Schema.TaggedErrorClass<PreviewAutomationClientDisconnectedError>()(\n  \"PreviewAutomationClientDisconnectedError\",\n  PreviewAutomationRequestErrorFields,\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;\n  }\n}\n\nexport class PreviewAutomationRequestQueueClosedError extends Schema.TaggedErrorClass<PreviewAutomationRequestQueueClosedError>()(\n  \"PreviewAutomationRequestQueueClosedError\",\n  PreviewAutomationRequestErrorFields,\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;\n  }\n}\n\nexport class PreviewAutomationRemoteUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationRemoteUnavailableError>()(\n  \"PreviewAutomationRemoteUnavailableError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;\n  }\n}\n\nexport class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorClass<PreviewAutomationMalformedResponseError>()(\n  \"PreviewAutomationMalformedResponseError\",\n  PreviewAutomationRequestErrorFields,\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;\n  }\n}\n\nexport const PreviewAutomationError = Schema.Union([\n  PreviewAutomationUnavailableError,\n  PreviewAutomationNoAvailableHostError,\n  PreviewAutomationUnsupportedClientError,\n  PreviewAutomationTabNotFoundError,\n  PreviewAutomationTimeoutError,\n  PreviewAutomationControlInterruptedError,\n  PreviewAutomationExecutionError,\n  PreviewAutomationInvalidSelectorError,\n  PreviewAutomationTargetNotEditableError,\n  PreviewAutomationResultTooLargeError,\n  PreviewAutomationClientDisconnectedError,\n  PreviewAutomationRequestQueueClosedError,\n  PreviewAutomationRemoteUnavailableError,\n  PreviewAutomationMalformedResponseError,\n]);\nexport type PreviewAutomationError = typeof PreviewAutomationError.Type;\n\nexport const PreviewUrlResolution = Schema.Struct({\n  requestedUrl: Schema.String,\n  resolvedUrl: Schema.String,\n  resolutionKind: Schema.Literals([\"direct\", \"direct-private-network\"]),\n  environmentId: EnvironmentId,\n});\nexport type PreviewUrlResolution = typeof PreviewUrlResolution.Type;\n","import type {\n  VcsCreateRefInput,\n  VcsCreateRefResult,\n  VcsCreateWorktreeInput,\n  VcsCreateWorktreeResult,\n  VcsInitInput,\n  VcsListRefsInput,\n  VcsListRefsResult,\n  VcsPullInput,\n  VcsPullResult,\n  VcsRemoveWorktreeInput,\n  VcsSwitchRefInput,\n  VcsSwitchRefResult,\n  GitPreparePullRequestThreadInput,\n  GitPreparePullRequestThreadResult,\n  GitPullRequestRefInput,\n  GitResolvePullRequestResult,\n  VcsStatusInput,\n  VcsStatusResult,\n} from \"./git.ts\";\nimport type {\n  ReviewDiffFileContentsInput,\n  ReviewDiffFileContentsResult,\n  ReviewDiffPreviewInput,\n  ReviewDiffPreviewResult,\n} from \"./review.ts\";\nimport type { FilesystemBrowseInput, FilesystemBrowseResult } from \"./filesystem.ts\";\nimport type { AssetCreateUrlInput, AssetCreateUrlResult } from \"./assets.ts\";\nimport type {\n  ProjectListEntriesInput,\n  ProjectListEntriesResult,\n  ProjectReadFileInput,\n  ProjectReadFileResult,\n  ProjectSearchEntriesInput,\n  ProjectSearchEntriesResult,\n  ProjectWriteFileInput,\n  ProjectWriteFileResult,\n} from \"./project.ts\";\nimport type {\n  TerminalAttachInput,\n  TerminalAttachStreamEvent,\n  TerminalClearInput,\n  TerminalCloseInput,\n  TerminalMetadataStreamEvent,\n  TerminalOpenInput,\n  TerminalResizeInput,\n  TerminalRestartInput,\n  TerminalSessionSnapshot,\n  TerminalWriteInput,\n} from \"./terminal.ts\";\nimport * as Schema from \"effect/Schema\";\nimport type {\n  DiscoveredLocalServerList,\n  PreviewCloseInput,\n  PreviewEvent,\n  PreviewListInput,\n  PreviewListResult,\n  PreviewNavigateInput,\n  PreviewOpenInput,\n  PreviewRefreshInput,\n  PreviewReportStatusInput,\n  PreviewResizeInput,\n  PreviewSessionSnapshot,\n} from \"./preview.ts\";\nimport {\n  PreviewAutomationClickInput,\n  PreviewAutomationEvaluateInput,\n  PreviewAutomationHost,\n  PreviewAutomationHostFocus,\n  PreviewAutomationPressInput,\n  PreviewAutomationResponse,\n  PreviewAutomationScrollInput,\n  PreviewAutomationSnapshot,\n  PreviewAutomationStatus,\n  PreviewAutomationStreamEvent,\n  PreviewAutomationTypeInput,\n  PreviewAutomationWaitForInput,\n} from \"./previewAutomation.ts\";\nimport type {\n  ClientOrchestrationCommand,\n  OrchestrationGetFullThreadDiffInput,\n  OrchestrationGetFullThreadDiffResult,\n  OrchestrationGetTurnDiffInput,\n  OrchestrationGetTurnDiffResult,\n  OrchestrationShellSnapshot,\n  OrchestrationShellStreamItem,\n  OrchestrationSubscribeThreadInput,\n  OrchestrationThreadStreamItem,\n} from \"./orchestration.ts\";\nimport { EnvironmentId } from \"./baseSchemas.ts\";\nimport { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } from \"./auth.ts\";\nimport { AdvertisedEndpoint } from \"./remoteAccess.ts\";\nimport { ExecutionEnvironmentDescriptor } from \"./environment.ts\";\nimport type { ClientSettings } from \"./settings.ts\";\nimport type {\n  SourceControlCloneRepositoryInput,\n  SourceControlCloneRepositoryResult,\n  SourceControlPublishRepositoryInput,\n  SourceControlPublishRepositoryResult,\n  SourceControlRepositoryInfo,\n  SourceControlRepositoryLookupInput,\n} from \"./sourceControl.ts\";\n\nexport interface ContextMenuItem<T extends string = string> {\n  id: T;\n  label: string;\n  destructive?: boolean;\n  disabled?: boolean;\n  /** Renders as a non-interactive section header label. Web fallback only — stripped on desktop native menus. */\n  header?: boolean;\n  /** Icon keyword resolved by the web fallback. Stripped on desktop native menus. */\n  icon?: string;\n  children?: readonly ContextMenuItem<T>[];\n}\n\nexport interface ContextMenuItemSchemaType {\n  readonly id: string;\n  readonly label: string;\n  readonly destructive?: boolean;\n  readonly disabled?: boolean;\n  readonly header?: boolean;\n  readonly icon?: string;\n  readonly children?: readonly ContextMenuItemSchemaType[];\n}\n\nexport const ContextMenuItemSchema: Schema.Codec<ContextMenuItemSchemaType> = Schema.Struct({\n  id: Schema.String,\n  label: Schema.String,\n  destructive: Schema.optionalKey(Schema.Boolean),\n  disabled: Schema.optionalKey(Schema.Boolean),\n  header: Schema.optionalKey(Schema.Boolean),\n  icon: Schema.optionalKey(Schema.String),\n  children: Schema.optionalKey(\n    Schema.Array(\n      Schema.suspend((): Schema.Codec<ContextMenuItemSchemaType> => ContextMenuItemSchema),\n    ),\n  ),\n});\n\nexport type DesktopUpdateStatus =\n  | \"disabled\"\n  | \"idle\"\n  | \"checking\"\n  | \"up-to-date\"\n  | \"available\"\n  | \"downloading\"\n  | \"downloaded\"\n  | \"error\";\n\nexport type DesktopRuntimeArch = \"arm64\" | \"x64\" | \"other\";\nexport type DesktopTheme = \"light\" | \"dark\" | \"system\";\nexport type DesktopUpdateChannel = \"latest\" | \"nightly\";\nexport type DesktopAppStageLabel = \"Alpha\" | \"Dev\" | \"Nightly\";\n\nexport const DesktopUpdateStatusSchema = Schema.Literals([\n  \"disabled\",\n  \"idle\",\n  \"checking\",\n  \"up-to-date\",\n  \"available\",\n  \"downloading\",\n  \"downloaded\",\n  \"error\",\n]);\nexport const DesktopRuntimeArchSchema = Schema.Literals([\"arm64\", \"x64\", \"other\"]);\nexport const DesktopThemeSchema = Schema.Literals([\"light\", \"dark\", \"system\"]);\nexport const DesktopUpdateChannelSchema = Schema.Literals([\"latest\", \"nightly\"]);\nexport const DesktopAppStageLabelSchema = Schema.Literals([\"Alpha\", \"Dev\", \"Nightly\"]);\n\nexport interface DesktopAppBranding {\n  baseName: string;\n  stageLabel: DesktopAppStageLabel;\n  displayName: string;\n}\n\nexport const DesktopAppBrandingSchema = Schema.Struct({\n  baseName: Schema.String,\n  stageLabel: DesktopAppStageLabelSchema,\n  displayName: Schema.String,\n});\n\nexport interface DesktopRuntimeInfo {\n  hostArch: DesktopRuntimeArch;\n  appArch: DesktopRuntimeArch;\n  runningUnderArm64Translation: boolean;\n}\n\nexport const DesktopRuntimeInfoSchema = Schema.Struct({\n  hostArch: DesktopRuntimeArchSchema,\n  appArch: DesktopRuntimeArchSchema,\n  runningUnderArm64Translation: Schema.Boolean,\n});\n\nexport interface DesktopUpdateState {\n  enabled: boolean;\n  status: DesktopUpdateStatus;\n  channel: DesktopUpdateChannel;\n  currentVersion: string;\n  hostArch: DesktopRuntimeArch;\n  appArch: DesktopRuntimeArch;\n  runningUnderArm64Translation: boolean;\n  availableVersion: string | null;\n  downloadedVersion: string | null;\n  releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote>;\n  downloadPercent: number | null;\n  checkedAt: string | null;\n  message: string | null;\n  errorContext: \"check\" | \"download\" | \"install\" | null;\n  canRetry: boolean;\n}\n\nexport interface DesktopUpdateReleaseNote {\n  version: string;\n  items: ReadonlyArray<string>;\n}\n\nexport const DesktopUpdateReleaseNoteSchema = Schema.Struct({\n  version: Schema.String,\n  items: Schema.Array(Schema.String),\n});\n\nexport const DesktopUpdateStateSchema = Schema.Struct({\n  enabled: Schema.Boolean,\n  status: DesktopUpdateStatusSchema,\n  channel: DesktopUpdateChannelSchema,\n  currentVersion: Schema.String,\n  hostArch: DesktopRuntimeArchSchema,\n  appArch: DesktopRuntimeArchSchema,\n  runningUnderArm64Translation: Schema.Boolean,\n  availableVersion: Schema.NullOr(Schema.String),\n  downloadedVersion: Schema.NullOr(Schema.String),\n  releaseNotes: Schema.Array(DesktopUpdateReleaseNoteSchema),\n  downloadPercent: Schema.NullOr(Schema.Number),\n  checkedAt: Schema.NullOr(Schema.String),\n  message: Schema.NullOr(Schema.String),\n  errorContext: Schema.NullOr(Schema.Literals([\"check\", \"download\", \"install\"])),\n  canRetry: Schema.Boolean,\n});\n\nexport interface DesktopUpdateActionResult {\n  accepted: boolean;\n  completed: boolean;\n  state: DesktopUpdateState;\n}\n\nexport const DesktopUpdateActionResultSchema = Schema.Struct({\n  accepted: Schema.Boolean,\n  completed: Schema.Boolean,\n  state: DesktopUpdateStateSchema,\n});\n\nexport interface DesktopUpdateCheckResult {\n  checked: boolean;\n  state: DesktopUpdateState;\n}\n\nexport const DesktopUpdateCheckResultSchema = Schema.Struct({\n  checked: Schema.Boolean,\n  state: DesktopUpdateStateSchema,\n});\n\n// Stable id for the Windows-native primary backend. Desktop side wraps\n// this with a brand inside DesktopBackendManager; web side keeps it as\n// a plain string so the env-runtime can compare against it without\n// importing brand machinery from the desktop package.\nexport const PRIMARY_LOCAL_ENVIRONMENT_ID = \"primary\";\n\nexport interface DesktopEnvironmentBootstrap {\n  // Stable backend instance id (e.g. \"primary\" or \"wsl:ubuntu\"). The\n  // web env runtime keys local environments off this so projects\n  // routed to a specific backend reopen against the same one.\n  id: string;\n  label: string;\n  // Concrete WSL distro used by the current backend run. This stays separate\n  // from id because a default-tracking instance keeps the stable\n  // \"wsl:default\" IPC target while each run launches a specific distro.\n  runningDistro?: string | null;\n  httpBaseUrl: string | null;\n  wsBaseUrl: string | null;\n  bootstrapToken?: string;\n}\n\nexport const DesktopEnvironmentBootstrapSchema = Schema.Struct({\n  id: Schema.String,\n  label: Schema.String,\n  runningDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),\n  httpBaseUrl: Schema.NullOr(Schema.String),\n  wsBaseUrl: Schema.NullOr(Schema.String),\n  bootstrapToken: Schema.optionalKey(Schema.String),\n});\n\nexport const DesktopSshEnvironmentTargetSchema = Schema.Struct({\n  alias: Schema.String,\n  hostname: Schema.String,\n  username: Schema.NullOr(Schema.String),\n  port: Schema.NullOr(Schema.Number),\n});\nexport type DesktopSshEnvironmentTarget = typeof DesktopSshEnvironmentTargetSchema.Type;\n\nexport type DesktopSshHostSource = \"ssh-config\" | \"known-hosts\";\nexport const DesktopSshHostSourceSchema = Schema.Literals([\"ssh-config\", \"known-hosts\"]);\n\nexport interface DesktopDiscoveredSshHost extends DesktopSshEnvironmentTarget {\n  source: DesktopSshHostSource;\n}\n\nexport const DesktopDiscoveredSshHostSchema = Schema.Struct({\n  alias: Schema.String,\n  hostname: Schema.String,\n  username: Schema.NullOr(Schema.String),\n  port: Schema.NullOr(Schema.Number),\n  source: DesktopSshHostSourceSchema,\n});\n\nexport interface DesktopSshEnvironmentBootstrap {\n  target: DesktopSshEnvironmentTarget;\n  httpBaseUrl: string;\n  wsBaseUrl: string;\n  pairingToken: string | null;\n  remotePort?: number;\n  remoteServerKind?: \"external\" | \"managed\";\n}\n\nexport const DesktopSshEnvironmentBootstrapSchema = Schema.Struct({\n  target: DesktopSshEnvironmentTargetSchema,\n  httpBaseUrl: Schema.String,\n  wsBaseUrl: Schema.String,\n  pairingToken: Schema.NullOr(Schema.String),\n  remotePort: Schema.optionalKey(Schema.Number),\n  remoteServerKind: Schema.optionalKey(Schema.Literals([\"external\", \"managed\"])),\n});\n\nexport interface DesktopSshPasswordPromptRequest {\n  requestId: string;\n  destination: string;\n  username: string | null;\n  prompt: string;\n  expiresAt: string;\n}\n\nexport const DesktopSshPasswordPromptRequestSchema = Schema.Struct({\n  requestId: Schema.String,\n  destination: Schema.String,\n  username: Schema.NullOr(Schema.String),\n  prompt: Schema.String,\n  expiresAt: Schema.String,\n});\n\nexport const DesktopSshPasswordPromptCancelledType = \"ssh-password-prompt-cancelled\" as const;\n\nexport const DesktopSshPasswordPromptCancelledResultSchema = Schema.Struct({\n  type: Schema.Literal(DesktopSshPasswordPromptCancelledType),\n  message: Schema.String,\n});\n\nexport const DesktopSshEnvironmentEnsureOptionsSchema = Schema.Struct({\n  issuePairingToken: Schema.optionalKey(Schema.Boolean),\n});\n\nexport const DesktopSshEnvironmentEnsureInputSchema = Schema.Struct({\n  target: DesktopSshEnvironmentTargetSchema,\n  options: Schema.optionalKey(DesktopSshEnvironmentEnsureOptionsSchema),\n});\n\nexport const DesktopSshEnvironmentEnsureResultSchema = Schema.Union([\n  DesktopSshEnvironmentBootstrapSchema,\n  DesktopSshPasswordPromptCancelledResultSchema,\n]);\n\nexport const DesktopSshHttpBaseUrlInputSchema = Schema.Struct({\n  httpBaseUrl: Schema.String,\n});\n\nexport const DesktopSshBearerRequestInputSchema = Schema.Struct({\n  httpBaseUrl: Schema.String,\n  bearerToken: Schema.String,\n});\n\nexport const DesktopSshBearerBootstrapInputSchema = Schema.Struct({\n  httpBaseUrl: Schema.String,\n  credential: Schema.String,\n});\n\nexport const DesktopSshPasswordPromptResolutionInputSchema = Schema.Struct({\n  requestId: Schema.String,\n  password: Schema.NullOr(Schema.String),\n});\n\nexport const PersistedSavedEnvironmentRecordSchema = Schema.Struct({\n  environmentId: EnvironmentId,\n  label: Schema.String,\n  wsBaseUrl: Schema.String,\n  httpBaseUrl: Schema.String,\n  createdAt: Schema.String,\n  lastConnectedAt: Schema.NullOr(Schema.String),\n  desktopSsh: Schema.optionalKey(DesktopSshEnvironmentTargetSchema),\n  relayManaged: Schema.optionalKey(\n    Schema.Struct({\n      relayUrl: Schema.String,\n    }),\n  ),\n});\nexport type PersistedSavedEnvironmentRecord = typeof PersistedSavedEnvironmentRecordSchema.Type;\n\nexport type DesktopServerExposureMode = \"local-only\" | \"network-accessible\";\n\nexport const DesktopServerExposureModeSchema = Schema.Literals([\n  \"local-only\",\n  \"network-accessible\",\n]);\n\nexport interface DesktopServerExposureState {\n  mode: DesktopServerExposureMode;\n  endpointUrl: string | null;\n  advertisedHost: string | null;\n  tailscaleServeEnabled: boolean;\n  tailscaleServePort: number;\n}\n\nexport const DesktopServerExposureStateSchema = Schema.Struct({\n  mode: DesktopServerExposureModeSchema,\n  endpointUrl: Schema.NullOr(Schema.String),\n  advertisedHost: Schema.NullOr(Schema.String),\n  tailscaleServeEnabled: Schema.Boolean,\n  tailscaleServePort: Schema.Number,\n});\n\nexport interface PickFolderOptions {\n  initialPath?: string | null;\n  // When set, the desktop dialog opens against the named backend's\n  // filesystem instead of the primary's. Used by callers that already\n  // know which local environment they're targeting (e.g. opening a\n  // project that lives inside WSL). Omitting it keeps the historical\n  // behavior so non-WSL users never see a different picker.\n  targetEnvironmentId?: string;\n}\n\nexport const PickFolderOptionsSchema = Schema.Struct({\n  initialPath: Schema.optionalKey(Schema.NullOr(Schema.String)),\n  targetEnvironmentId: Schema.optionalKey(Schema.String),\n});\n\nexport interface DesktopWslDistro {\n  name: string;\n  isDefault: boolean;\n  version: 1 | 2;\n}\n\nexport const DesktopWslDistroSchema = Schema.Struct({\n  name: Schema.String,\n  isDefault: Schema.Boolean,\n  version: Schema.Literals([1, 2]),\n});\n\nexport interface DesktopWslState {\n  // True when the user has opted the WSL backend in; the actual backend\n  // process is registered with the desktop pool independently of this\n  // flag and may take a moment to come up after the user enables it.\n  enabled: boolean;\n  // null means \"track the current WSL default distro\".\n  distro: string | null;\n  available: boolean;\n  // When true (and `enabled` is also true) the desktop runs only the\n  // WSL backend as the primary; the Windows-side Node backend is not\n  // started. Toggling this requires an app restart because the\n  // primary backend's spec is captured once at layer init.\n  wslOnly: boolean;\n  distros: readonly DesktopWslDistro[];\n  // Reason the dual-mode WSL backend last failed preflight (no node, wrong\n  // version, missing build tools), or null. Surfaced inline in Connections\n  // settings. Always null in wsl-only mode — that path shows a dialog and\n  // falls back to Windows instead.\n  preflightError: string | null;\n}\n\nexport const DesktopWslStateSchema = Schema.Struct({\n  enabled: Schema.Boolean,\n  distro: Schema.NullOr(Schema.String),\n  available: Schema.Boolean,\n  wslOnly: Schema.Boolean,\n  distros: Schema.Array(DesktopWslDistroSchema),\n  preflightError: Schema.NullOr(Schema.String),\n});\n\n/**\n * Renderer-facing snapshot of a desktop preview tab. Mirrors the main-process\n * PreviewTabState shape but uses serialisable primitives only.\n */\nexport type DesktopPreviewNavStatus =\n  | { kind: \"Idle\" }\n  | { kind: \"Loading\"; url: string; title: string }\n  | { kind: \"Success\"; url: string; title: string }\n  | {\n      kind: \"LoadFailed\";\n      url: string;\n      title: string;\n      code: number;\n      description: string;\n    };\n\n/**\n * Emulated `prefers-color-scheme` for the guest page. \"system\" clears the\n * override so the page follows the OS appearance.\n */\nexport type DesktopPreviewColorScheme = \"system\" | \"light\" | \"dark\";\n\nexport const DesktopPreviewColorSchemeSchema: Schema.Codec<DesktopPreviewColorScheme> =\n  Schema.Literals([\"system\", \"light\", \"dark\"]);\n\nexport interface DesktopPreviewTabState {\n  tabId: string;\n  webContentsId: number | null;\n  navStatus: DesktopPreviewNavStatus;\n  canGoBack: boolean;\n  canGoForward: boolean;\n  /** Current zoom factor (1.0 = 100%). */\n  zoomFactor: number;\n  /** Whether this tab is currently mirrored into a desktop picture-in-picture window. */\n  pictureInPicture: boolean;\n  colorScheme: DesktopPreviewColorScheme;\n  controller: \"human\" | \"agent\" | \"none\";\n  updatedAt: string;\n}\n\nexport const DesktopPreviewTabIdSchema = Schema.String.check(Schema.isTrimmed()).check(\n  Schema.isNonEmpty(),\n);\n\nexport const DesktopPreviewNavStatusSchema = Schema.Union([\n  Schema.Struct({ kind: Schema.Literal(\"Idle\") }),\n  Schema.Struct({\n    kind: Schema.Literal(\"Loading\"),\n    url: Schema.String,\n    title: Schema.String,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"Success\"),\n    url: Schema.String,\n    title: Schema.String,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"LoadFailed\"),\n    url: Schema.String,\n    title: Schema.String,\n    code: Schema.Number,\n    description: Schema.String,\n  }),\n]);\n\nexport const DesktopPreviewTabStateSchema: Schema.Codec<DesktopPreviewTabState> = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  webContentsId: Schema.NullOr(Schema.Int),\n  navStatus: DesktopPreviewNavStatusSchema,\n  canGoBack: Schema.Boolean,\n  canGoForward: Schema.Boolean,\n  zoomFactor: Schema.Number,\n  pictureInPicture: Schema.Boolean,\n  colorScheme: DesktopPreviewColorSchemeSchema,\n  controller: Schema.Literals([\"human\", \"agent\", \"none\"]),\n  updatedAt: Schema.String,\n});\n\nexport interface DesktopPreviewPointerEvent {\n  tabId: string;\n  phase: \"move\" | \"click\";\n  x: number;\n  y: number;\n  sequence: number;\n  createdAt: string;\n}\n\nexport const DesktopPreviewPointerEventSchema: Schema.Codec<DesktopPreviewPointerEvent> =\n  Schema.Struct({\n    tabId: DesktopPreviewTabIdSchema,\n    phase: Schema.Literals([\"move\", \"click\"]),\n    x: Schema.Number,\n    y: Schema.Number,\n    sequence: Schema.Int,\n    createdAt: Schema.String,\n  });\n\n/**\n * Static config a renderer needs to mount a preview `<webview>`. Returned\n * atomically by `DesktopPreviewBridge.getPreviewConfig()` so the renderer\n * doesn't have to wait on three separate IPC round-trips before the webview\n * can attach.\n */\nexport interface DesktopPreviewWebviewConfig {\n  /** `persist:t3code-preview` (or whatever the desktop chose). */\n  partition: string;\n  /**\n   * Canonical `<webview webpreferences=\"...\">` string. Encodes the security\n   * posture (sandboxed but contextIsolation off so the picker preload can\n   * read the page's React DevTools hook). Always present.\n   */\n  webPreferences: string;\n  /**\n   * Absolute `file://`-style URL to the picker preload bundle. Set to null\n   * when the bundle isn't present (older builds, broken install) — the\n   * renderer must then disable element-pick affordances.\n   */\n  preloadUrl: string | null;\n}\n\nexport const DesktopPreviewWebviewConfigSchema: Schema.Codec<DesktopPreviewWebviewConfig> =\n  Schema.Struct({\n    partition: Schema.String,\n    webPreferences: Schema.String,\n    preloadUrl: Schema.NullOr(Schema.String),\n  });\n\nexport interface DesktopPreviewAnnotationTheme {\n  colorScheme: \"light\" | \"dark\";\n  radius: string;\n  background: string;\n  foreground: string;\n  popover: string;\n  popoverForeground: string;\n  primary: string;\n  primaryForeground: string;\n  muted: string;\n  mutedForeground: string;\n  accent: string;\n  accentForeground: string;\n  border: string;\n  input: string;\n  ring: string;\n  fontSans: string;\n  fontMono: string;\n}\n\nexport const DesktopPreviewAnnotationThemeSchema: Schema.Codec<DesktopPreviewAnnotationTheme> =\n  Schema.Struct({\n    colorScheme: Schema.Literals([\"light\", \"dark\"]),\n    radius: Schema.String,\n    background: Schema.String,\n    foreground: Schema.String,\n    popover: Schema.String,\n    popoverForeground: Schema.String,\n    primary: Schema.String,\n    primaryForeground: Schema.String,\n    muted: Schema.String,\n    mutedForeground: Schema.String,\n    accent: Schema.String,\n    accentForeground: Schema.String,\n    border: Schema.String,\n    input: Schema.String,\n    ring: Schema.String,\n    fontSans: Schema.String,\n    fontMono: Schema.String,\n  });\n\nexport interface DesktopPreviewRecordingFrame {\n  tabId: string;\n  data: string;\n  width: number;\n  height: number;\n  receivedAt: string;\n}\n\nexport const DesktopPreviewRecordingFrameSchema: Schema.Codec<DesktopPreviewRecordingFrame> =\n  Schema.Struct({\n    tabId: DesktopPreviewTabIdSchema,\n    data: Schema.String,\n    width: Schema.Number,\n    height: Schema.Number,\n    receivedAt: Schema.String,\n  });\n\nexport interface DesktopPreviewRecordingArtifact {\n  id: string;\n  tabId: string;\n  path: string;\n  mimeType: string;\n  sizeBytes: number;\n  createdAt: string;\n}\n\nexport const DesktopPreviewRecordingArtifactSchema: Schema.Codec<DesktopPreviewRecordingArtifact> =\n  Schema.Struct({\n    id: Schema.String,\n    tabId: DesktopPreviewTabIdSchema,\n    path: Schema.String,\n    mimeType: Schema.String,\n    sizeBytes: Schema.Int,\n    createdAt: Schema.String,\n  });\n\nexport interface DesktopPreviewScreenshotArtifact {\n  id: string;\n  tabId: string;\n  path: string;\n  mimeType: \"image/png\";\n  sizeBytes: number;\n  createdAt: string;\n}\n\nexport const DesktopPreviewScreenshotArtifactSchema: Schema.Codec<DesktopPreviewScreenshotArtifact> =\n  Schema.Struct({\n    id: Schema.String,\n    tabId: DesktopPreviewTabIdSchema,\n    path: Schema.String,\n    mimeType: Schema.Literal(\"image/png\"),\n    sizeBytes: Schema.Int,\n    createdAt: Schema.String,\n  });\n\n/**\n * Single stack frame captured by react-grab's `getElementContext`. We surface\n * the source file/line so coding agents can jump straight to the JSX that\n * produced the picked DOM node.\n */\nexport interface PickedElementStackFrame {\n  functionName: string | null;\n  fileName: string | null;\n  lineNumber: number | null;\n  columnNumber: number | null;\n}\n\nexport const PickedElementStackFrameSchema: Schema.Codec<PickedElementStackFrame> = Schema.Struct({\n  functionName: Schema.NullOr(Schema.String),\n  fileName: Schema.NullOr(Schema.String),\n  lineNumber: Schema.NullOr(Schema.Number),\n  columnNumber: Schema.NullOr(Schema.Number),\n});\n\n/**\n * A successful element pick from the preview webview. All fields are\n * best-effort — pages that don't ship a React fiber tree (or aren't running\n * in dev) will still produce a usable payload (selector + html preview),\n * just without component / source attribution.\n */\nexport interface PickedElementPayload {\n  /** URL of the page the element was picked on. */\n  pageUrl: string;\n  /** Optional `<title>` of that page (best-effort). */\n  pageTitle: string | null;\n  /** Lowercase tag name, e.g. `\"button\"`. */\n  tagName: string;\n  /** CSS selector resolving back to the element on a re-render. */\n  selector: string | null;\n  /** Truncated outer-HTML preview (matches react-grab's `htmlPreview`). */\n  htmlPreview: string;\n  /** Nearest React component display name, or null when unavailable. */\n  componentName: string | null;\n  /** First source-mapped stack frame (file + line of the JSX source). */\n  source: PickedElementStackFrame | null;\n  /** Full owner-stack frames; can be empty. Useful for richer context. */\n  stack: ReadonlyArray<PickedElementStackFrame>;\n  /** Author CSS only (UA defaults stripped) — react-grab's `styles`. */\n  styles: string;\n  /** Wall-clock pick time as ISO-8601 string. */\n  pickedAt: string;\n}\n\nexport const PickedElementPayloadSchema: Schema.Codec<PickedElementPayload> = Schema.Struct({\n  pageUrl: Schema.String,\n  pageTitle: Schema.NullOr(Schema.String),\n  tagName: Schema.String,\n  selector: Schema.NullOr(Schema.String),\n  htmlPreview: Schema.String,\n  componentName: Schema.NullOr(Schema.String),\n  source: Schema.NullOr(PickedElementStackFrameSchema),\n  stack: Schema.Array(PickedElementStackFrameSchema),\n  styles: Schema.String,\n  pickedAt: Schema.String,\n});\n\nexport interface PreviewAnnotationRect {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\nexport const PreviewAnnotationRectSchema: Schema.Codec<PreviewAnnotationRect> = Schema.Struct({\n  x: Schema.Number,\n  y: Schema.Number,\n  width: Schema.Number,\n  height: Schema.Number,\n});\n\nexport interface PreviewAnnotationPoint {\n  x: number;\n  y: number;\n}\n\nexport const PreviewAnnotationPointSchema: Schema.Codec<PreviewAnnotationPoint> = Schema.Struct({\n  x: Schema.Number,\n  y: Schema.Number,\n});\n\nexport interface PreviewAnnotationElementTarget {\n  id: string;\n  element: PickedElementPayload;\n  rect: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationElementTargetSchema: Schema.Codec<PreviewAnnotationElementTarget> =\n  Schema.Struct({\n    id: Schema.String,\n    element: PickedElementPayloadSchema,\n    rect: PreviewAnnotationRectSchema,\n  });\n\nexport interface PreviewAnnotationRegionTarget {\n  id: string;\n  rect: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationRegionTargetSchema: Schema.Codec<PreviewAnnotationRegionTarget> =\n  Schema.Struct({\n    id: Schema.String,\n    rect: PreviewAnnotationRectSchema,\n  });\n\nexport interface PreviewAnnotationStrokeTarget {\n  id: string;\n  color: string;\n  width: number;\n  points: ReadonlyArray<PreviewAnnotationPoint>;\n  bounds: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationStrokeTargetSchema: Schema.Codec<PreviewAnnotationStrokeTarget> =\n  Schema.Struct({\n    id: Schema.String,\n    color: Schema.String,\n    width: Schema.Number,\n    points: Schema.Array(PreviewAnnotationPointSchema),\n    bounds: PreviewAnnotationRectSchema,\n  });\n\nexport interface PreviewAnnotationStyleChange {\n  targetId: string;\n  selector: string | null;\n  property: string;\n  previousValue: string;\n  value: string;\n}\n\nexport const PreviewAnnotationStyleChangeSchema: Schema.Codec<PreviewAnnotationStyleChange> =\n  Schema.Struct({\n    targetId: Schema.String,\n    selector: Schema.NullOr(Schema.String),\n    property: Schema.String,\n    previousValue: Schema.String,\n    value: Schema.String,\n  });\n\nexport interface PreviewAnnotationScreenshot {\n  dataUrl: string;\n  width: number;\n  height: number;\n  cropRect: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationScreenshotSchema: Schema.Codec<PreviewAnnotationScreenshot> =\n  Schema.Struct({\n    dataUrl: Schema.String,\n    width: Schema.Number,\n    height: Schema.Number,\n    cropRect: PreviewAnnotationRectSchema,\n  });\n\n/**\n * A submitted preview annotation. One annotation may reference multiple DOM\n * elements, freeform regions, and ink strokes. The desktop main process adds\n * the screenshot after the guest preload submits the structured draft.\n */\nexport interface PreviewAnnotationPayload {\n  id: string;\n  pageUrl: string;\n  pageTitle: string | null;\n  comment: string;\n  elements: ReadonlyArray<PreviewAnnotationElementTarget>;\n  regions: ReadonlyArray<PreviewAnnotationRegionTarget>;\n  strokes: ReadonlyArray<PreviewAnnotationStrokeTarget>;\n  styleChanges: ReadonlyArray<PreviewAnnotationStyleChange>;\n  screenshot: PreviewAnnotationScreenshot | null;\n  createdAt: string;\n}\n\nexport const PreviewAnnotationPayloadSchema: Schema.Codec<PreviewAnnotationPayload> = Schema.Struct(\n  {\n    id: Schema.String,\n    pageUrl: Schema.String,\n    pageTitle: Schema.NullOr(Schema.String),\n    comment: Schema.String,\n    elements: Schema.Array(PreviewAnnotationElementTargetSchema),\n    regions: Schema.Array(PreviewAnnotationRegionTargetSchema),\n    strokes: Schema.Array(PreviewAnnotationStrokeTargetSchema),\n    styleChanges: Schema.Array(PreviewAnnotationStyleChangeSchema),\n    screenshot: Schema.NullOr(PreviewAnnotationScreenshotSchema),\n    createdAt: Schema.String,\n  },\n);\n\nexport type PreviewAnnotationSubmission = \"attach\" | \"send\";\nexport const PreviewAnnotationSubmissionSchema: Schema.Codec<PreviewAnnotationSubmission> =\n  Schema.Literals([\"attach\", \"send\"]);\n\nexport interface PreviewAnnotationSubmissionResult {\n  annotation: PreviewAnnotationPayload;\n  submission: PreviewAnnotationSubmission;\n}\nexport const PreviewAnnotationSubmissionResultSchema: Schema.Codec<PreviewAnnotationSubmissionResult> =\n  Schema.Struct({\n    annotation: PreviewAnnotationPayloadSchema,\n    submission: PreviewAnnotationSubmissionSchema,\n  });\n\nexport const DesktopPreviewTabInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n});\n\nexport const DesktopPreviewRegisterWebviewInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  webContentsId: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport const DesktopPreviewNavigateInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  url: Schema.String,\n});\n\nexport const DesktopPreviewConfigInputSchema = Schema.Struct({\n  environmentId: EnvironmentId,\n});\n\nexport const DesktopPreviewSetColorSchemeInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  colorScheme: DesktopPreviewColorSchemeSchema,\n});\n\nexport const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({\n  theme: DesktopPreviewAnnotationThemeSchema,\n});\n\nexport const DesktopPreviewArtifactInputSchema = Schema.Struct({\n  path: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),\n});\n\nexport const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  mimeType: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),\n  data: Schema.Uint8Array,\n});\n\nexport const DesktopPreviewAutomationClickInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationClickInput,\n});\n\nexport const DesktopPreviewAutomationTypeInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationTypeInput,\n});\n\nexport const DesktopPreviewAutomationPressInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationPressInput,\n});\n\nexport const DesktopPreviewAutomationScrollInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationScrollInput,\n});\n\nexport const DesktopPreviewAutomationEvaluateInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationEvaluateInput,\n});\n\nexport const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationWaitForInput,\n});\n\nexport interface DesktopBridge {\n  getAppBranding: () => DesktopAppBranding | null;\n  // One bootstrap per pool instance currently registered with bootstrap\n  // info (omits instances whose backend hasn't produced a config yet).\n  // The primary backend is identified by id === PRIMARY_LOCAL_ENVIRONMENT_ID.\n  getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[];\n  getLocalEnvironmentBearerToken: () => Promise<string>;\n  getClientSettings: () => Promise<ClientSettings | null>;\n  setClientSettings: (settings: ClientSettings) => Promise<void>;\n  getConnectionCatalog?: () => Promise<string | null>;\n  setConnectionCatalog?: (catalog: string) => Promise<boolean>;\n  clearConnectionCatalog?: () => Promise<void>;\n  discoverSshHosts: () => Promise<readonly DesktopDiscoveredSshHost[]>;\n  ensureSshEnvironment: (\n    target: DesktopSshEnvironmentTarget,\n    options?: { issuePairingToken?: boolean },\n  ) => Promise<DesktopSshEnvironmentBootstrap>;\n  disconnectSshEnvironment: (target: DesktopSshEnvironmentTarget) => Promise<void>;\n  fetchSshEnvironmentDescriptor: (httpBaseUrl: string) => Promise<ExecutionEnvironmentDescriptor>;\n  bootstrapSshBearerSession: (\n    httpBaseUrl: string,\n    credential: string,\n  ) => Promise<AuthAccessTokenResult>;\n  fetchSshSessionState: (httpBaseUrl: string, bearerToken: string) => Promise<AuthSessionState>;\n  issueSshWebSocketTicket: (\n    httpBaseUrl: string,\n    bearerToken: string,\n  ) => Promise<AuthWebSocketTicketResult>;\n  onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => () => void;\n  resolveSshPasswordPrompt: (requestId: string, password: string | null) => Promise<void>;\n  getServerExposureState: () => Promise<DesktopServerExposureState>;\n  setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;\n  setTailscaleServeEnabled: (input: {\n    readonly enabled: boolean;\n    readonly port?: number;\n  }) => Promise<DesktopServerExposureState>;\n  getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;\n  getWslState: () => Promise<DesktopWslState>;\n  setWslBackendEnabled: (enabled: boolean) => Promise<DesktopWslState>;\n  setWslDistro: (distro: string | null) => Promise<DesktopWslState>;\n  setWslOnly: (enabled: boolean) => Promise<DesktopWslState>;\n  pickFolder: (options?: PickFolderOptions) => Promise<string | null>;\n  confirm: (message: string) => Promise<boolean>;\n  setTheme: (theme: DesktopTheme) => Promise<void>;\n  showContextMenu: <T extends string>(\n    items: readonly ContextMenuItem<T>[],\n    position?: { x: number; y: number },\n  ) => Promise<T | null>;\n  openExternal: (url: string) => Promise<boolean>;\n  onMenuAction: (listener: (action: string) => void) => () => void;\n  getWindowFullscreenState: () => boolean;\n  onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;\n  getUpdateState: () => Promise<DesktopUpdateState>;\n  setUpdateChannel: (channel: DesktopUpdateChannel) => Promise<DesktopUpdateState>;\n  checkForUpdate: () => Promise<DesktopUpdateCheckResult>;\n  downloadUpdate: () => Promise<DesktopUpdateActionResult>;\n  installUpdate: () => Promise<DesktopUpdateActionResult>;\n  onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;\n  /**\n   * Desktop-only preview surface. Present iff the renderer is hosted by the\n   * Electron desktop build; web builds have `preview === undefined`.\n   */\n  preview?: DesktopPreviewBridge;\n}\n\nexport interface DesktopPreviewBridge {\n  createTab: (tabId: string) => Promise<void>;\n  closeTab: (tabId: string) => Promise<void>;\n  registerWebview: (tabId: string, webContentsId: number) => Promise<void>;\n  navigate: (tabId: string, url: string) => Promise<void>;\n  goBack: (tabId: string) => Promise<void>;\n  goForward: (tabId: string) => Promise<void>;\n  refresh: (tabId: string) => Promise<void>;\n  zoomIn: (tabId: string) => Promise<void>;\n  zoomOut: (tabId: string) => Promise<void>;\n  resetZoom: (tabId: string) => Promise<void>;\n  /** Reload bypassing the HTTP cache. */\n  hardReload: (tabId: string) => Promise<void>;\n  /**\n   * Emulate `prefers-color-scheme` on the guest page (\"system\" clears the\n   * override). Persists per tab and is re-applied across webview swaps.\n   */\n  setColorScheme: (tabId: string, colorScheme: DesktopPreviewColorScheme) => Promise<void>;\n  /** Open the guest webview's DevTools (detached). */\n  openDevTools: (tabId: string) => Promise<void>;\n  /** Drop cookies + storage data for the preview partition (all tabs). */\n  clearCookies: () => Promise<void>;\n  /** Drop the HTTP cache for the preview partition (all tabs). */\n  clearCache: () => Promise<void>;\n  /**\n   * One-shot config for mounting a preview `<webview>`. Replaces three\n   * earlier round-trip calls (`getBrowserPartition`, `getWebviewPreferences`,\n   * `getPickPreloadPath`) so adding a new field here only requires touching\n   * the contract + main, not the renderer's mount logic.\n   */\n  getPreviewConfig: (environmentId: EnvironmentId) => Promise<DesktopPreviewWebviewConfig>;\n  setAnnotationTheme: (theme: DesktopPreviewAnnotationTheme) => Promise<void>;\n  /**\n   * Activate the in-page element picker for the given tab. Resolves with\n   * the picked annotation and its attach/send intent, or `null` when the\n   * user cancels (Escape / nav). The promise rejects if the picker can't be\n   * activated (no webview, etc.).\n   */\n  pickElement: (tabId: string) => Promise<PreviewAnnotationSubmissionResult | null>;\n  /** Cancel an in-flight preview annotation session. */\n  cancelPickElement: (tabId: string) => Promise<void>;\n  captureScreenshot: (tabId: string) => Promise<DesktopPreviewScreenshotArtifact>;\n  revealArtifact: (path: string) => Promise<void>;\n  copyArtifactToClipboard: (path: string) => Promise<void>;\n  pictureInPicture: {\n    open: (tabId: string) => Promise<void>;\n    close: (tabId: string) => Promise<void>;\n  };\n  recording: {\n    startScreencast: (tabId: string) => Promise<void>;\n    stopScreencast: (tabId: string) => Promise<void>;\n    save: (\n      tabId: string,\n      mimeType: string,\n      data: Uint8Array,\n    ) => Promise<DesktopPreviewRecordingArtifact>;\n    onFrame: (listener: (frame: DesktopPreviewRecordingFrame) => void) => () => void;\n  };\n  automation: {\n    status: (tabId: string) => Promise<PreviewAutomationStatus>;\n    snapshot: (tabId: string) => Promise<PreviewAutomationSnapshot>;\n    click: (tabId: string, input: PreviewAutomationClickInput) => Promise<void>;\n    type: (tabId: string, input: PreviewAutomationTypeInput) => Promise<void>;\n    press: (tabId: string, input: PreviewAutomationPressInput) => Promise<void>;\n    scroll: (tabId: string, input: PreviewAutomationScrollInput) => Promise<void>;\n    evaluate: (tabId: string, input: PreviewAutomationEvaluateInput) => Promise<unknown>;\n    waitFor: (tabId: string, input: PreviewAutomationWaitForInput) => Promise<void>;\n  };\n  onStateChange: (listener: (tabId: string, state: DesktopPreviewTabState) => void) => () => void;\n  onPointerEvent: (listener: (event: DesktopPreviewPointerEvent) => void) => () => void;\n}\n\n/**\n * APIs bound to the local app shell, not to any particular backend environment.\n *\n * These capabilities describe the desktop/browser host that the user is\n * currently running: dialogs, external-link opening, context menus, and\n * app-level settings/config access. They must not be used as a proxy for\n * \"whatever environment the user is targeting\", because in a multi-environment\n * world the local shell and a selected backend environment are distinct\n * concepts.\n */\nexport interface LocalApi {\n  dialogs: {\n    pickFolder: (options?: PickFolderOptions) => Promise<string | null>;\n    confirm: (message: string) => Promise<boolean>;\n  };\n  shell: {\n    openExternal: (url: string) => Promise<void>;\n  };\n  contextMenu: {\n    show: <T extends string>(\n      items: readonly ContextMenuItem<T>[],\n      position?: { x: number; y: number },\n    ) => Promise<T | null>;\n  };\n  persistence: {\n    getClientSettings: () => Promise<ClientSettings | null>;\n    setClientSettings: (settings: ClientSettings) => Promise<void>;\n  };\n}\n\n/**\n * APIs bound to a specific backend environment connection.\n *\n * These operations must always be routed with explicit environment context.\n * They represent remote stateful capabilities such as orchestration, terminal,\n * project, VCS, and provider operations. In multi-environment mode, each environment gets\n * its own instance of this surface, and callers should resolve it by\n * `environmentId` rather than reaching through the local desktop bridge.\n */\nexport interface EnvironmentApi {\n  terminal: {\n    open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;\n    attach: (\n      input: typeof TerminalAttachInput.Encoded,\n      callback: (event: TerminalAttachStreamEvent) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n    write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;\n    resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;\n    clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;\n    restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;\n    close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;\n    onMetadata: (\n      callback: (event: TerminalMetadataStreamEvent) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n  };\n  projects: {\n    listEntries: (input: ProjectListEntriesInput) => Promise<ProjectListEntriesResult>;\n    readFile: (input: ProjectReadFileInput) => Promise<ProjectReadFileResult>;\n    searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;\n    writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;\n  };\n  filesystem: {\n    browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;\n  };\n  assets: {\n    createUrl: (input: AssetCreateUrlInput) => Promise<AssetCreateUrlResult>;\n  };\n  sourceControl: {\n    lookupRepository: (\n      input: SourceControlRepositoryLookupInput,\n    ) => Promise<SourceControlRepositoryInfo>;\n    cloneRepository: (\n      input: SourceControlCloneRepositoryInput,\n    ) => Promise<SourceControlCloneRepositoryResult>;\n    publishRepository: (\n      input: SourceControlPublishRepositoryInput,\n    ) => Promise<SourceControlPublishRepositoryResult>;\n  };\n  vcs: {\n    listRefs: (input: VcsListRefsInput) => Promise<VcsListRefsResult>;\n    createWorktree: (input: VcsCreateWorktreeInput) => Promise<VcsCreateWorktreeResult>;\n    removeWorktree: (input: VcsRemoveWorktreeInput) => Promise<void>;\n    createRef: (input: VcsCreateRefInput) => Promise<VcsCreateRefResult>;\n    switchRef: (input: VcsSwitchRefInput) => Promise<VcsSwitchRefResult>;\n    init: (input: VcsInitInput) => Promise<void>;\n    pull: (input: VcsPullInput) => Promise<VcsPullResult>;\n    refreshStatus: (input: VcsStatusInput) => Promise<VcsStatusResult>;\n    onStatus: (\n      input: VcsStatusInput,\n      callback: (status: VcsStatusResult) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n  };\n  git: {\n    resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;\n    preparePullRequestThread: (\n      input: GitPreparePullRequestThreadInput,\n    ) => Promise<GitPreparePullRequestThreadResult>;\n  };\n  review: {\n    getDiffPreview: (input: ReviewDiffPreviewInput) => Promise<ReviewDiffPreviewResult>;\n    getDiffFileContents: (\n      input: ReviewDiffFileContentsInput,\n    ) => Promise<ReviewDiffFileContentsResult>;\n  };\n  orchestration: {\n    dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;\n    getTurnDiff: (input: OrchestrationGetTurnDiffInput) => Promise<OrchestrationGetTurnDiffResult>;\n    getFullThreadDiff: (\n      input: OrchestrationGetFullThreadDiffInput,\n    ) => Promise<OrchestrationGetFullThreadDiffResult>;\n    getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;\n    subscribeShell: (\n      callback: (event: OrchestrationShellStreamItem) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n    subscribeThread: (\n      input: OrchestrationSubscribeThreadInput,\n      callback: (event: OrchestrationThreadStreamItem) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n  };\n  preview: {\n    open: (input: typeof PreviewOpenInput.Encoded) => Promise<PreviewSessionSnapshot>;\n    navigate: (input: typeof PreviewNavigateInput.Encoded) => Promise<PreviewSessionSnapshot>;\n    resize: (input: typeof PreviewResizeInput.Encoded) => Promise<PreviewSessionSnapshot>;\n    refresh: (input: typeof PreviewRefreshInput.Encoded) => Promise<void>;\n    close: (input: typeof PreviewCloseInput.Encoded) => Promise<void>;\n    list: (input: typeof PreviewListInput.Encoded) => Promise<PreviewListResult>;\n    reportStatus: (input: typeof PreviewReportStatusInput.Encoded) => Promise<void>;\n    automation: {\n      connect: (\n        input: PreviewAutomationHost,\n        callback: (event: PreviewAutomationStreamEvent) => void,\n        options?: { onResubscribe?: () => void },\n      ) => () => void;\n      respond: (response: PreviewAutomationResponse) => Promise<void>;\n      focusHost: (input: PreviewAutomationHostFocus) => Promise<void>;\n    };\n    onEvent: (\n      callback: (event: PreviewEvent) => void,\n      options?: { onResubscribe?: () => void },\n    ) => () => void;\n    subscribePorts: (\n      callback: (servers: DiscoveredLocalServerList) => void,\n      options?: { onResubscribe?: () => void },\n    ) => () => void;\n  };\n}\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\n/**\n * Client-side id for the first shell opened on a thread. Ids are uniformly\n * `term-N`; there's no \"default\" intrinsic. Kept as a named constant so callers\n * that want \"the primary shell\" don't hardcode `\"term-1\"`.\n */\nexport const DEFAULT_TERMINAL_ID = \"term-1\";\n\nconst TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\nconst TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(\n  Schema.isLessThanOrEqualTo(1000),\n);\nconst TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(\n  Schema.isLessThanOrEqualTo(500),\n);\nconst TerminalIdSchema = TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(128));\nconst TerminalEnvKeySchema = Schema.String.check(\n  Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),\n).check(Schema.isMaxLength(128));\nconst TerminalEnvValueSchema = Schema.String.check(Schema.isMaxLength(8_192));\nconst TerminalEnvSchema = Schema.Record(TerminalEnvKeySchema, TerminalEnvValueSchema).check(\n  Schema.isMaxProperties(128),\n);\n\nexport const TerminalThreadInput = Schema.Struct({\n  threadId: TrimmedNonEmptyStringSchema,\n});\nexport type TerminalThreadInput = typeof TerminalThreadInput.Type;\n\n/** Terminal ids are ALWAYS chosen by the client and sent explicitly — no server-side allocation. */\nconst TerminalSessionInput = Schema.Struct({\n  ...TerminalThreadInput.fields,\n  terminalId: TerminalIdSchema,\n});\nexport type TerminalSessionInput = Schema.Codec.Encoded<typeof TerminalSessionInput>;\n\nexport const TerminalOpenInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cwd: TrimmedNonEmptyStringSchema,\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  cols: Schema.optional(TerminalColsSchema),\n  rows: Schema.optional(TerminalRowsSchema),\n  env: Schema.optional(TerminalEnvSchema),\n});\nexport type TerminalOpenInput = Schema.Codec.Encoded<typeof TerminalOpenInput>;\n\nexport const TerminalAttachInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cwd: Schema.optional(TrimmedNonEmptyStringSchema),\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  cols: Schema.optional(TerminalColsSchema),\n  rows: Schema.optional(TerminalRowsSchema),\n  env: Schema.optional(TerminalEnvSchema),\n  restartIfNotRunning: Schema.optional(Schema.Boolean),\n});\nexport type TerminalAttachInput = Schema.Codec.Encoded<typeof TerminalAttachInput>;\n\nexport const TerminalWriteInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  data: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),\n});\nexport type TerminalWriteInput = Schema.Codec.Encoded<typeof TerminalWriteInput>;\n\nexport const TerminalResizeInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cols: TerminalColsSchema,\n  rows: TerminalRowsSchema,\n});\nexport type TerminalResizeInput = Schema.Codec.Encoded<typeof TerminalResizeInput>;\n\nexport const TerminalClearInput = TerminalSessionInput;\nexport type TerminalClearInput = Schema.Codec.Encoded<typeof TerminalClearInput>;\n\nexport const TerminalRestartInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cwd: TrimmedNonEmptyStringSchema,\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  cols: TerminalColsSchema,\n  rows: TerminalRowsSchema,\n  env: Schema.optional(TerminalEnvSchema),\n});\nexport type TerminalRestartInput = Schema.Codec.Encoded<typeof TerminalRestartInput>;\n\nexport const TerminalCloseInput = Schema.Struct({\n  ...TerminalThreadInput.fields,\n  terminalId: Schema.optional(TerminalIdSchema),\n  deleteHistory: Schema.optional(Schema.Boolean),\n});\nexport type TerminalCloseInput = typeof TerminalCloseInput.Type;\n\nexport const TerminalSessionStatus = Schema.Literals([\"starting\", \"running\", \"exited\", \"error\"]);\nexport type TerminalSessionStatus = typeof TerminalSessionStatus.Type;\n\nexport const TerminalSessionSnapshot = Schema.Struct({\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n  cwd: Schema.String.check(Schema.isNonEmpty()),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  status: TerminalSessionStatus,\n  pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),\n  history: Schema.String,\n  exitCode: Schema.NullOr(Schema.Int),\n  exitSignal: Schema.NullOr(Schema.Int),\n  /** Server-computed display title (idle shell vs subprocess command). */\n  label: Schema.String.check(Schema.isMaxLength(128)),\n  updatedAt: Schema.String,\n  sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n});\nexport type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;\n\nexport const TerminalSummary = Schema.Struct({\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n  cwd: Schema.String.check(Schema.isNonEmpty()),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  status: TerminalSessionStatus,\n  pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),\n  exitCode: Schema.NullOr(Schema.Int),\n  exitSignal: Schema.NullOr(Schema.Int),\n  hasRunningSubprocess: Schema.Boolean,\n  /** Server-computed display title (idle shell vs subprocess command). */\n  label: Schema.String.check(Schema.isMaxLength(128)),\n  updatedAt: Schema.String,\n});\nexport type TerminalSummary = typeof TerminalSummary.Type;\n\nconst TerminalMetadataSnapshotEvent = Schema.Struct({\n  type: Schema.Literal(\"snapshot\"),\n  terminals: Schema.Array(TerminalSummary),\n});\n\nconst TerminalMetadataUpsertEvent = Schema.Struct({\n  type: Schema.Literal(\"upsert\"),\n  terminal: TerminalSummary,\n});\n\nconst TerminalMetadataRemoveEvent = Schema.Struct({\n  type: Schema.Literal(\"remove\"),\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n});\n\nexport const TerminalMetadataStreamEvent = Schema.Union([\n  TerminalMetadataSnapshotEvent,\n  TerminalMetadataUpsertEvent,\n  TerminalMetadataRemoveEvent,\n]);\nexport type TerminalMetadataStreamEvent = typeof TerminalMetadataStreamEvent.Type;\n\nconst TerminalEventBaseSchema = Schema.Struct({\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n  sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n});\n\nconst TerminalStartedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"started\"),\n  snapshot: TerminalSessionSnapshot,\n});\n\nconst TerminalOutputEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"output\"),\n  data: Schema.String,\n});\n\nconst TerminalExitedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"exited\"),\n  exitCode: Schema.NullOr(Schema.Int),\n  exitSignal: Schema.NullOr(Schema.Int),\n});\n\nconst TerminalClosedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"closed\"),\n});\n\nconst TerminalErrorEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"error\"),\n  message: Schema.String.check(Schema.isNonEmpty()),\n});\n\nconst TerminalClearedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"cleared\"),\n});\n\nconst TerminalRestartedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"restarted\"),\n  snapshot: TerminalSessionSnapshot,\n});\n\nconst TerminalActivityEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"activity\"),\n  hasRunningSubprocess: Schema.Boolean,\n  label: Schema.String.check(Schema.isMaxLength(128)),\n});\n\nexport const TerminalEvent = Schema.Union([\n  TerminalStartedEvent,\n  TerminalOutputEvent,\n  TerminalExitedEvent,\n  TerminalClosedEvent,\n  TerminalErrorEvent,\n  TerminalClearedEvent,\n  TerminalRestartedEvent,\n  TerminalActivityEvent,\n]);\nexport type TerminalEvent = typeof TerminalEvent.Type;\n\nconst TerminalAttachSnapshotEvent = Schema.Struct({\n  type: Schema.Literal(\"snapshot\"),\n  snapshot: TerminalSessionSnapshot,\n});\n\nexport const TerminalAttachStreamEvent = Schema.Union([\n  TerminalAttachSnapshotEvent,\n  TerminalOutputEvent,\n  TerminalExitedEvent,\n  TerminalClosedEvent,\n  TerminalErrorEvent,\n  TerminalClearedEvent,\n  TerminalRestartedEvent,\n  TerminalActivityEvent,\n]);\nexport type TerminalAttachStreamEvent = typeof TerminalAttachStreamEvent.Type;\n\nexport class TerminalCwdNotFoundError extends Schema.TaggedErrorClass<TerminalCwdNotFoundError>()(\n  \"TerminalCwdNotFoundError\",\n  {\n    cwd: Schema.String,\n  },\n) {\n  override get message() {\n    return `Terminal cwd does not exist: ${this.cwd}`;\n  }\n}\n\nexport class TerminalCwdNotDirectoryError extends Schema.TaggedErrorClass<TerminalCwdNotDirectoryError>()(\n  \"TerminalCwdNotDirectoryError\",\n  {\n    cwd: Schema.String,\n  },\n) {\n  override get message() {\n    return `Terminal cwd is not a directory: ${this.cwd}`;\n  }\n}\n\nexport class TerminalCwdStatError extends Schema.TaggedErrorClass<TerminalCwdStatError>()(\n  \"TerminalCwdStatError\",\n  {\n    cwd: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to access terminal cwd: ${this.cwd}`;\n  }\n}\n\nexport const TerminalCwdError = Schema.Union([\n  TerminalCwdNotFoundError,\n  TerminalCwdNotDirectoryError,\n  TerminalCwdStatError,\n]);\nexport type TerminalCwdError = typeof TerminalCwdError.Type;\n\nexport class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(\n  \"TerminalHistoryError\",\n  {\n    operation: Schema.Literals([\"read\", \"truncate\", \"migrate\"]),\n    threadId: Schema.String,\n    terminalId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;\n  }\n}\n\nexport class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(\n  \"TerminalSessionLookupError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n  },\n) {\n  override get message() {\n    return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;\n  }\n}\n\nexport class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(\n  \"TerminalNotRunningError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n  },\n) {\n  override get message() {\n    return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;\n  }\n}\n\nexport class TerminalWriteError extends Schema.TaggedErrorClass<TerminalWriteError>()(\n  \"TerminalWriteError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n    terminalPid: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to write to terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid}`;\n  }\n}\n\nexport class TerminalResizeError extends Schema.TaggedErrorClass<TerminalResizeError>()(\n  \"TerminalResizeError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n    terminalPid: Schema.Number,\n    cols: TerminalColsSchema,\n    rows: TerminalRowsSchema,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to resize terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid} to ${this.cols}x${this.rows}`;\n  }\n}\n\nexport const TerminalError = Schema.Union([\n  TerminalCwdError,\n  TerminalHistoryError,\n  TerminalSessionLookupError,\n  TerminalNotRunningError,\n  TerminalWriteError,\n  TerminalResizeError,\n]);\nexport type TerminalError = typeof TerminalError.Type;\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport {\n  ApprovalRequestId,\n  EventId,\n  IsoDateTime,\n  ProviderItemId,\n  ThreadId,\n  TurnId,\n} from \"./baseSchemas.ts\";\nimport {\n  ChatAttachment,\n  ModelSelection,\n  PROVIDER_SEND_TURN_MAX_ATTACHMENTS,\n  PROVIDER_SEND_TURN_MAX_INPUT_CHARS,\n  ProviderApprovalDecision,\n  ProviderApprovalPolicy,\n  ProviderInteractionMode,\n  ProviderRequestKind,\n  ProviderSandboxMode,\n  ProviderUserInputAnswers,\n  RuntimeMode,\n} from \"./orchestration.ts\";\nimport { ProviderInstanceId, ProviderDriverKind } from \"./providerInstance.ts\";\n\nconst ProviderSessionStatus = Schema.Literals([\n  \"connecting\",\n  \"ready\",\n  \"running\",\n  \"error\",\n  \"closed\",\n]);\n\nexport const ProviderSession = Schema.Struct({\n  provider: ProviderDriverKind,\n  // Optional during the driver/instance migration. Once every producer\n  // populates it (post-slice-4), routing flips to instance-id-only and the\n  // legacy `provider` field is removed.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  status: ProviderSessionStatus,\n  runtimeMode: RuntimeMode,\n  cwd: Schema.optional(TrimmedNonEmptyString),\n  model: Schema.optional(TrimmedNonEmptyString),\n  threadId: ThreadId,\n  resumeCursor: Schema.optional(Schema.Unknown),\n  activeTurnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  lastError: Schema.optional(TrimmedNonEmptyString),\n});\nexport type ProviderSession = typeof ProviderSession.Type;\n\nexport const ProviderSessionStartInput = Schema.Struct({\n  threadId: ThreadId,\n  provider: Schema.optional(ProviderDriverKind),\n  // See ProviderSession for the migration story.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  cwd: Schema.optional(TrimmedNonEmptyString),\n  modelSelection: Schema.optional(ModelSelection),\n  resumeCursor: Schema.optional(Schema.Unknown),\n  approvalPolicy: Schema.optional(ProviderApprovalPolicy),\n  sandboxMode: Schema.optional(ProviderSandboxMode),\n  runtimeMode: RuntimeMode,\n});\nexport type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type;\n\nexport const ProviderSendTurnInput = Schema.Struct({\n  threadId: ThreadId,\n  input: Schema.optional(\n    TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),\n  ),\n  attachments: Schema.optional(\n    Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),\n  ),\n  modelSelection: Schema.optional(ModelSelection),\n  interactionMode: Schema.optional(ProviderInteractionMode),\n});\nexport type ProviderSendTurnInput = typeof ProviderSendTurnInput.Type;\n\nexport const ProviderTurnStartResult = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  resumeCursor: Schema.optional(Schema.Unknown),\n});\nexport type ProviderTurnStartResult = typeof ProviderTurnStartResult.Type;\n\nexport const ProviderInterruptTurnInput = Schema.Struct({\n  threadId: ThreadId,\n  turnId: Schema.optional(TurnId),\n});\nexport type ProviderInterruptTurnInput = typeof ProviderInterruptTurnInput.Type;\n\nexport const ProviderStopSessionInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ProviderStopSessionInput = typeof ProviderStopSessionInput.Type;\n\nexport const ProviderRespondToRequestInput = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  decision: ProviderApprovalDecision,\n});\nexport type ProviderRespondToRequestInput = typeof ProviderRespondToRequestInput.Type;\n\nexport const ProviderRespondToUserInputInput = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  answers: ProviderUserInputAnswers,\n});\nexport type ProviderRespondToUserInputInput = typeof ProviderRespondToUserInputInput.Type;\n\nconst ProviderEventKind = Schema.Literals([\"session\", \"notification\", \"request\", \"error\"]);\n\nexport const ProviderEvent = Schema.Struct({\n  id: EventId,\n  kind: ProviderEventKind,\n  provider: ProviderDriverKind,\n  // See ProviderSession for the migration story.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n  method: TrimmedNonEmptyString,\n  message: Schema.optional(TrimmedNonEmptyString),\n  turnId: Schema.optional(TurnId),\n  itemId: Schema.optional(ProviderItemId),\n  requestId: Schema.optional(ApprovalRequestId),\n  requestKind: Schema.optional(ProviderRequestKind),\n  textDelta: Schema.optional(Schema.String),\n  payload: Schema.optional(Schema.Unknown),\n});\nexport type ProviderEvent = typeof ProviderEvent.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n  EventId,\n  IsoDateTime,\n  NonNegativeInt,\n  ProviderItemId,\n  PositiveInt,\n  RuntimeItemId,\n  RuntimeRequestId,\n  RuntimeTaskId,\n  ThreadId,\n  TrimmedNonEmptyString,\n  TurnId,\n} from \"./baseSchemas.ts\";\nimport { ProviderInstanceId, ProviderDriverKind } from \"./providerInstance.ts\";\n\nconst TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\nconst UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);\n\nconst RuntimeEventRawSource = Schema.Union([\n  Schema.Literal(\"codex.app-server.notification\"),\n  Schema.Literal(\"codex.app-server.request\"),\n  Schema.Literal(\"codex.eventmsg\"),\n  Schema.Literal(\"claude.sdk.message\"),\n  Schema.Literal(\"claude.sdk.permission\"),\n  Schema.Literal(\"codex.sdk.thread-event\"),\n  Schema.Literal(\"opencode.sdk.event\"),\n  Schema.Literal(\"acp.jsonrpc\"),\n  Schema.TemplateLiteral([\"acp.\", Schema.String, \".extension\"]),\n]);\nexport type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;\n\nexport const RuntimeEventRaw = Schema.Struct({\n  source: RuntimeEventRawSource,\n  method: Schema.optional(TrimmedNonEmptyStringSchema),\n  messageType: Schema.optional(TrimmedNonEmptyStringSchema),\n  payload: Schema.Unknown,\n});\nexport type RuntimeEventRaw = typeof RuntimeEventRaw.Type;\n\nconst ProviderRequestId = TrimmedNonEmptyStringSchema;\nexport type ProviderRequestId = typeof ProviderRequestId.Type;\n\nconst ProviderRefs = Schema.Struct({\n  providerTurnId: Schema.optional(TrimmedNonEmptyStringSchema),\n  providerItemId: Schema.optional(ProviderItemId),\n  providerRequestId: Schema.optional(ProviderRequestId),\n});\nexport type ProviderRefs = typeof ProviderRefs.Type;\n\nconst RuntimeSessionState = Schema.Literals([\n  \"starting\",\n  \"ready\",\n  \"running\",\n  \"waiting\",\n  \"stopped\",\n  \"error\",\n]);\nexport type RuntimeSessionState = typeof RuntimeSessionState.Type;\n\nconst RuntimeThreadState = Schema.Literals([\n  \"active\",\n  \"idle\",\n  \"archived\",\n  \"closed\",\n  \"compacted\",\n  \"error\",\n]);\nexport type RuntimeThreadState = typeof RuntimeThreadState.Type;\n\nconst RuntimeTurnState = Schema.Literals([\"completed\", \"failed\", \"interrupted\", \"cancelled\"]);\nexport type RuntimeTurnState = typeof RuntimeTurnState.Type;\n\nconst RuntimePlanStepStatus = Schema.Literals([\"pending\", \"inProgress\", \"completed\"]);\nexport type RuntimePlanStepStatus = typeof RuntimePlanStepStatus.Type;\n\nconst RuntimeItemStatus = Schema.Literals([\"inProgress\", \"completed\", \"failed\", \"declined\"]);\nexport type RuntimeItemStatus = typeof RuntimeItemStatus.Type;\n\nconst RuntimeContentStreamKind = Schema.Literals([\n  \"assistant_text\",\n  \"reasoning_text\",\n  \"reasoning_summary_text\",\n  \"plan_text\",\n  \"command_output\",\n  \"file_change_output\",\n  \"unknown\",\n]);\nexport type RuntimeContentStreamKind = typeof RuntimeContentStreamKind.Type;\n\nconst RuntimeSessionExitKind = Schema.Literals([\"graceful\", \"error\"]);\nexport type RuntimeSessionExitKind = typeof RuntimeSessionExitKind.Type;\n\nconst RuntimeErrorClass = Schema.Literals([\n  \"provider_error\",\n  \"transport_error\",\n  \"permission_error\",\n  \"validation_error\",\n  \"unknown\",\n]);\nexport type RuntimeErrorClass = typeof RuntimeErrorClass.Type;\n\nexport const TOOL_LIFECYCLE_ITEM_TYPES = [\n  \"command_execution\",\n  \"file_change\",\n  \"mcp_tool_call\",\n  \"dynamic_tool_call\",\n  \"collab_agent_tool_call\",\n  \"web_search\",\n  \"image_view\",\n] as const;\n\nexport const ToolLifecycleItemType = Schema.Literals(TOOL_LIFECYCLE_ITEM_TYPES);\nexport type ToolLifecycleItemType = typeof ToolLifecycleItemType.Type;\n\nexport function isToolLifecycleItemType(value: string): value is ToolLifecycleItemType {\n  return TOOL_LIFECYCLE_ITEM_TYPES.includes(value as ToolLifecycleItemType);\n}\n\nexport const CanonicalItemType = Schema.Literals([\n  \"user_message\",\n  \"assistant_message\",\n  \"reasoning\",\n  \"plan\",\n  ...TOOL_LIFECYCLE_ITEM_TYPES,\n  \"review_entered\",\n  \"review_exited\",\n  \"context_compaction\",\n  \"error\",\n  \"unknown\",\n]);\nexport type CanonicalItemType = typeof CanonicalItemType.Type;\n\nexport const CanonicalRequestType = Schema.Literals([\n  \"command_execution_approval\",\n  \"file_read_approval\",\n  \"file_change_approval\",\n  \"apply_patch_approval\",\n  \"exec_command_approval\",\n  \"tool_user_input\",\n  \"dynamic_tool_call\",\n  \"auth_tokens_refresh\",\n  \"unknown\",\n]);\nexport type CanonicalRequestType = typeof CanonicalRequestType.Type;\n\nconst ProviderRuntimeEventType = Schema.Literals([\n  \"session.started\",\n  \"session.configured\",\n  \"session.state.changed\",\n  \"session.exited\",\n  \"thread.started\",\n  \"thread.state.changed\",\n  \"thread.metadata.updated\",\n  \"thread.token-usage.updated\",\n  \"thread.realtime.started\",\n  \"thread.realtime.item-added\",\n  \"thread.realtime.transcript.delta\",\n  \"thread.realtime.transcript.done\",\n  \"thread.realtime.audio.delta\",\n  \"thread.realtime.error\",\n  \"thread.realtime.closed\",\n  \"turn.started\",\n  \"turn.completed\",\n  \"turn.aborted\",\n  \"turn.plan.updated\",\n  \"turn.proposed.delta\",\n  \"turn.proposed.completed\",\n  \"turn.diff.updated\",\n  \"item.started\",\n  \"item.updated\",\n  \"item.completed\",\n  \"content.delta\",\n  \"request.opened\",\n  \"request.resolved\",\n  \"user-input.requested\",\n  \"user-input.resolved\",\n  \"task.started\",\n  \"task.progress\",\n  \"task.updated\",\n  \"task.completed\",\n  \"hook.started\",\n  \"hook.progress\",\n  \"hook.completed\",\n  \"tool.progress\",\n  \"tool.summary\",\n  \"auth.status\",\n  \"account.updated\",\n  \"account.rate-limits.updated\",\n  \"mcp.status.updated\",\n  \"mcp.oauth.completed\",\n  \"model.rerouted\",\n  \"config.warning\",\n  \"deprecation.notice\",\n  \"files.persisted\",\n  \"runtime.warning\",\n  \"runtime.error\",\n]);\nexport type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type;\n\nconst SessionStartedType = Schema.Literal(\"session.started\");\nconst SessionConfiguredType = Schema.Literal(\"session.configured\");\nconst SessionStateChangedType = Schema.Literal(\"session.state.changed\");\nconst SessionExitedType = Schema.Literal(\"session.exited\");\nconst ThreadStartedType = Schema.Literal(\"thread.started\");\nconst ThreadStateChangedType = Schema.Literal(\"thread.state.changed\");\nconst ThreadMetadataUpdatedType = Schema.Literal(\"thread.metadata.updated\");\nconst ThreadTokenUsageUpdatedType = Schema.Literal(\"thread.token-usage.updated\");\nconst ThreadRealtimeStartedType = Schema.Literal(\"thread.realtime.started\");\nconst ThreadRealtimeItemAddedType = Schema.Literal(\"thread.realtime.item-added\");\nconst ThreadRealtimeTranscriptDeltaType = Schema.Literal(\"thread.realtime.transcript.delta\");\nconst ThreadRealtimeTranscriptDoneType = Schema.Literal(\"thread.realtime.transcript.done\");\nconst ThreadRealtimeAudioDeltaType = Schema.Literal(\"thread.realtime.audio.delta\");\nconst ThreadRealtimeErrorType = Schema.Literal(\"thread.realtime.error\");\nconst ThreadRealtimeClosedType = Schema.Literal(\"thread.realtime.closed\");\nconst TurnStartedType = Schema.Literal(\"turn.started\");\nconst TurnCompletedType = Schema.Literal(\"turn.completed\");\nconst TurnAbortedType = Schema.Literal(\"turn.aborted\");\nconst TurnPlanUpdatedType = Schema.Literal(\"turn.plan.updated\");\nconst TurnProposedDeltaType = Schema.Literal(\"turn.proposed.delta\");\nconst TurnProposedCompletedType = Schema.Literal(\"turn.proposed.completed\");\nconst TurnDiffUpdatedType = Schema.Literal(\"turn.diff.updated\");\nconst ItemStartedType = Schema.Literal(\"item.started\");\nconst ItemUpdatedType = Schema.Literal(\"item.updated\");\nconst ItemCompletedType = Schema.Literal(\"item.completed\");\nconst ContentDeltaType = Schema.Literal(\"content.delta\");\nconst RequestOpenedType = Schema.Literal(\"request.opened\");\nconst RequestResolvedType = Schema.Literal(\"request.resolved\");\nconst UserInputRequestedType = Schema.Literal(\"user-input.requested\");\nconst UserInputResolvedType = Schema.Literal(\"user-input.resolved\");\nconst TaskStartedType = Schema.Literal(\"task.started\");\nconst TaskProgressType = Schema.Literal(\"task.progress\");\nconst TaskUpdatedType = Schema.Literal(\"task.updated\");\nconst TaskCompletedType = Schema.Literal(\"task.completed\");\nconst HookStartedType = Schema.Literal(\"hook.started\");\nconst HookProgressType = Schema.Literal(\"hook.progress\");\nconst HookCompletedType = Schema.Literal(\"hook.completed\");\nconst ToolProgressType = Schema.Literal(\"tool.progress\");\nconst ToolSummaryType = Schema.Literal(\"tool.summary\");\nconst AuthStatusType = Schema.Literal(\"auth.status\");\nconst AccountUpdatedType = Schema.Literal(\"account.updated\");\nconst AccountRateLimitsUpdatedType = Schema.Literal(\"account.rate-limits.updated\");\nconst McpStatusUpdatedType = Schema.Literal(\"mcp.status.updated\");\nconst McpOauthCompletedType = Schema.Literal(\"mcp.oauth.completed\");\nconst ModelReroutedType = Schema.Literal(\"model.rerouted\");\nconst ConfigWarningType = Schema.Literal(\"config.warning\");\nconst DeprecationNoticeType = Schema.Literal(\"deprecation.notice\");\nconst FilesPersistedType = Schema.Literal(\"files.persisted\");\nconst ToolDeniedType = Schema.Literal(\"tool.denied\");\nconst RuntimeWarningType = Schema.Literal(\"runtime.warning\");\nconst RuntimeErrorType = Schema.Literal(\"runtime.error\");\n\nconst ProviderRuntimeEventBase = Schema.Struct({\n  eventId: EventId,\n  provider: ProviderDriverKind,\n  // Optional during the driver/instance migration. See providerInstance.ts\n  // for the routing-key-vs-driver-id distinction. Once every emitter\n  // populates it (post-slice-4), routing flips to instance-id-only.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n  turnId: Schema.optional(TurnId),\n  itemId: Schema.optional(RuntimeItemId),\n  requestId: Schema.optional(RuntimeRequestId),\n  providerRefs: Schema.optional(ProviderRefs),\n  raw: Schema.optional(RuntimeEventRaw),\n});\nexport type ProviderRuntimeEventBase = typeof ProviderRuntimeEventBase.Type;\n\nconst SessionStartedPayload = Schema.Struct({\n  message: Schema.optional(TrimmedNonEmptyStringSchema),\n  resume: Schema.optional(Schema.Unknown),\n});\nexport type SessionStartedPayload = typeof SessionStartedPayload.Type;\n\nconst SessionConfiguredPayload = Schema.Struct({\n  config: UnknownRecordSchema,\n});\nexport type SessionConfiguredPayload = typeof SessionConfiguredPayload.Type;\n\nconst SessionStateChangedPayload = Schema.Struct({\n  state: RuntimeSessionState,\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type SessionStateChangedPayload = typeof SessionStateChangedPayload.Type;\n\nconst SessionExitedPayload = Schema.Struct({\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n  recoverable: Schema.optional(Schema.Boolean),\n  exitKind: Schema.optional(RuntimeSessionExitKind),\n});\nexport type SessionExitedPayload = typeof SessionExitedPayload.Type;\n\nconst ThreadStartedPayload = Schema.Struct({\n  providerThreadId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ThreadStartedPayload = typeof ThreadStartedPayload.Type;\n\nconst ThreadStateChangedPayload = Schema.Struct({\n  state: RuntimeThreadState,\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type ThreadStateChangedPayload = typeof ThreadStateChangedPayload.Type;\n\nconst ThreadMetadataUpdatedPayload = Schema.Struct({\n  name: Schema.optional(TrimmedNonEmptyStringSchema),\n  metadata: Schema.optional(UnknownRecordSchema),\n});\nexport type ThreadMetadataUpdatedPayload = typeof ThreadMetadataUpdatedPayload.Type;\n\nexport const ThreadTokenUsageSnapshot = Schema.Struct({\n  usedTokens: NonNegativeInt,\n  totalProcessedTokens: Schema.optional(NonNegativeInt),\n  maxTokens: Schema.optional(PositiveInt),\n  inputTokens: Schema.optional(NonNegativeInt),\n  cachedInputTokens: Schema.optional(NonNegativeInt),\n  outputTokens: Schema.optional(NonNegativeInt),\n  reasoningOutputTokens: Schema.optional(NonNegativeInt),\n  lastUsedTokens: Schema.optional(NonNegativeInt),\n  lastInputTokens: Schema.optional(NonNegativeInt),\n  lastCachedInputTokens: Schema.optional(NonNegativeInt),\n  lastOutputTokens: Schema.optional(NonNegativeInt),\n  lastReasoningOutputTokens: Schema.optional(NonNegativeInt),\n  toolUses: Schema.optional(NonNegativeInt),\n  durationMs: Schema.optional(NonNegativeInt),\n  compactsAutomatically: Schema.optional(Schema.Boolean),\n});\nexport type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;\n\nconst ThreadTokenUsageUpdatedPayload = Schema.Struct({\n  usage: ThreadTokenUsageSnapshot,\n});\nexport type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type;\n\nconst ThreadRealtimeStartedPayload = Schema.Struct({\n  realtimeSessionId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ThreadRealtimeStartedPayload = typeof ThreadRealtimeStartedPayload.Type;\n\nconst ThreadRealtimeItemAddedPayload = Schema.Struct({\n  item: Schema.Unknown,\n});\nexport type ThreadRealtimeItemAddedPayload = typeof ThreadRealtimeItemAddedPayload.Type;\n\nconst ThreadRealtimeTranscriptDeltaPayload = Schema.Struct({\n  role: TrimmedNonEmptyStringSchema,\n  delta: Schema.String,\n});\nexport type ThreadRealtimeTranscriptDeltaPayload =\n  typeof ThreadRealtimeTranscriptDeltaPayload.Type;\n\nconst ThreadRealtimeTranscriptDonePayload = Schema.Struct({\n  role: TrimmedNonEmptyStringSchema,\n  text: Schema.String,\n});\nexport type ThreadRealtimeTranscriptDonePayload = typeof ThreadRealtimeTranscriptDonePayload.Type;\n\nconst ThreadRealtimeAudioDeltaPayload = Schema.Struct({\n  audio: Schema.Unknown,\n});\nexport type ThreadRealtimeAudioDeltaPayload = typeof ThreadRealtimeAudioDeltaPayload.Type;\n\nconst ThreadRealtimeErrorPayload = Schema.Struct({\n  message: TrimmedNonEmptyStringSchema,\n});\nexport type ThreadRealtimeErrorPayload = typeof ThreadRealtimeErrorPayload.Type;\n\nconst ThreadRealtimeClosedPayload = Schema.Struct({\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ThreadRealtimeClosedPayload = typeof ThreadRealtimeClosedPayload.Type;\n\nconst TurnStartedPayload = Schema.Struct({\n  model: Schema.optional(TrimmedNonEmptyStringSchema),\n  effort: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type TurnStartedPayload = typeof TurnStartedPayload.Type;\n\nconst TurnCompletedPayload = Schema.Struct({\n  state: RuntimeTurnState,\n  stopReason: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  usage: Schema.optional(Schema.Unknown),\n  modelUsage: Schema.optional(UnknownRecordSchema),\n  totalCostUsd: Schema.optional(Schema.Number),\n  errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type TurnCompletedPayload = typeof TurnCompletedPayload.Type;\n\nconst TurnAbortedPayload = Schema.Struct({\n  reason: TrimmedNonEmptyStringSchema,\n});\nexport type TurnAbortedPayload = typeof TurnAbortedPayload.Type;\n\nconst RuntimePlanStep = Schema.Struct({\n  step: TrimmedNonEmptyStringSchema,\n  status: RuntimePlanStepStatus,\n});\nexport type RuntimePlanStep = typeof RuntimePlanStep.Type;\n\nconst TurnPlanUpdatedPayload = Schema.Struct({\n  explanation: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  plan: Schema.Array(RuntimePlanStep),\n});\nexport type TurnPlanUpdatedPayload = typeof TurnPlanUpdatedPayload.Type;\n\nconst TurnProposedDeltaPayload = Schema.Struct({\n  delta: Schema.String,\n});\nexport type TurnProposedDeltaPayload = typeof TurnProposedDeltaPayload.Type;\n\nconst TurnProposedCompletedPayload = Schema.Struct({\n  planMarkdown: TrimmedNonEmptyStringSchema,\n});\nexport type TurnProposedCompletedPayload = typeof TurnProposedCompletedPayload.Type;\n\nconst TurnDiffUpdatedPayload = Schema.Struct({\n  unifiedDiff: Schema.String,\n});\nexport type TurnDiffUpdatedPayload = typeof TurnDiffUpdatedPayload.Type;\n\nexport const ItemLifecyclePayload = Schema.Struct({\n  itemType: CanonicalItemType,\n  status: Schema.optional(RuntimeItemStatus),\n  title: Schema.optional(TrimmedNonEmptyStringSchema),\n  detail: Schema.optional(TrimmedNonEmptyStringSchema),\n  data: Schema.optional(Schema.Unknown),\n  /**\n   * Owning agent when this item ran inside a subagent (resolved from the\n   * SDK's parent_tool_use_id). Clients re-home attributed items out of the\n   * main timeline and into the owning agent's Agents-surface row.\n   */\n  agentId: Schema.optional(TrimmedNonEmptyStringSchema),\n  parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ItemLifecyclePayload = typeof ItemLifecyclePayload.Type;\n\nconst ContentDeltaPayload = Schema.Struct({\n  streamKind: RuntimeContentStreamKind,\n  delta: Schema.String,\n  contentIndex: Schema.optional(Schema.Int),\n  summaryIndex: Schema.optional(Schema.Int),\n});\nexport type ContentDeltaPayload = typeof ContentDeltaPayload.Type;\n\nconst RequestOpenedPayload = Schema.Struct({\n  requestType: CanonicalRequestType,\n  detail: Schema.optional(TrimmedNonEmptyStringSchema),\n  args: Schema.optional(Schema.Unknown),\n});\nexport type RequestOpenedPayload = typeof RequestOpenedPayload.Type;\n\nconst RequestResolvedPayload = Schema.Struct({\n  requestType: CanonicalRequestType,\n  decision: Schema.optional(TrimmedNonEmptyStringSchema),\n  resolution: Schema.optional(Schema.Unknown),\n});\nexport type RequestResolvedPayload = typeof RequestResolvedPayload.Type;\n\nconst UserInputQuestionOption = Schema.Struct({\n  label: TrimmedNonEmptyStringSchema,\n  description: TrimmedNonEmptyStringSchema,\n});\nexport type UserInputQuestionOption = typeof UserInputQuestionOption.Type;\n\nexport const UserInputQuestion = Schema.Struct({\n  id: TrimmedNonEmptyStringSchema,\n  header: TrimmedNonEmptyStringSchema,\n  question: TrimmedNonEmptyStringSchema,\n  options: Schema.Array(UserInputQuestionOption),\n  multiSelect: Schema.optional(Schema.Boolean).pipe(\n    Schema.withConstructorDefault(Effect.succeed(false)),\n  ),\n});\nexport type UserInputQuestion = typeof UserInputQuestion.Type;\n\nconst UserInputRequestedPayload = Schema.Struct({\n  questions: Schema.Array(UserInputQuestion),\n});\nexport type UserInputRequestedPayload = typeof UserInputRequestedPayload.Type;\n\nconst UserInputResolvedPayload = Schema.Struct({\n  answers: UnknownRecordSchema,\n});\nexport type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;\n\n/**\n * Typed per-task usage rollup. Field names match the orchestration-v2 subagent\n * usage vocabulary (#4779) so the eventual migration is a rename, not a remap.\n * Claude reports per-activation deltas; Codex reports cumulative totals — the\n * merge strategy is provider-specific and lives in client-runtime.\n */\nexport const RuntimeTaskUsage = Schema.Struct({\n  totalTokens: NonNegativeInt,\n  inputTokens: Schema.optional(NonNegativeInt),\n  cachedInputTokens: Schema.optional(NonNegativeInt),\n  outputTokens: Schema.optional(NonNegativeInt),\n  reasoningOutputTokens: Schema.optional(NonNegativeInt),\n  toolUses: Schema.optional(NonNegativeInt),\n  durationMs: Schema.optional(NonNegativeInt),\n});\nexport type RuntimeTaskUsage = typeof RuntimeTaskUsage.Type;\n\nexport const TaskWorkflowPhase = Schema.Struct({\n  index: NonNegativeInt,\n  title: TrimmedNonEmptyStringSchema,\n});\nexport type TaskWorkflowPhase = typeof TaskWorkflowPhase.Type;\n\nexport const TaskRunHandles = Schema.Struct({\n  runId: Schema.optional(TrimmedNonEmptyStringSchema),\n  scriptPath: Schema.optional(TrimmedNonEmptyStringSchema),\n  transcriptDir: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Only http/https URLs may be stored here — sanitized at the adapter. */\n  sessionUrl: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type TaskRunHandles = typeof TaskRunHandles.Type;\n\n/**\n * Watch-loop task types: Monitor-tool tasks plus background shells (a shell\n * that outlives its turn is in practice a watch loop). Canonical single copy —\n * the server liveness registry, ingestion's agentKind stamp, and the client\n * fold's legacy fallback all classify with these sets.\n */\nexport const MONITOR_TASK_TYPES: ReadonlySet<string> = new Set([\n  \"monitor\",\n  \"monitor_mcp\",\n  \"local_bash\",\n  \"shell\",\n]);\n/** Task types that are neither agents nor watch loops (plan-mode bookkeeping). */\nexport const INERT_TASK_TYPES: ReadonlySet<string> = new Set([\"plan\", \"dream\"]);\n\n/**\n * Agent-vs-background classification, stamped by ingestion as `agentKind` so\n * persisted rows are self-describing. A deliberate denylist: the SDK's\n * agent-flavored type names drift (subagent, local_agent, local_workflow, …)\n * and an allowlist silently dropped real subagents when \"local_agent\"\n * appeared. A task launched from inside a subagent (agentId set) is\n * agent-internal background work UNLESS it is itself agent-flavored — a\n * nested agent can outlive its parent and stays in the roster.\n */\nexport function classifyTaskAgentKind(input: {\n  readonly taskType?: string | undefined;\n  readonly agentId?: string | undefined;\n}): \"agent\" | \"background\" {\n  const { taskType, agentId } = input;\n  const nonAgentType =\n    taskType !== undefined && (MONITOR_TASK_TYPES.has(taskType) || INERT_TASK_TYPES.has(taskType));\n  if (agentId !== undefined && agentId.trim().length > 0) {\n    return taskType === undefined || nonAgentType ? \"background\" : \"agent\";\n  }\n  return nonAgentType ? \"background\" : \"agent\";\n}\n\n/**\n * Optional agent-identity linkage carried on every task lifecycle payload.\n * Repeated on progress and terminal rows (not just start) so client folds can\n * reconstruct an agent even when its start row aged out of activity retention.\n * All fields optional: old emitters and old rows decode unchanged.\n */\nconst taskAgentLinkageFields = {\n  /** SDK task_type (subagent/shell/monitor/local_workflow/…), repeated on\n   * every row so folds can classify without the start row. */\n  taskType: Schema.optional(TrimmedNonEmptyStringSchema),\n  /**\n   * Server-stamped classification (classifyTaskAgentKind at ingestion).\n   * Clients trust this stamp outright; rows without it (legacy, pre-stamp)\n   * fall back to client-side heuristics.\n   */\n  agentKind: Schema.optional(Schema.Literals([\"agent\", \"background\"])),\n  /**\n   * Owning agent when the task itself was launched from inside a subagent\n   * (e.g. a subagent's background shell). Clients treat such tasks as\n   * agent-internal and keep them out of the parent work log.\n   */\n  agentId: Schema.optional(TrimmedNonEmptyStringSchema),\n  title: Schema.optional(TrimmedNonEmptyStringSchema),\n  role: Schema.optional(TrimmedNonEmptyStringSchema),\n  model: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Reasoning effort when known (e.g. \"high\"). Open string: provider vocabularies differ. */\n  effort: Schema.optional(TrimmedNonEmptyStringSchema),\n  toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n  parentAgentId: Schema.optional(TrimmedNonEmptyStringSchema),\n  workflowName: Schema.optional(TrimmedNonEmptyStringSchema),\n  agentIndex: Schema.optional(NonNegativeInt),\n  phaseIndex: Schema.optional(NonNegativeInt),\n  phaseTitle: Schema.optional(TrimmedNonEmptyStringSchema),\n  phases: Schema.optional(Schema.Array(TaskWorkflowPhase)),\n  attempt: Schema.optional(NonNegativeInt),\n  runHandles: Schema.optional(TaskRunHandles),\n  outputFile: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Codex agent hierarchy path, e.g. \"/root/marlow\". */\n  agentPath: Schema.optional(TrimmedNonEmptyStringSchema),\n  /**\n   * Set on provider-synthesized child-agent events (Codex) whose activity\n   * belongs in the Agents surface, never the parent timeline.\n   */\n  timelineBypass: Schema.optional(Schema.Boolean),\n} as const;\n\nexport const TaskAgentLinkage = Schema.Struct(taskAgentLinkageFields);\nexport type TaskAgentLinkage = typeof TaskAgentLinkage.Type;\n\nconst TaskStartedPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  description: Schema.optional(TrimmedNonEmptyStringSchema),\n  ...taskAgentLinkageFields,\n});\nexport type TaskStartedPayload = typeof TaskStartedPayload.Type;\n\nexport const RuntimeTaskStatus = Schema.Literals([\n  \"pending\",\n  \"running\",\n  \"waiting\",\n  \"idle\",\n  \"completed\",\n  \"failed\",\n  \"cancelled\",\n  \"interrupted\",\n]);\nexport type RuntimeTaskStatus = typeof RuntimeTaskStatus.Type;\n\nconst TaskProgressPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  description: TrimmedNonEmptyStringSchema,\n  summary: Schema.optional(TrimmedNonEmptyStringSchema),\n  usage: Schema.optional(Schema.Unknown),\n  typedUsage: Schema.optional(RuntimeTaskUsage),\n  lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Present on synthesized member/child progress rows that carry state. */\n  status: Schema.optional(RuntimeTaskStatus),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n  ...taskAgentLinkageFields,\n});\nexport type TaskProgressPayload = typeof TaskProgressPayload.Type;\n\n/**\n * Non-terminal status patch (from the Claude SDK's task_updated, which main\n * previously dropped). killed→cancelled and paused→idle are mapped at the\n * adapter so the wire only carries the shared vocabulary.\n */\nconst TaskUpdatedPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  status: Schema.optional(RuntimeTaskStatus),\n  description: Schema.optional(TrimmedNonEmptyStringSchema),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n  endedAt: Schema.optional(IsoDateTime),\n  isBackgrounded: Schema.optional(Schema.Boolean),\n  ...taskAgentLinkageFields,\n});\nexport type TaskUpdatedPayload = typeof TaskUpdatedPayload.Type;\n\nconst TaskCompletedPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  status: Schema.Literals([\"completed\", \"failed\", \"stopped\"]),\n  summary: Schema.optional(TrimmedNonEmptyStringSchema),\n  usage: Schema.optional(Schema.Unknown),\n  typedUsage: Schema.optional(RuntimeTaskUsage),\n  ...taskAgentLinkageFields,\n});\nexport type TaskCompletedPayload = typeof TaskCompletedPayload.Type;\n\nconst HookStartedPayload = Schema.Struct({\n  hookId: TrimmedNonEmptyStringSchema,\n  hookName: TrimmedNonEmptyStringSchema,\n  hookEvent: TrimmedNonEmptyStringSchema,\n});\nexport type HookStartedPayload = typeof HookStartedPayload.Type;\n\nconst HookProgressPayload = Schema.Struct({\n  hookId: TrimmedNonEmptyStringSchema,\n  output: Schema.optional(Schema.String),\n  stdout: Schema.optional(Schema.String),\n  stderr: Schema.optional(Schema.String),\n});\nexport type HookProgressPayload = typeof HookProgressPayload.Type;\n\nconst HookCompletedPayload = Schema.Struct({\n  hookId: TrimmedNonEmptyStringSchema,\n  outcome: Schema.Literals([\"success\", \"error\", \"cancelled\"]),\n  output: Schema.optional(Schema.String),\n  stdout: Schema.optional(Schema.String),\n  stderr: Schema.optional(Schema.String),\n  exitCode: Schema.optional(Schema.Int),\n});\nexport type HookCompletedPayload = typeof HookCompletedPayload.Type;\n\nconst ToolProgressPayload = Schema.Struct({\n  toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n  toolName: Schema.optional(TrimmedNonEmptyStringSchema),\n  summary: Schema.optional(TrimmedNonEmptyStringSchema),\n  elapsedSeconds: Schema.optional(Schema.Number),\n  /** Owning task/agent when the tool ran inside a subagent. */\n  taskId: Schema.optional(RuntimeTaskId),\n  parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ToolProgressPayload = typeof ToolProgressPayload.Type;\n\nconst ToolSummaryPayload = Schema.Struct({\n  summary: TrimmedNonEmptyStringSchema,\n  precedingToolUseIds: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)),\n});\nexport type ToolSummaryPayload = typeof ToolSummaryPayload.Type;\n\nconst AuthStatusPayload = Schema.Struct({\n  isAuthenticating: Schema.optional(Schema.Boolean),\n  output: Schema.optional(Schema.Array(Schema.String)),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type AuthStatusPayload = typeof AuthStatusPayload.Type;\n\nconst AccountUpdatedPayload = Schema.Struct({\n  account: Schema.Unknown,\n});\nexport type AccountUpdatedPayload = typeof AccountUpdatedPayload.Type;\n\nconst AccountRateLimitsUpdatedPayload = Schema.Struct({\n  rateLimits: Schema.Unknown,\n});\nexport type AccountRateLimitsUpdatedPayload = typeof AccountRateLimitsUpdatedPayload.Type;\n\nconst McpStatusUpdatedPayload = Schema.Struct({\n  status: Schema.Unknown,\n});\nexport type McpStatusUpdatedPayload = typeof McpStatusUpdatedPayload.Type;\n\nconst McpOauthCompletedPayload = Schema.Struct({\n  success: Schema.Boolean,\n  name: Schema.optional(TrimmedNonEmptyStringSchema),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type McpOauthCompletedPayload = typeof McpOauthCompletedPayload.Type;\n\nconst ModelReroutedPayload = Schema.Struct({\n  fromModel: TrimmedNonEmptyStringSchema,\n  toModel: TrimmedNonEmptyStringSchema,\n  reason: TrimmedNonEmptyStringSchema,\n});\nexport type ModelReroutedPayload = typeof ModelReroutedPayload.Type;\n\nconst ConfigWarningPayload = Schema.Struct({\n  summary: TrimmedNonEmptyStringSchema,\n  details: Schema.optional(TrimmedNonEmptyStringSchema),\n  path: Schema.optional(TrimmedNonEmptyStringSchema),\n  range: Schema.optional(Schema.Unknown),\n});\nexport type ConfigWarningPayload = typeof ConfigWarningPayload.Type;\n\nconst DeprecationNoticePayload = Schema.Struct({\n  summary: TrimmedNonEmptyStringSchema,\n  details: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type DeprecationNoticePayload = typeof DeprecationNoticePayload.Type;\n\nconst FilesPersistedPayload = Schema.Struct({\n  files: Schema.Array(\n    Schema.Struct({\n      filename: TrimmedNonEmptyStringSchema,\n      fileId: TrimmedNonEmptyStringSchema,\n    }),\n  ),\n  failed: Schema.optional(\n    Schema.Array(\n      Schema.Struct({\n        filename: TrimmedNonEmptyStringSchema,\n        error: TrimmedNonEmptyStringSchema,\n      }),\n    ),\n  ),\n});\nexport type FilesPersistedPayload = typeof FilesPersistedPayload.Type;\n\nconst ToolDeniedPayload = Schema.Struct({\n  toolName: TrimmedNonEmptyStringSchema,\n  toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n  agentId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ToolDeniedPayload = typeof ToolDeniedPayload.Type;\n\nconst RuntimeWarningPayload = Schema.Struct({\n  message: TrimmedNonEmptyStringSchema,\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type RuntimeWarningPayload = typeof RuntimeWarningPayload.Type;\n\nconst RuntimeErrorPayload = Schema.Struct({\n  message: TrimmedNonEmptyStringSchema,\n  class: Schema.optional(RuntimeErrorClass),\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type RuntimeErrorPayload = typeof RuntimeErrorPayload.Type;\n\nconst ProviderRuntimeSessionStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionStartedType,\n  payload: SessionStartedPayload,\n});\nexport type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;\n\nconst ProviderRuntimeSessionConfiguredEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionConfiguredType,\n  payload: SessionConfiguredPayload,\n});\nexport type ProviderRuntimeSessionConfiguredEvent =\n  typeof ProviderRuntimeSessionConfiguredEvent.Type;\n\nconst ProviderRuntimeSessionStateChangedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionStateChangedType,\n  payload: SessionStateChangedPayload,\n});\nexport type ProviderRuntimeSessionStateChangedEvent =\n  typeof ProviderRuntimeSessionStateChangedEvent.Type;\n\nconst ProviderRuntimeSessionExitedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionExitedType,\n  payload: SessionExitedPayload,\n});\nexport type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;\n\nconst ProviderRuntimeThreadStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadStartedType,\n  payload: ThreadStartedPayload,\n});\nexport type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;\n\nconst ProviderRuntimeThreadStateChangedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadStateChangedType,\n  payload: ThreadStateChangedPayload,\n});\nexport type ProviderRuntimeThreadStateChangedEvent =\n  typeof ProviderRuntimeThreadStateChangedEvent.Type;\n\nconst ProviderRuntimeThreadMetadataUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadMetadataUpdatedType,\n  payload: ThreadMetadataUpdatedPayload,\n});\nexport type ProviderRuntimeThreadMetadataUpdatedEvent =\n  typeof ProviderRuntimeThreadMetadataUpdatedEvent.Type;\n\nconst ProviderRuntimeThreadTokenUsageUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadTokenUsageUpdatedType,\n  payload: ThreadTokenUsageUpdatedPayload,\n});\nexport type ProviderRuntimeThreadTokenUsageUpdatedEvent =\n  typeof ProviderRuntimeThreadTokenUsageUpdatedEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeStartedType,\n  payload: ThreadRealtimeStartedPayload,\n});\nexport type ProviderRuntimeThreadRealtimeStartedEvent =\n  typeof ProviderRuntimeThreadRealtimeStartedEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeItemAddedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeItemAddedType,\n  payload: ThreadRealtimeItemAddedPayload,\n});\nexport type ProviderRuntimeThreadRealtimeItemAddedEvent =\n  typeof ProviderRuntimeThreadRealtimeItemAddedEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeTranscriptDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeTranscriptDeltaType,\n  payload: ThreadRealtimeTranscriptDeltaPayload,\n});\nexport type ProviderRuntimeThreadRealtimeTranscriptDeltaEvent =\n  typeof ProviderRuntimeThreadRealtimeTranscriptDeltaEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeTranscriptDoneEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeTranscriptDoneType,\n  payload: ThreadRealtimeTranscriptDonePayload,\n});\nexport type ProviderRuntimeThreadRealtimeTranscriptDoneEvent =\n  typeof ProviderRuntimeThreadRealtimeTranscriptDoneEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeAudioDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeAudioDeltaType,\n  payload: ThreadRealtimeAudioDeltaPayload,\n});\nexport type ProviderRuntimeThreadRealtimeAudioDeltaEvent =\n  typeof ProviderRuntimeThreadRealtimeAudioDeltaEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeErrorEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeErrorType,\n  payload: ThreadRealtimeErrorPayload,\n});\nexport type ProviderRuntimeThreadRealtimeErrorEvent =\n  typeof ProviderRuntimeThreadRealtimeErrorEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeClosedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeClosedType,\n  payload: ThreadRealtimeClosedPayload,\n});\nexport type ProviderRuntimeThreadRealtimeClosedEvent =\n  typeof ProviderRuntimeThreadRealtimeClosedEvent.Type;\n\nconst ProviderRuntimeTurnStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnStartedType,\n  payload: TurnStartedPayload,\n});\nexport type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;\n\nconst ProviderRuntimeTurnCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnCompletedType,\n  payload: TurnCompletedPayload,\n});\nexport type ProviderRuntimeTurnCompletedEvent = typeof ProviderRuntimeTurnCompletedEvent.Type;\n\nconst ProviderRuntimeTurnAbortedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnAbortedType,\n  payload: TurnAbortedPayload,\n});\nexport type ProviderRuntimeTurnAbortedEvent = typeof ProviderRuntimeTurnAbortedEvent.Type;\n\nconst ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnPlanUpdatedType,\n  payload: TurnPlanUpdatedPayload,\n});\nexport type ProviderRuntimeTurnPlanUpdatedEvent = typeof ProviderRuntimeTurnPlanUpdatedEvent.Type;\n\nconst ProviderRuntimeTurnProposedDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnProposedDeltaType,\n  payload: TurnProposedDeltaPayload,\n});\nexport type ProviderRuntimeTurnProposedDeltaEvent =\n  typeof ProviderRuntimeTurnProposedDeltaEvent.Type;\n\nconst ProviderRuntimeTurnProposedCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnProposedCompletedType,\n  payload: TurnProposedCompletedPayload,\n});\nexport type ProviderRuntimeTurnProposedCompletedEvent =\n  typeof ProviderRuntimeTurnProposedCompletedEvent.Type;\n\nconst ProviderRuntimeTurnDiffUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnDiffUpdatedType,\n  payload: TurnDiffUpdatedPayload,\n});\nexport type ProviderRuntimeTurnDiffUpdatedEvent = typeof ProviderRuntimeTurnDiffUpdatedEvent.Type;\n\nconst ProviderRuntimeItemStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ItemStartedType,\n  payload: ItemLifecyclePayload,\n});\nexport type ProviderRuntimeItemStartedEvent = typeof ProviderRuntimeItemStartedEvent.Type;\n\nconst ProviderRuntimeItemUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ItemUpdatedType,\n  payload: ItemLifecyclePayload,\n});\nexport type ProviderRuntimeItemUpdatedEvent = typeof ProviderRuntimeItemUpdatedEvent.Type;\n\nconst ProviderRuntimeItemCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ItemCompletedType,\n  payload: ItemLifecyclePayload,\n});\nexport type ProviderRuntimeItemCompletedEvent = typeof ProviderRuntimeItemCompletedEvent.Type;\n\nconst ProviderRuntimeContentDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ContentDeltaType,\n  payload: ContentDeltaPayload,\n});\nexport type ProviderRuntimeContentDeltaEvent = typeof ProviderRuntimeContentDeltaEvent.Type;\n\nconst ProviderRuntimeRequestOpenedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RequestOpenedType,\n  payload: RequestOpenedPayload,\n});\nexport type ProviderRuntimeRequestOpenedEvent = typeof ProviderRuntimeRequestOpenedEvent.Type;\n\nconst ProviderRuntimeRequestResolvedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RequestResolvedType,\n  payload: RequestResolvedPayload,\n});\nexport type ProviderRuntimeRequestResolvedEvent = typeof ProviderRuntimeRequestResolvedEvent.Type;\n\nconst ProviderRuntimeUserInputRequestedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: UserInputRequestedType,\n  payload: UserInputRequestedPayload,\n});\nexport type ProviderRuntimeUserInputRequestedEvent =\n  typeof ProviderRuntimeUserInputRequestedEvent.Type;\n\nconst ProviderRuntimeUserInputResolvedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: UserInputResolvedType,\n  payload: UserInputResolvedPayload,\n});\nexport type ProviderRuntimeUserInputResolvedEvent =\n  typeof ProviderRuntimeUserInputResolvedEvent.Type;\n\nconst ProviderRuntimeTaskStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskStartedType,\n  payload: TaskStartedPayload,\n});\nexport type ProviderRuntimeTaskStartedEvent = typeof ProviderRuntimeTaskStartedEvent.Type;\n\nconst ProviderRuntimeTaskProgressEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskProgressType,\n  payload: TaskProgressPayload,\n});\nexport type ProviderRuntimeTaskProgressEvent = typeof ProviderRuntimeTaskProgressEvent.Type;\n\nconst ProviderRuntimeTaskUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskUpdatedType,\n  payload: TaskUpdatedPayload,\n});\nexport type ProviderRuntimeTaskUpdatedEvent = typeof ProviderRuntimeTaskUpdatedEvent.Type;\n\nconst ProviderRuntimeTaskCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskCompletedType,\n  payload: TaskCompletedPayload,\n});\nexport type ProviderRuntimeTaskCompletedEvent = typeof ProviderRuntimeTaskCompletedEvent.Type;\n\nconst ProviderRuntimeHookStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: HookStartedType,\n  payload: HookStartedPayload,\n});\nexport type ProviderRuntimeHookStartedEvent = typeof ProviderRuntimeHookStartedEvent.Type;\n\nconst ProviderRuntimeHookProgressEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: HookProgressType,\n  payload: HookProgressPayload,\n});\nexport type ProviderRuntimeHookProgressEvent = typeof ProviderRuntimeHookProgressEvent.Type;\n\nconst ProviderRuntimeHookCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: HookCompletedType,\n  payload: HookCompletedPayload,\n});\nexport type ProviderRuntimeHookCompletedEvent = typeof ProviderRuntimeHookCompletedEvent.Type;\n\nconst ProviderRuntimeToolProgressEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ToolProgressType,\n  payload: ToolProgressPayload,\n});\nexport type ProviderRuntimeToolProgressEvent = typeof ProviderRuntimeToolProgressEvent.Type;\n\nconst ProviderRuntimeToolSummaryEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ToolSummaryType,\n  payload: ToolSummaryPayload,\n});\nexport type ProviderRuntimeToolSummaryEvent = typeof ProviderRuntimeToolSummaryEvent.Type;\n\nconst ProviderRuntimeAuthStatusEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: AuthStatusType,\n  payload: AuthStatusPayload,\n});\nexport type ProviderRuntimeAuthStatusEvent = typeof ProviderRuntimeAuthStatusEvent.Type;\n\nconst ProviderRuntimeAccountUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: AccountUpdatedType,\n  payload: AccountUpdatedPayload,\n});\nexport type ProviderRuntimeAccountUpdatedEvent = typeof ProviderRuntimeAccountUpdatedEvent.Type;\n\nconst ProviderRuntimeAccountRateLimitsUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: AccountRateLimitsUpdatedType,\n  payload: AccountRateLimitsUpdatedPayload,\n});\nexport type ProviderRuntimeAccountRateLimitsUpdatedEvent =\n  typeof ProviderRuntimeAccountRateLimitsUpdatedEvent.Type;\n\nconst ProviderRuntimeMcpStatusUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: McpStatusUpdatedType,\n  payload: McpStatusUpdatedPayload,\n});\nexport type ProviderRuntimeMcpStatusUpdatedEvent = typeof ProviderRuntimeMcpStatusUpdatedEvent.Type;\n\nconst ProviderRuntimeMcpOauthCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: McpOauthCompletedType,\n  payload: McpOauthCompletedPayload,\n});\nexport type ProviderRuntimeMcpOauthCompletedEvent =\n  typeof ProviderRuntimeMcpOauthCompletedEvent.Type;\n\nconst ProviderRuntimeModelReroutedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ModelReroutedType,\n  payload: ModelReroutedPayload,\n});\nexport type ProviderRuntimeModelReroutedEvent = typeof ProviderRuntimeModelReroutedEvent.Type;\n\nconst ProviderRuntimeConfigWarningEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ConfigWarningType,\n  payload: ConfigWarningPayload,\n});\nexport type ProviderRuntimeConfigWarningEvent = typeof ProviderRuntimeConfigWarningEvent.Type;\n\nconst ProviderRuntimeDeprecationNoticeEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: DeprecationNoticeType,\n  payload: DeprecationNoticePayload,\n});\nexport type ProviderRuntimeDeprecationNoticeEvent =\n  typeof ProviderRuntimeDeprecationNoticeEvent.Type;\n\nconst ProviderRuntimeFilesPersistedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: FilesPersistedType,\n  payload: FilesPersistedPayload,\n});\nexport type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;\n\nconst ProviderRuntimeToolDeniedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ToolDeniedType,\n  payload: ToolDeniedPayload,\n});\nexport type ProviderRuntimeToolDeniedEvent = typeof ProviderRuntimeToolDeniedEvent.Type;\n\nconst ProviderRuntimeWarningEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RuntimeWarningType,\n  payload: RuntimeWarningPayload,\n});\nexport type ProviderRuntimeWarningEvent = typeof ProviderRuntimeWarningEvent.Type;\n\nconst ProviderRuntimeErrorEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RuntimeErrorType,\n  payload: RuntimeErrorPayload,\n});\nexport type ProviderRuntimeErrorEvent = typeof ProviderRuntimeErrorEvent.Type;\n\nexport const ProviderRuntimeEventV2 = Schema.Union([\n  ProviderRuntimeSessionStartedEvent,\n  ProviderRuntimeSessionConfiguredEvent,\n  ProviderRuntimeSessionStateChangedEvent,\n  ProviderRuntimeSessionExitedEvent,\n  ProviderRuntimeThreadStartedEvent,\n  ProviderRuntimeThreadStateChangedEvent,\n  ProviderRuntimeThreadMetadataUpdatedEvent,\n  ProviderRuntimeThreadTokenUsageUpdatedEvent,\n  ProviderRuntimeThreadRealtimeStartedEvent,\n  ProviderRuntimeThreadRealtimeItemAddedEvent,\n  ProviderRuntimeThreadRealtimeTranscriptDeltaEvent,\n  ProviderRuntimeThreadRealtimeTranscriptDoneEvent,\n  ProviderRuntimeThreadRealtimeAudioDeltaEvent,\n  ProviderRuntimeThreadRealtimeErrorEvent,\n  ProviderRuntimeThreadRealtimeClosedEvent,\n  ProviderRuntimeTurnStartedEvent,\n  ProviderRuntimeTurnCompletedEvent,\n  ProviderRuntimeTurnAbortedEvent,\n  ProviderRuntimeTurnPlanUpdatedEvent,\n  ProviderRuntimeTurnProposedDeltaEvent,\n  ProviderRuntimeTurnProposedCompletedEvent,\n  ProviderRuntimeTurnDiffUpdatedEvent,\n  ProviderRuntimeItemStartedEvent,\n  ProviderRuntimeItemUpdatedEvent,\n  ProviderRuntimeItemCompletedEvent,\n  ProviderRuntimeContentDeltaEvent,\n  ProviderRuntimeRequestOpenedEvent,\n  ProviderRuntimeRequestResolvedEvent,\n  ProviderRuntimeUserInputRequestedEvent,\n  ProviderRuntimeUserInputResolvedEvent,\n  ProviderRuntimeTaskStartedEvent,\n  ProviderRuntimeTaskProgressEvent,\n  ProviderRuntimeTaskUpdatedEvent,\n  ProviderRuntimeTaskCompletedEvent,\n  ProviderRuntimeHookStartedEvent,\n  ProviderRuntimeHookProgressEvent,\n  ProviderRuntimeHookCompletedEvent,\n  ProviderRuntimeToolProgressEvent,\n  ProviderRuntimeToolSummaryEvent,\n  ProviderRuntimeAuthStatusEvent,\n  ProviderRuntimeAccountUpdatedEvent,\n  ProviderRuntimeAccountRateLimitsUpdatedEvent,\n  ProviderRuntimeMcpStatusUpdatedEvent,\n  ProviderRuntimeMcpOauthCompletedEvent,\n  ProviderRuntimeModelReroutedEvent,\n  ProviderRuntimeConfigWarningEvent,\n  ProviderRuntimeDeprecationNoticeEvent,\n  ProviderRuntimeFilesPersistedEvent,\n  ProviderRuntimeToolDeniedEvent,\n  ProviderRuntimeWarningEvent,\n  ProviderRuntimeErrorEvent,\n]);\nexport type ProviderRuntimeEventV2 = typeof ProviderRuntimeEventV2.Type;\n\nexport const ProviderRuntimeEvent = ProviderRuntimeEventV2;\nexport type ProviderRuntimeEvent = ProviderRuntimeEventV2;\n\n// Compatibility aliases for call sites still importing legacy names.\nconst ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;\nexport type ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;\nconst ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;\nexport type ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;\nconst ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;\nexport type ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;\nconst ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;\nexport type ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;\nconst ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;\nexport type ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;\nconst ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;\nexport type ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;\n\n// Legacy helper aliases retained for adapters/tests.\nconst ProviderRuntimeToolKind = Schema.Literals([\"command\", \"file-read\", \"file-change\", \"other\"]);\nexport type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;\n\nexport const ProviderRuntimeTurnStatus = RuntimeTurnState;\nexport type ProviderRuntimeTurnStatus = RuntimeTurnState;\n","import * as Schema from \"effect/Schema\";\nimport { ForwardCompatibleArray, TrimmedString } from \"./baseSchemas.ts\";\n\nexport const MAX_KEYBINDING_VALUE_LENGTH = 64;\nexport const MAX_KEYBINDING_WHEN_LENGTH = 256;\nexport const MAX_WHEN_EXPRESSION_DEPTH = 64;\nexport const MAX_SCRIPT_ID_LENGTH = 24;\nexport const MAX_KEYBINDINGS_COUNT = 256;\n\nexport const THREAD_JUMP_KEYBINDING_COMMANDS = [\n  \"thread.jump.1\",\n  \"thread.jump.2\",\n  \"thread.jump.3\",\n  \"thread.jump.4\",\n  \"thread.jump.5\",\n  \"thread.jump.6\",\n  \"thread.jump.7\",\n  \"thread.jump.8\",\n  \"thread.jump.9\",\n] as const;\nexport type ThreadJumpKeybindingCommand = (typeof THREAD_JUMP_KEYBINDING_COMMANDS)[number];\n\nexport const MODEL_PICKER_JUMP_KEYBINDING_COMMANDS = [\n  \"modelPicker.jump.1\",\n  \"modelPicker.jump.2\",\n  \"modelPicker.jump.3\",\n  \"modelPicker.jump.4\",\n  \"modelPicker.jump.5\",\n  \"modelPicker.jump.6\",\n  \"modelPicker.jump.7\",\n  \"modelPicker.jump.8\",\n  \"modelPicker.jump.9\",\n] as const;\nexport type ModelPickerJumpKeybindingCommand =\n  (typeof MODEL_PICKER_JUMP_KEYBINDING_COMMANDS)[number];\n\nexport const THREAD_KEYBINDING_COMMANDS = [\n  \"thread.previous\",\n  \"thread.next\",\n  ...THREAD_JUMP_KEYBINDING_COMMANDS,\n] as const;\nexport type ThreadKeybindingCommand = (typeof THREAD_KEYBINDING_COMMANDS)[number];\n\nexport const MODEL_PICKER_KEYBINDING_COMMANDS = [\n  \"modelPicker.toggle\",\n  ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,\n] as const;\nexport type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];\n\nconst STATIC_KEYBINDING_COMMANDS = [\n  \"sidebar.toggle\",\n  \"terminal.toggle\",\n  \"terminal.split\",\n  \"terminal.splitVertical\",\n  \"terminal.new\",\n  \"terminal.close\",\n  \"rightPanel.toggle\",\n  \"diff.toggle\",\n  \"preview.toggle\",\n  \"preview.refresh\",\n  \"preview.focusUrl\",\n  \"preview.zoomIn\",\n  \"preview.zoomOut\",\n  \"preview.resetZoom\",\n  \"commandPalette.toggle\",\n  \"filePicker.toggle\",\n  \"projectSearch.toggle\",\n  \"composer.stash\",\n  \"chat.new\",\n  \"chat.newLocal\",\n  \"editor.openFavorite\",\n  ...MODEL_PICKER_KEYBINDING_COMMANDS,\n  ...THREAD_KEYBINDING_COMMANDS,\n] as const;\n\nexport const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([\n  Schema.Literal(\"script.\"),\n  Schema.NonEmptyString.check(\n    Schema.isMaxLength(MAX_SCRIPT_ID_LENGTH),\n    Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),\n  ),\n  Schema.Literal(\".run\"),\n]);\n\nexport const KeybindingCommand = Schema.Union([\n  Schema.Literals(STATIC_KEYBINDING_COMMANDS),\n  SCRIPT_RUN_COMMAND_PATTERN,\n]);\nexport type KeybindingCommand = typeof KeybindingCommand.Type;\n\nexport const KeybindingValue = TrimmedString.check(\n  Schema.isMinLength(1),\n  Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),\n);\n\nexport const KeybindingWhen = TrimmedString.check(\n  Schema.isMinLength(1),\n  Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),\n);\nexport const KeybindingRule = Schema.Struct({\n  key: KeybindingValue,\n  command: KeybindingCommand,\n  when: Schema.optional(KeybindingWhen),\n});\nexport type KeybindingRule = typeof KeybindingRule.Type;\n\nexport const KeybindingsConfig = Schema.Array(KeybindingRule).check(\n  Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),\n);\nexport type KeybindingsConfig = typeof KeybindingsConfig.Type;\n\nexport const KeybindingShortcut = Schema.Struct({\n  key: KeybindingValue,\n  metaKey: Schema.Boolean,\n  ctrlKey: Schema.Boolean,\n  shiftKey: Schema.Boolean,\n  altKey: Schema.Boolean,\n  modKey: Schema.Boolean,\n});\nexport type KeybindingShortcut = typeof KeybindingShortcut.Type;\n\nconst KeybindingWhenNodeRef = Schema.suspend(\n  (): Schema.Codec<KeybindingWhenNode> => KeybindingWhenNode,\n);\nexport const KeybindingWhenNode = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"identifier\"),\n    name: Schema.NonEmptyString,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"not\"),\n    node: KeybindingWhenNodeRef,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"and\"),\n    left: KeybindingWhenNodeRef,\n    right: KeybindingWhenNodeRef,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"or\"),\n    left: KeybindingWhenNodeRef,\n    right: KeybindingWhenNodeRef,\n  }),\n]);\nexport type KeybindingWhenNode =\n  | { type: \"identifier\"; name: string }\n  | { type: \"not\"; node: KeybindingWhenNode }\n  | { type: \"and\"; left: KeybindingWhenNode; right: KeybindingWhenNode }\n  | { type: \"or\"; left: KeybindingWhenNode; right: KeybindingWhenNode };\n\nexport const ResolvedKeybindingRule = Schema.Struct({\n  command: KeybindingCommand,\n  shortcut: KeybindingShortcut,\n  whenAst: Schema.optional(KeybindingWhenNode),\n}).annotate({ parseOptions: { onExcessProperty: \"ignore\" } });\nexport type ResolvedKeybindingRule = typeof ResolvedKeybindingRule.Type;\n\n/**\n * The command set grows over time, so a client may receive rules it cannot\n * represent (a command or `when` node added after that client shipped).\n * Decoding drops those rules instead of failing the whole payload —\n * rejecting the config would take down the connection over a shortcut the\n * client couldn't dispatch anyway.\n */\nexport const ResolvedKeybindingsConfig = ForwardCompatibleArray(ResolvedKeybindingRule).check(\n  Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),\n);\nexport type ResolvedKeybindingsConfig = typeof ResolvedKeybindingsConfig.Type;\n\nexport class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(\n  \"KeybindingsConfigParseError\",\n  {\n    configPath: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const EditorLaunchStyle = Schema.Literals([\"direct-path\", \"goto\", \"line-column\"]);\nexport type EditorLaunchStyle = typeof EditorLaunchStyle.Type;\n\ntype EditorDefinition = {\n  readonly id: string;\n  readonly label: string;\n  readonly commands: readonly [string, ...string[]] | null;\n  readonly baseArgs?: readonly string[];\n  readonly launchStyle: EditorLaunchStyle;\n};\n\nexport const EDITORS = [\n  { id: \"cursor\", label: \"Cursor\", commands: [\"cursor\"], launchStyle: \"goto\" },\n  { id: \"trae\", label: \"Trae\", commands: [\"trae\"], launchStyle: \"goto\" },\n  { id: \"kiro\", label: \"Kiro\", commands: [\"kiro\"], baseArgs: [\"ide\"], launchStyle: \"goto\" },\n  { id: \"vscode\", label: \"VS Code\", commands: [\"code\"], launchStyle: \"goto\" },\n  {\n    id: \"vscode-insiders\",\n    label: \"VS Code Insiders\",\n    commands: [\"code-insiders\"],\n    launchStyle: \"goto\",\n  },\n  { id: \"vscodium\", label: \"VSCodium\", commands: [\"codium\"], launchStyle: \"goto\" },\n  { id: \"zed\", label: \"Zed\", commands: [\"zed\", \"zeditor\"], launchStyle: \"direct-path\" },\n  { id: \"antigravity\", label: \"Antigravity\", commands: [\"agy\"], launchStyle: \"goto\" },\n  { id: \"idea\", label: \"IntelliJ IDEA\", commands: [\"idea\"], launchStyle: \"line-column\" },\n  { id: \"aqua\", label: \"Aqua\", commands: [\"aqua\"], launchStyle: \"line-column\" },\n  { id: \"clion\", label: \"CLion\", commands: [\"clion\"], launchStyle: \"line-column\" },\n  { id: \"datagrip\", label: \"DataGrip\", commands: [\"datagrip\"], launchStyle: \"line-column\" },\n  { id: \"dataspell\", label: \"DataSpell\", commands: [\"dataspell\"], launchStyle: \"line-column\" },\n  { id: \"goland\", label: \"GoLand\", commands: [\"goland\"], launchStyle: \"line-column\" },\n  { id: \"phpstorm\", label: \"PhpStorm\", commands: [\"phpstorm\"], launchStyle: \"line-column\" },\n  { id: \"pycharm\", label: \"PyCharm\", commands: [\"pycharm\"], launchStyle: \"line-column\" },\n  { id: \"rider\", label: \"Rider\", commands: [\"rider\"], launchStyle: \"line-column\" },\n  { id: \"rubymine\", label: \"RubyMine\", commands: [\"rubymine\"], launchStyle: \"line-column\" },\n  { id: \"rustrover\", label: \"RustRover\", commands: [\"rustrover\"], launchStyle: \"line-column\" },\n  { id: \"webstorm\", label: \"WebStorm\", commands: [\"webstorm\"], launchStyle: \"line-column\" },\n  { id: \"file-manager\", label: \"File Manager\", commands: null, launchStyle: \"direct-path\" },\n] as const satisfies ReadonlyArray<EditorDefinition>;\n\nexport const EditorId = Schema.Literals(EDITORS.map((e) => e.id));\nexport type EditorId = typeof EditorId.Type;\n\nexport const LaunchEditorInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  editor: EditorId,\n});\nexport type LaunchEditorInput = typeof LaunchEditorInput.Type;\n\nexport class ExternalLauncherUnknownEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnknownEditorError>()(\n  \"ExternalLauncherUnknownEditorError\",\n  {\n    editor: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Unknown editor: ${this.editor}`;\n  }\n}\n\nexport class ExternalLauncherUnsupportedEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnsupportedEditorError>()(\n  \"ExternalLauncherUnsupportedEditorError\",\n  {\n    editor: EditorId,\n  },\n) {\n  override get message(): string {\n    return `Unsupported editor: ${this.editor}`;\n  }\n}\n\nexport class ExternalLauncherCommandNotFoundError extends Schema.TaggedErrorClass<ExternalLauncherCommandNotFoundError>()(\n  \"ExternalLauncherCommandNotFoundError\",\n  {\n    editor: EditorId,\n    command: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Editor command not found: ${this.command}`;\n  }\n}\n\nconst ExternalLauncherSpawnFields = {\n  command: Schema.String,\n  args: Schema.Array(Schema.String),\n  cause: Schema.Defect(),\n};\n\nexport class ExternalLauncherBrowserSpawnError extends Schema.TaggedErrorClass<ExternalLauncherBrowserSpawnError>()(\n  \"ExternalLauncherBrowserSpawnError\",\n  {\n    ...ExternalLauncherSpawnFields,\n    target: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Failed to launch browser target '${this.target}' with '${[this.command, ...this.args].join(\" \")}'`;\n  }\n}\n\nexport class ExternalLauncherEditorSpawnError extends Schema.TaggedErrorClass<ExternalLauncherEditorSpawnError>()(\n  \"ExternalLauncherEditorSpawnError\",\n  {\n    ...ExternalLauncherSpawnFields,\n    editor: EditorId,\n    target: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Failed to launch '${this.target}' in ${this.editor} with '${[this.command, ...this.args].join(\" \")}'`;\n  }\n}\n\nexport const ExternalLauncherError = Schema.Union([\n  ExternalLauncherUnknownEditorError,\n  ExternalLauncherUnsupportedEditorError,\n  ExternalLauncherCommandNotFoundError,\n  ExternalLauncherBrowserSpawnError,\n  ExternalLauncherEditorSpawnError,\n]);\nexport type ExternalLauncherError = typeof ExternalLauncherError.Type;\n\nexport const isExternalLauncherError = Schema.is(ExternalLauncherError);\n","import * as Effect from \"effect/Effect\";\nimport * as Duration from \"effect/Duration\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport { TrimmedNonEmptyString, TrimmedString } from \"./baseSchemas.ts\";\nimport {\n  DEFAULT_TEXT_GENERATION_MODEL,\n  DEFAULT_TEXT_GENERATION_REASONING_EFFORT,\n  ProviderOptionSelections,\n} from \"./model.ts\";\nimport { ModelSelection } from \"./orchestration.ts\";\nimport { ProviderInstanceConfig, ProviderInstanceId } from \"./providerInstance.ts\";\n\n// ── Client Settings (local-only) ───────────────────────────────\n\nexport const TimestampFormat = Schema.Literals([\"locale\", \"12-hour\", \"24-hour\"]);\nexport type TimestampFormat = typeof TimestampFormat.Type;\nexport const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = \"locale\";\n\nexport const SidebarProjectSortOrder = Schema.Literals([\"updated_at\", \"created_at\", \"manual\"]);\nexport type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;\nexport const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = \"updated_at\";\n\nexport const SidebarThreadSortOrder = Schema.Literals([\"updated_at\", \"created_at\"]);\nexport type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;\nexport const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = \"updated_at\";\n\nexport const SidebarProjectGroupingMode = Schema.Literals([\n  \"repository\",\n  \"repository_path\",\n  \"separate\",\n]);\nexport type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;\nexport const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = \"repository\";\nexport const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1;\nexport const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15;\nexport const SidebarThreadPreviewCount = Schema.Int.check(\n  Schema.isBetween({\n    minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT,\n    maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT,\n  }),\n);\nexport type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;\nexport const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;\nexport const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;\nexport const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;\nexport const SidebarAutoSettleAfterDays = Schema.Number.check(\n  Schema.isBetween({\n    minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,\n    maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,\n  }),\n);\nexport type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;\nexport const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3;\nexport const MIN_GLASS_OPACITY = 40;\nexport const MAX_GLASS_OPACITY = 100;\nexport const GlassOpacity = Schema.Int.check(\n  Schema.isBetween({\n    minimum: MIN_GLASS_OPACITY,\n    maximum: MAX_GLASS_OPACITY,\n  }),\n);\nexport type GlassOpacity = typeof GlassOpacity.Type;\nexport const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;\n/**\n * Font size preferences, in CSS pixels. The ranges are deliberately narrow:\n * the interface size scales every rem-based dimension in the app, so the\n * bounds keep layouts intact rather than offering unusable extremes.\n */\nexport const MIN_INTERFACE_FONT_SIZE = 12;\nexport const MAX_INTERFACE_FONT_SIZE = 20;\nexport const InterfaceFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_INTERFACE_FONT_SIZE, maximum: MAX_INTERFACE_FONT_SIZE }),\n);\nexport type InterfaceFontSize = typeof InterfaceFontSize.Type;\nexport const DEFAULT_INTERFACE_FONT_SIZE: InterfaceFontSize = 16;\n\nexport const MIN_PROMPT_FONT_SIZE = 12;\nexport const MAX_PROMPT_FONT_SIZE = 20;\nexport const PromptFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_PROMPT_FONT_SIZE, maximum: MAX_PROMPT_FONT_SIZE }),\n);\nexport type PromptFontSize = typeof PromptFontSize.Type;\nexport const DEFAULT_PROMPT_FONT_SIZE: PromptFontSize = 14;\n\nexport const MIN_CODE_FONT_SIZE = 10;\nexport const MAX_CODE_FONT_SIZE = 18;\nexport const CodeFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_CODE_FONT_SIZE, maximum: MAX_CODE_FONT_SIZE }),\n);\nexport type CodeFontSize = typeof CodeFontSize.Type;\nexport const DEFAULT_CODE_FONT_SIZE: CodeFontSize = 13;\n\nexport const MIN_TERMINAL_FONT_SIZE = 8;\nexport const MAX_TERMINAL_FONT_SIZE = 20;\nexport const TerminalFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_TERMINAL_FONT_SIZE, maximum: MAX_TERMINAL_FONT_SIZE }),\n);\nexport type TerminalFontSize = typeof TerminalFontSize.Type;\nexport const DEFAULT_TERMINAL_FONT_SIZE: TerminalFontSize = 12;\n\nexport const EnvironmentIdentificationMode = Schema.Literals([\"artwork\", \"pill\", \"none\"]);\nexport type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;\nexport const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = \"artwork\";\n\nexport const ClientLanguage = Schema.Literals([\"system\", \"en\", \"zh-CN\"]);\nexport type ClientLanguage = typeof ClientLanguage.Type;\nexport const DEFAULT_CLIENT_LANGUAGE: ClientLanguage = \"system\";\n\n/**\n * A user-chosen font family (a single name or a comma-separated list). Empty\n * means \"use the app default\"; clients compose their own fallback stacks.\n */\nexport const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));\nexport type FontFamilyPreference = typeof FontFamilyPreference.Type;\n\nexport const ClientSettingsSchema = Schema.Struct({\n  autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  language: ClientLanguage.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_CLIENT_LANGUAGE))),\n  confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(\n    Schema.withDecodingDefault(Effect.succeed([])),\n  ),\n  diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  environmentIdentificationMode: EnvironmentIdentificationMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),\n  ),\n  glassOpacity: GlassOpacity.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),\n  ),\n  fontSizeInterface: InterfaceFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)),\n  ),\n  fontSizePrompt: PromptFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROMPT_FONT_SIZE)),\n  ),\n  fontSizeCode: CodeFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_CODE_FONT_SIZE)),\n  ),\n  fontSizeTerminal: TerminalFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_FONT_SIZE)),\n  ),\n  fontFamilyCode: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  fontFamilyComposer: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  fontFamilySans: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  fontFamilyTerminal: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  // Grayscale `-webkit-font-smoothing: antialiased` (thinner strokes);\n  // disabling restores the platform's heavier default. No effect off macOS.\n  fontSmoothing: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  // Model favorites. Historically keyed by provider kind, now\n  // widened to `ProviderInstanceId` so users can favorite a specific model\n  // on a custom provider instance (e.g. \"Codex Personal · gpt-5\") without\n  // the UI collapsing it into the same bucket as the default Codex. The\n  // widening is backward-compatible by construction: prior provider-kind\n  // strings satisfy the `ProviderInstanceId` slug schema, so previously\n  // persisted favorites decode unchanged and continue to point at the\n  // default instance for their kind (because `defaultInstanceIdForDriver(kind)`\n  // uses the same slug). The field name is kept as `provider` for storage\n  // stability; new call sites should treat the value as an instance id.\n  favorites: Schema.Array(\n    Schema.Struct({\n      provider: ProviderInstanceId,\n      model: TrimmedNonEmptyString,\n    }),\n  ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n  providerModelPreferences: Schema.Record(\n    ProviderInstanceId,\n    Schema.Struct({\n      hiddenModels: Schema.Array(Schema.String).pipe(\n        Schema.withDecodingDefault(Effect.succeed([])),\n      ),\n      modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n    }),\n  ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),\n  ),\n  sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),\n  ),\n  sidebarProjectGroupingOverrides: Schema.Record(\n    TrimmedNonEmptyString,\n    SidebarProjectGroupingMode,\n  ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),\n  ),\n  sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),\n  ),\n  sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),\n  ),\n  sidebarV2Enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  // Whether `sidebarV2Enabled` reflects an explicit choice in Settings → Beta.\n  // Client settings persist as a whole blob, so every user who has ever touched\n  // any setting already has `sidebarV2Enabled: false` stored — without this bit\n  // there is no way to tell that apart from \"left alone\", and a channel-derived\n  // default could never reach them. Mirrors `updateChannelConfiguredByUser`.\n  sidebarV2ConfiguredByUser: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  timestampFormat: TimestampFormat.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),\n  ),\n  wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n});\nexport type ClientSettings = typeof ClientSettingsSchema.Type;\n\nexport const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});\n\n// ── Server Settings (server-authoritative) ────────────────────\n\nexport const ThreadEnvMode = Schema.Literals([\"local\", \"worktree\"]);\nexport type ThreadEnvMode = typeof ThreadEnvMode.Type;\n\nconst makeBinaryPathSetting = (fallback: string) =>\n  TrimmedString.pipe(\n    Schema.decodeTo(\n      Schema.String,\n      SchemaTransformation.transformOrFail({\n        decode: (value) => Effect.succeed(value || fallback),\n        encode: (value) => Effect.succeed(value),\n      }),\n    ),\n    Schema.withDecodingDefault(Effect.succeed(fallback)),\n  );\n\nexport type ProviderSettingsFormControl = \"text\" | \"password\" | \"textarea\" | \"switch\";\n\nexport interface ProviderSettingsFormAnnotation {\n  readonly control?: ProviderSettingsFormControl | undefined;\n  readonly placeholder?: string | undefined;\n  readonly hidden?: boolean | undefined;\n  readonly clearWhenEmpty?: \"omit\" | \"persist\" | undefined;\n}\n\nexport interface ProviderSettingsFormSchemaAnnotation {\n  readonly order?: readonly string[] | undefined;\n}\n\ndeclare module \"effect/Schema\" {\n  namespace Annotations {\n    interface Annotations {\n      readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;\n      readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;\n    }\n  }\n}\n\nexport type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<\n  keyof Fields,\n  string\n>[];\n\nexport function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(\n  fields: Fields,\n  options?: {\n    readonly order?: ProviderSettingsOrder<Fields> | undefined;\n  },\n): Schema.Struct<Fields> {\n  return Schema.Struct(fields).pipe(\n    Schema.annotate({\n      providerSettingsFormSchema:\n        options?.order === undefined ? undefined : { order: options.order },\n    }),\n  );\n}\n\nexport const CodexSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(true)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"codex\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the Codex binary used by this instance.\",\n        providerSettingsForm: { placeholder: \"codex\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    homePath: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"CODEX_HOME path\",\n        description: \"Custom Codex home and config directory.\",\n        providerSettingsForm: {\n          placeholder: \"~/.codex\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    shadowHomePath: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Shadow home path\",\n        description:\n          \"Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.\",\n        providerSettingsForm: {\n          placeholder: \"~/.codex-t3/personal\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    launchArgs: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Launch arguments\",\n        description: \"Additional CLI arguments passed to codex app-server on session start.\",\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n  },\n  {\n    order: [\"binaryPath\", \"homePath\", \"shadowHomePath\", \"launchArgs\"],\n  },\n);\nexport type CodexSettings = typeof CodexSettings.Type;\n\nexport const ClaudeSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(true)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"claude\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the Claude binary used by this instance.\",\n        providerSettingsForm: { placeholder: \"claude\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    homePath: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"CLAUDE_CONFIG_DIR path\",\n        description:\n          \"Custom Claude home and config directory. Keeps .claude.json and .claude separate.\",\n        providerSettingsForm: { placeholder: \"~/.claude\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    launchArgs: Schema.String.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Launch arguments\",\n        description: \"Additional CLI arguments passed on session start.\",\n        providerSettingsForm: {\n          placeholder: \"e.g. --chrome\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n  },\n  {\n    order: [\"binaryPath\", \"homePath\", \"launchArgs\"],\n  },\n);\nexport type ClaudeSettings = typeof ClaudeSettings.Type;\n\n/**\n * Shared shape for ACP-based agents (agentlink fork additions): Gemini CLI,\n * Qwen Code, Kimi CLI, JoyCode. Each only needs an enable switch, a binary path, and\n * a custom-model list — everything else is negotiated over ACP at runtime.\n */\nconst makeAcpAgentSettingsSchema = (input: {\n  readonly binaryFallback: string;\n  readonly binaryTitle: string;\n  readonly binaryDescription: string;\n}) =>\n  makeProviderSettingsSchema(\n    {\n      enabled: Schema.Boolean.pipe(\n        Schema.withDecodingDefault(Effect.succeed(false)),\n        Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n      ),\n      binaryPath: makeBinaryPathSetting(input.binaryFallback).pipe(\n        Schema.annotateKey({\n          title: input.binaryTitle,\n          description: input.binaryDescription,\n          providerSettingsForm: { placeholder: input.binaryFallback, clearWhenEmpty: \"omit\" },\n        }),\n      ),\n      customModels: Schema.Array(Schema.String).pipe(\n        Schema.withDecodingDefault(Effect.succeed([])),\n        Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n      ),\n    },\n    {\n      order: [\"binaryPath\"],\n    },\n  );\n\nexport const GeminiSettings = makeAcpAgentSettingsSchema({\n  binaryFallback: \"gemini\",\n  binaryTitle: \"Binary path\",\n  binaryDescription: \"Path to the Gemini CLI binary (started with --experimental-acp).\",\n});\nexport type GeminiSettings = typeof GeminiSettings.Type;\n\nexport const QwenSettings = makeAcpAgentSettingsSchema({\n  binaryFallback: \"qwen\",\n  binaryTitle: \"Binary path\",\n  binaryDescription: \"Path to the Qwen Code binary (started with --experimental-acp).\",\n});\nexport type QwenSettings = typeof QwenSettings.Type;\n\nexport const KimiSettings = makeAcpAgentSettingsSchema({\n  binaryFallback: \"kimi\",\n  binaryTitle: \"Binary path\",\n  binaryDescription: \"Path to the Kimi CLI binary (started with `kimi acp`).\",\n});\nexport type KimiSettings = typeof KimiSettings.Type;\n\nexport const JoyCodeSettings = makeAcpAgentSettingsSchema({\n  binaryFallback: \"joycode\",\n  binaryTitle: \"Binary path\",\n  binaryDescription: \"Path to the JoyCode CLI binary (started with `joycode app-server`).\",\n});\nexport type JoyCodeSettings = typeof JoyCodeSettings.Type;\n\nexport const ObservabilitySettings = Schema.Struct({\n  otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n});\nexport type ObservabilitySettings = typeof ObservabilitySettings.Type;\n\nexport const SourceControlWritingStyleMode = Schema.Literals([\n  \"repo_conventions\",\n  \"conventional_commits\",\n  \"custom\",\n]);\nexport type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;\n\nexport const SourceControlWritingStyleSettings = Schema.Struct({\n  mode: SourceControlWritingStyleMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(\"repo_conventions\" as const)),\n  ),\n  customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  followChangeRequestTemplates: Schema.Boolean.pipe(\n    Schema.withDecodingDefault(Effect.succeed(true)),\n  ),\n});\nexport type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;\n\nexport const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);\nexport const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);\n\nexport const BackgroundActivityProfile = Schema.Literals([\n  \"balanced\",\n  \"performance\",\n  \"battery-saver\",\n]);\nexport type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;\nexport const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = \"balanced\";\n\nexport const BackgroundActivityProfileSelection = Schema.Literals([\n  \"balanced\",\n  \"performance\",\n  \"battery-saver\",\n  \"custom\",\n]);\nexport type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;\n\nexport const BackgroundActivityOverrides = Schema.Struct({\n  automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),\n  pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),\n  pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),\n  pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),\n  pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),\n});\nexport type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;\n\nexport const BackgroundActivitySettings = Schema.Struct({\n  schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),\n  profile: BackgroundActivityProfileSelection.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),\n  ),\n  baseProfile: Schema.optionalKey(BackgroundActivityProfile),\n  overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n}).pipe(Schema.withDecodingDefault(Effect.succeed({})));\nexport type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;\n\nexport const ServerSettings = Schema.Struct({\n  enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  backgroundActivity: BackgroundActivitySettings,\n  // Legacy flat fields retained for old settings files and old clients. New\n  // consumers should resolve `backgroundActivity` instead.\n  automaticGitFetchInterval: Schema.DurationFromMillis.pipe(\n    Schema.withDecodingDefault(\n      Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),\n    ),\n  ),\n  providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(\n    Schema.withDecodingDefault(\n      Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),\n    ),\n  ),\n  backgroundActivityProfile: BackgroundActivityProfile.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),\n  ),\n  defaultThreadEnvMode: ThreadEnvMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(\"local\" as const satisfies ThreadEnvMode)),\n  ),\n  newWorktreesStartFromOrigin: Schema.Boolean.pipe(\n    Schema.withDecodingDefault(Effect.succeed(true)),\n  ),\n  addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  textGenerationModelSelection: ModelSelection.pipe(\n    Schema.withDecodingDefault(\n      Effect.succeed({\n        instanceId: ProviderInstanceId.make(\"codex\"),\n        model: DEFAULT_TEXT_GENERATION_MODEL,\n        options: [\n          {\n            id: \"reasoningEffort\",\n            value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,\n          },\n        ],\n      }),\n    ),\n  ),\n  sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(\n    Schema.withDecodingDefault(Effect.succeed({})),\n  ),\n  sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n\n  // Legacy single-instance-per-driver settings. Continues to be the source\n  // of truth until `providerInstances` (below) lands per-driver migration\n  // shims and the server starts hydrating instances from it. Driver-specific\n  // schemas live here for the duration of the migration; once each driver\n  // owns its config in its own package, this struct shrinks to nothing and\n  // is removed entirely.\n  providers: Schema.Struct({\n    codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    gemini: GeminiSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    qwen: QwenSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    kimi: KimiSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    joycode: JoyCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values\n  // are `ProviderInstanceConfig` envelopes. The driver-specific config blob\n  // is `Schema.Unknown` at this layer so envelopes with unknown drivers\n  // (forks, downgrades, in-flight PR branches) round-trip without loss.\n  // See providerInstance.ts for the forward/backward compatibility invariant.\n  providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(\n    Schema.withDecodingDefault(Effect.succeed({})),\n  ),\n  observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n});\nexport type ServerSettings = typeof ServerSettings.Type;\n\nexport const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});\n\nexport const ServerSettingsOperation = Schema.Literals([\n  \"normalize\",\n  \"check-exists\",\n  \"read-file\",\n  \"read-secret\",\n  \"remove-secret\",\n  \"remove-stale-secret\",\n  \"write-secret\",\n  \"write-file\",\n  \"prepare-directory\",\n]);\nexport type ServerSettingsOperation = typeof ServerSettingsOperation.Type;\n\nexport class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(\n  \"ServerSettingsError\",\n  {\n    settingsPath: Schema.String,\n    operation: ServerSettingsOperation,\n    providerInstanceId: Schema.optional(Schema.String),\n    environmentVariable: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const provider =\n      this.providerInstanceId === undefined ? \"\" : ` for provider ${this.providerInstanceId}`;\n    const variable =\n      this.environmentVariable === undefined\n        ? \"\"\n        : ` and environment variable ${this.environmentVariable}`;\n    return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;\n  }\n}\n\n// ── Unified type ─────────────────────────────────────────────────────\n\nexport type UnifiedSettings = ServerSettings & ClientSettings;\nexport const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {\n  ...DEFAULT_SERVER_SETTINGS,\n  ...DEFAULT_CLIENT_SETTINGS,\n};\n\n// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────\n\nconst ModelSelectionPatch = Schema.Struct({\n  instanceId: Schema.optionalKey(ProviderInstanceId),\n  model: Schema.optionalKey(TrimmedNonEmptyString),\n  options: Schema.optionalKey(ProviderOptionSelections),\n});\n\nconst CodexSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  homePath: Schema.optionalKey(TrimmedString),\n  shadowHomePath: Schema.optionalKey(TrimmedString),\n  launchArgs: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n});\n\nconst ClaudeSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  homePath: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n  launchArgs: Schema.optionalKey(TrimmedString),\n});\n\nconst AcpAgentSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n});\n\nexport const ServerSettingsPatch = Schema.Struct({\n  // Server settings\n  enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),\n  enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),\n  backgroundActivity: Schema.optionalKey(\n    Schema.Struct({\n      schemaVersion: Schema.optionalKey(Schema.Literal(1)),\n      profile: Schema.optionalKey(BackgroundActivityProfileSelection),\n      baseProfile: Schema.optionalKey(BackgroundActivityProfile),\n      overrides: Schema.optionalKey(BackgroundActivityOverrides),\n    }),\n  ),\n  automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),\n  defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),\n  newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),\n  addProjectBaseDirectory: Schema.optionalKey(TrimmedString),\n  textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),\n  sourceControlWritingStyle: Schema.optionalKey(\n    Schema.Struct({\n      mode: Schema.optionalKey(SourceControlWritingStyleMode),\n      customInstructions: Schema.optionalKey(TrimmedString),\n      followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),\n    }),\n  ),\n  sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),\n  observability: Schema.optionalKey(\n    Schema.Struct({\n      otlpTracesUrl: Schema.optionalKey(TrimmedString),\n      otlpMetricsUrl: Schema.optionalKey(TrimmedString),\n    }),\n  ),\n  providers: Schema.optionalKey(\n    Schema.Struct({\n      codex: Schema.optionalKey(CodexSettingsPatch),\n      claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),\n      gemini: Schema.optionalKey(AcpAgentSettingsPatch),\n      qwen: Schema.optionalKey(AcpAgentSettingsPatch),\n      kimi: Schema.optionalKey(AcpAgentSettingsPatch),\n      joycode: Schema.optionalKey(AcpAgentSettingsPatch),\n    }),\n  ),\n  // Whole-map replacement for the new instance config. Patching individual\n  // entries is intentionally out of scope: the map is small, and partial\n  // patches risk leaving driver-specific config in a half-merged state.\n  // The web UI sends a fully-formed map every time it edits this field.\n  providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),\n});\nexport type ServerSettingsPatch = typeof ServerSettingsPatch.Type;\n\nexport const ClientSettingsPatch = Schema.Struct({\n  autoOpenPlanSidebar: Schema.optionalKey(Schema.Boolean),\n  language: Schema.optionalKey(ClientLanguage),\n  confirmThreadArchive: Schema.optionalKey(Schema.Boolean),\n  confirmThreadDelete: Schema.optionalKey(Schema.Boolean),\n  diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),\n  environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),\n  glassOpacity: Schema.optionalKey(GlassOpacity),\n  fontSizeInterface: Schema.optionalKey(InterfaceFontSize),\n  fontSizePrompt: Schema.optionalKey(PromptFontSize),\n  fontSizeCode: Schema.optionalKey(CodeFontSize),\n  fontSizeTerminal: Schema.optionalKey(TerminalFontSize),\n  fontFamilyCode: Schema.optionalKey(FontFamilyPreference),\n  fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),\n  fontFamilySans: Schema.optionalKey(FontFamilyPreference),\n  fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),\n  fontSmoothing: Schema.optionalKey(Schema.Boolean),\n  favorites: Schema.optionalKey(\n    Schema.Array(\n      Schema.Struct({\n        provider: ProviderInstanceId,\n        model: TrimmedNonEmptyString,\n      }),\n    ),\n  ),\n  providerModelPreferences: Schema.optionalKey(\n    Schema.Record(\n      ProviderInstanceId,\n      Schema.Struct({\n        hiddenModels: Schema.Array(Schema.String).pipe(\n          Schema.withDecodingDefault(Effect.succeed([])),\n        ),\n        modelOrder: Schema.Array(Schema.String).pipe(\n          Schema.withDecodingDefault(Effect.succeed([])),\n        ),\n      }),\n    ),\n  ),\n  sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),\n  sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),\n  sidebarProjectGroupingOverrides: Schema.optionalKey(\n    Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),\n  ),\n  sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),\n  sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),\n  sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),\n  sidebarV2Enabled: Schema.optionalKey(Schema.Boolean),\n  sidebarV2ConfiguredByUser: Schema.optionalKey(Schema.Boolean),\n  timestampFormat: Schema.optionalKey(TimestampFormat),\n  wordWrap: Schema.optionalKey(Schema.Boolean),\n});\nexport type ClientSettingsPatch = typeof ClientSettingsPatch.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { ExecutionEnvironmentDescriptor, ServerSelfUpdateMethod } from \"./environment.ts\";\nimport { ServerAuthDescriptor } from \"./auth.ts\";\nimport {\n  ForwardCompatibleArray,\n  IsoDateTime,\n  NonNegativeInt,\n  PositiveInt,\n  ProjectId,\n  ThreadId,\n  TrimmedNonEmptyString,\n} from \"./baseSchemas.ts\";\nimport {\n  KeybindingCommand,\n  KeybindingValue,\n  KeybindingWhen,\n  ResolvedKeybindingsConfig,\n} from \"./keybindings.ts\";\nimport { EditorId } from \"./editor.ts\";\nimport { ModelCapabilities } from \"./model.ts\";\nimport { ProviderDriverKind, ProviderInstanceId } from \"./providerInstance.ts\";\nimport { ServerSettings } from \"./settings.ts\";\n\nconst KeybindingsMalformedConfigIssue = Schema.Struct({\n  kind: Schema.Literal(\"keybindings.malformed-config\"),\n  message: TrimmedNonEmptyString,\n});\n\nconst KeybindingsInvalidEntryIssue = Schema.Struct({\n  kind: Schema.Literal(\"keybindings.invalid-entry\"),\n  message: TrimmedNonEmptyString,\n  index: Schema.Number,\n});\n\nexport const ServerConfigIssue = Schema.Union([\n  KeybindingsMalformedConfigIssue,\n  KeybindingsInvalidEntryIssue,\n]);\nexport type ServerConfigIssue = typeof ServerConfigIssue.Type;\n\n// Issue kinds grow over time; older clients must not fail the whole config\n// decode over a kind they cannot render.\nconst ServerConfigIssues = ForwardCompatibleArray(ServerConfigIssue);\n\nexport const ServerProviderState = Schema.Literals([\"ready\", \"warning\", \"error\", \"disabled\"]);\nexport type ServerProviderState = typeof ServerProviderState.Type;\n\nexport const ServerProviderAuthStatus = Schema.Literals([\n  \"authenticated\",\n  \"unauthenticated\",\n  \"unknown\",\n]);\nexport type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;\n\nexport const ServerProviderAuth = Schema.Struct({\n  status: ServerProviderAuthStatus,\n  type: Schema.optional(TrimmedNonEmptyString),\n  label: Schema.optional(TrimmedNonEmptyString),\n  email: Schema.optional(TrimmedNonEmptyString),\n});\nexport type ServerProviderAuth = typeof ServerProviderAuth.Type;\n\nexport const ServerProviderModel = Schema.Struct({\n  slug: TrimmedNonEmptyString,\n  name: TrimmedNonEmptyString,\n  shortName: Schema.optional(TrimmedNonEmptyString),\n  subProvider: Schema.optional(TrimmedNonEmptyString),\n  isCustom: Schema.Boolean,\n  isDefault: Schema.optional(Schema.Boolean),\n  isLegacy: Schema.optional(Schema.Boolean),\n  capabilities: Schema.NullOr(ModelCapabilities),\n});\nexport type ServerProviderModel = typeof ServerProviderModel.Type;\n\nexport const ServerProviderSlashCommandInput = Schema.Struct({\n  hint: TrimmedNonEmptyString,\n});\nexport type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type;\n\nexport const ServerProviderSlashCommand = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n  input: Schema.optional(ServerProviderSlashCommandInput),\n});\nexport type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type;\n\nexport const ServerProviderSkill = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n  path: TrimmedNonEmptyString,\n  scope: Schema.optional(TrimmedNonEmptyString),\n  enabled: Schema.Boolean,\n  displayName: Schema.optional(TrimmedNonEmptyString),\n  shortDescription: Schema.optional(TrimmedNonEmptyString),\n});\nexport type ServerProviderSkill = typeof ServerProviderSkill.Type;\n\nconst ServerProviderUsagePercent = Schema.Number.check(Schema.isGreaterThanOrEqualTo(0)).check(\n  Schema.isLessThanOrEqualTo(100),\n);\n\nexport const ServerProviderUsageWindow = Schema.Struct({\n  kind: Schema.Literals([\"session\", \"weekly\"]),\n  label: TrimmedNonEmptyString,\n  usedPercent: ServerProviderUsagePercent,\n  resetsAt: Schema.optional(IsoDateTime),\n  windowDurationMins: Schema.optional(NonNegativeInt),\n});\nexport type ServerProviderUsageWindow = typeof ServerProviderUsageWindow.Type;\n\nexport const ServerProviderUsageLimits = Schema.Struct({\n  source: Schema.Literals([\"codexAppServer\", \"claudeAgentSdk\"]),\n  available: Schema.Boolean,\n  reason: Schema.optional(TrimmedNonEmptyString),\n  windows: ForwardCompatibleArray(ServerProviderUsageWindow),\n  checkedAt: IsoDateTime,\n});\nexport type ServerProviderUsageLimits = typeof ServerProviderUsageLimits.Type;\n\n/**\n * Availability of a configured provider instance from the runtime's POV.\n *\n *  - `available` — the build ships this driver and an instance is wired\n *    up. Default for legacy snapshots produced from the closed\n *    `ServerSettings.providers` map.\n *  - `unavailable` — the user's `ServerSettings.providerInstances` (or a\n *    persisted thread / session binding) references a driver this build\n *    doesn't ship. Common after rolling back from a fork or PR branch\n *    that introduced a new driver. The snapshot is preserved so the UI\n *    can render \"missing driver\" affordances and so the data round-trips\n *    when the user moves back to the fork.\n *\n * Snapshots with `availability: \"unavailable\"` MUST set\n * `installed: false` and `enabled: false`; the runtime refuses turn\n * starts against them with a structured error.\n */\nexport const ServerProviderAvailability = Schema.Literals([\"available\", \"unavailable\"]);\nexport type ServerProviderAvailability = typeof ServerProviderAvailability.Type;\n\nexport const ServerProviderContinuation = Schema.Struct({\n  groupKey: TrimmedNonEmptyString,\n});\nexport type ServerProviderContinuation = typeof ServerProviderContinuation.Type;\n\nexport const ServerProviderVersionAdvisoryStatus = Schema.Literals([\n  \"unknown\",\n  \"current\",\n  \"behind_latest\",\n]);\nexport type ServerProviderVersionAdvisoryStatus = typeof ServerProviderVersionAdvisoryStatus.Type;\n\nexport const ServerProviderVersionAdvisory = Schema.Struct({\n  status: ServerProviderVersionAdvisoryStatus,\n  currentVersion: Schema.NullOr(TrimmedNonEmptyString),\n  latestVersion: Schema.NullOr(TrimmedNonEmptyString),\n  updateCommand: Schema.NullOr(TrimmedNonEmptyString),\n  canUpdate: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  checkedAt: Schema.NullOr(IsoDateTime),\n  message: Schema.NullOr(TrimmedNonEmptyString),\n});\nexport type ServerProviderVersionAdvisory = typeof ServerProviderVersionAdvisory.Type;\n\nexport const ServerProviderUpdateStatus = Schema.Literals([\n  \"idle\",\n  \"queued\",\n  \"running\",\n  \"succeeded\",\n  \"failed\",\n  \"unchanged\",\n]);\nexport type ServerProviderUpdateStatus = typeof ServerProviderUpdateStatus.Type;\n\nexport const ServerProviderUpdateState = Schema.Struct({\n  status: ServerProviderUpdateStatus,\n  startedAt: Schema.NullOr(IsoDateTime),\n  finishedAt: Schema.NullOr(IsoDateTime),\n  message: Schema.NullOr(TrimmedNonEmptyString),\n  output: Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000))),\n});\nexport type ServerProviderUpdateState = typeof ServerProviderUpdateState.Type;\n\nexport const ServerProvider = Schema.Struct({\n  // Routing key for the configured instance this snapshot represents. This\n  // is the only stable identity consumers may use for provider routing.\n  instanceId: ProviderInstanceId,\n  // Open driver kind slug that selects the implementation handling this\n  // instance. It is metadata/capability context, not a routing key.\n  driver: ProviderDriverKind,\n  displayName: Schema.optional(TrimmedNonEmptyString),\n  accentColor: Schema.optional(TrimmedNonEmptyString),\n  badgeLabel: Schema.optional(TrimmedNonEmptyString),\n  continuation: Schema.optional(ServerProviderContinuation),\n  showInteractionModeToggle: Schema.optional(Schema.Boolean),\n  requiresNewThreadForModelChange: Schema.optional(Schema.Boolean),\n  enabled: Schema.Boolean,\n  installed: Schema.Boolean,\n  version: Schema.NullOr(TrimmedNonEmptyString),\n  status: ServerProviderState,\n  auth: ServerProviderAuth,\n  checkedAt: IsoDateTime,\n  message: Schema.optional(TrimmedNonEmptyString),\n  // Optional for back-compat: every legacy producer omits this field and\n  // an absent value is interpreted as `\"available\"` by consumers (see\n  // `isProviderAvailable`). New `ProviderInstanceRegistry` outputs set it\n  // explicitly so the UI can render unavailable shadows from\n  // `ServerSettings.providerInstances`.\n  availability: Schema.optional(ServerProviderAvailability),\n  // Human-readable reason populated when `availability === \"unavailable\"`.\n  // Surfaces in the UI alongside the missing-driver affordance.\n  unavailableReason: Schema.optional(TrimmedNonEmptyString),\n  models: Schema.Array(ServerProviderModel),\n  slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(\n    Schema.withDecodingDefault(Effect.succeed([])),\n  ),\n  skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n  usageLimits: Schema.optional(ServerProviderUsageLimits),\n  versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),\n  updateState: Schema.optionalKey(ServerProviderUpdateState),\n});\nexport type ServerProvider = typeof ServerProvider.Type;\n\n// Provider status kinds grow over time (ServerProviderState,\n// ServerProviderAuthStatus, ServerProviderVersionAdvisoryStatus,\n// ServerProviderUpdateStatus); an older client must not fail the whole config\n// decode over one provider it cannot render.\nexport const ServerProviders = ForwardCompatibleArray(ServerProvider);\nexport type ServerProviders = typeof ServerProviders.Type;\n\n/**\n * Treat the optional `availability` as \"available\" when absent. This is\n * the rule legacy producers (which omit the field) and new producers\n * (which set it explicitly) agree on so consumers never have to thread\n * `?? \"available\"` defaults through their code paths.\n */\nexport const isProviderAvailable = (snapshot: ServerProvider): boolean =>\n  snapshot.availability !== \"unavailable\";\n\nexport const ServerObservability = Schema.Struct({\n  logsDirectoryPath: TrimmedNonEmptyString,\n  localTracingEnabled: Schema.Boolean,\n  otlpTracesUrl: Schema.optional(TrimmedNonEmptyString),\n  otlpTracesEnabled: Schema.Boolean,\n  otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString),\n  otlpMetricsEnabled: Schema.Boolean,\n});\nexport type ServerObservability = typeof ServerObservability.Type;\n\nexport const ServerTraceDiagnosticsErrorKind = Schema.Literals([\n  \"trace-file-not-found\",\n  \"trace-file-read-failed\",\n]);\nexport type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;\n\nexport const ServerTraceDiagnosticsSpanSummary = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  count: NonNegativeInt,\n  failureCount: NonNegativeInt,\n  totalDurationMs: Schema.Number,\n  averageDurationMs: Schema.Number,\n  maxDurationMs: Schema.Number,\n});\nexport type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;\n\nexport const ServerTraceDiagnosticsFailureSummary = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  cause: TrimmedNonEmptyString,\n  count: NonNegativeInt,\n  lastSeenAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;\n\nexport const ServerTraceDiagnosticsRecentFailure = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  cause: TrimmedNonEmptyString,\n  durationMs: Schema.Number,\n  endedAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;\n\nexport const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  durationMs: Schema.Number,\n  endedAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;\n\nexport const ServerTraceDiagnosticsLogEvent = Schema.Struct({\n  spanName: TrimmedNonEmptyString,\n  level: TrimmedNonEmptyString,\n  message: TrimmedNonEmptyString,\n  seenAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;\n\nexport const ServerTraceDiagnosticsResult = Schema.Struct({\n  traceFilePath: TrimmedNonEmptyString,\n  scannedFilePaths: Schema.Array(TrimmedNonEmptyString),\n  readAt: Schema.DateTimeUtc,\n  recordCount: NonNegativeInt,\n  parseErrorCount: NonNegativeInt,\n  firstSpanAt: Schema.Option(Schema.DateTimeUtc),\n  lastSpanAt: Schema.Option(Schema.DateTimeUtc),\n  failureCount: NonNegativeInt,\n  interruptionCount: NonNegativeInt,\n  slowSpanThresholdMs: NonNegativeInt,\n  slowSpanCount: NonNegativeInt,\n  logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),\n  topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),\n  slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),\n  commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),\n  latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),\n  latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),\n  partialFailure: Schema.Option(Schema.Boolean),\n  error: Schema.Option(\n    Schema.Struct({\n      kind: ServerTraceDiagnosticsErrorKind,\n      message: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;\n\nexport const ServerProcessSignal = Schema.Literals([\"SIGINT\", \"SIGKILL\"]);\nexport type ServerProcessSignal = typeof ServerProcessSignal.Type;\n\nexport const ServerProcessDiagnosticsEntry = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: NonNegativeInt,\n  ppid: NonNegativeInt,\n  pgid: Schema.Option(Schema.Int),\n  status: TrimmedNonEmptyString,\n  cpuPercent: Schema.Number,\n  rssBytes: NonNegativeInt,\n  elapsed: TrimmedNonEmptyString,\n  command: TrimmedNonEmptyString,\n  depth: NonNegativeInt,\n  childPids: Schema.Array(PositiveInt),\n});\nexport type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;\n\nexport const ServerProcessDiagnosticsResult = Schema.Struct({\n  serverPid: PositiveInt,\n  readAt: Schema.DateTimeUtc,\n  processCount: NonNegativeInt,\n  totalRssBytes: NonNegativeInt,\n  totalCpuPercent: Schema.Number,\n  processes: Schema.Array(ServerProcessDiagnosticsEntry),\n  error: Schema.Option(\n    Schema.Struct({\n      message: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;\n\nexport const ServerProcessResourceHistoryInput = Schema.Struct({\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n});\nexport type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;\n\nexport const ServerProcessResourceHistoryBucket = Schema.Struct({\n  startedAt: Schema.DateTimeUtc,\n  endedAt: Schema.DateTimeUtc,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  maxRssBytes: NonNegativeInt,\n  maxProcessCount: NonNegativeInt,\n});\nexport type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;\n\nexport const ServerProcessResourceHistorySummary = Schema.Struct({\n  processKey: TrimmedNonEmptyString,\n  pid: PositiveInt,\n  ppid: NonNegativeInt,\n  command: TrimmedNonEmptyString,\n  depth: NonNegativeInt,\n  isServerRoot: Schema.Boolean,\n  firstSeenAt: Schema.DateTimeUtc,\n  lastSeenAt: Schema.DateTimeUtc,\n  currentCpuPercent: Schema.Number,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  cpuSecondsApprox: Schema.Number,\n  currentRssBytes: NonNegativeInt,\n  maxRssBytes: NonNegativeInt,\n  sampleCount: NonNegativeInt,\n});\nexport type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;\n\nexport const ServerProcessResourceHistoryFailureTag = Schema.Literals([\n  \"ProcessDiagnosticsQueryTimeoutError\",\n  \"ProcessDiagnosticsQueryFailedError\",\n  \"ProcessDiagnosticsServerProcessSignalError\",\n  \"ProcessDiagnosticsNotDescendantError\",\n  \"ProcessDiagnosticsSignalFailedError\",\n]);\nexport type ServerProcessResourceHistoryFailureTag =\n  typeof ServerProcessResourceHistoryFailureTag.Type;\n\nexport const ServerProcessResourceHistoryResult = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n  sampleIntervalMs: NonNegativeInt,\n  retainedSampleCount: NonNegativeInt,\n  totalCpuSecondsApprox: Schema.Number,\n  buckets: Schema.Array(ServerProcessResourceHistoryBucket),\n  topProcesses: Schema.Array(ServerProcessResourceHistorySummary),\n  error: Schema.Option(\n    Schema.Struct({\n      failureTag: ServerProcessResourceHistoryFailureTag,\n      message: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;\n\nexport const ServerSignalProcessInput = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: NonNegativeInt,\n  signal: ServerProcessSignal,\n});\nexport type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;\n\nexport const ServerSignalProcessResult = Schema.Struct({\n  pid: PositiveInt,\n  signal: ServerProcessSignal,\n  signaled: Schema.Boolean,\n  message: Schema.Option(TrimmedNonEmptyString),\n});\nexport type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;\n\nexport const ServerConfig = Schema.Struct({\n  environment: ExecutionEnvironmentDescriptor,\n  auth: ServerAuthDescriptor,\n  cwd: TrimmedNonEmptyString,\n  keybindingsConfigPath: TrimmedNonEmptyString,\n  keybindings: ResolvedKeybindingsConfig,\n  issues: ServerConfigIssues,\n  providers: ServerProviders,\n  // Editor ids grow over time; drop ones this build does not know rather than\n  // failing the whole config decode.\n  availableEditors: ForwardCompatibleArray(EditorId),\n  observability: ServerObservability,\n  settings: ServerSettings,\n  /** Whether shell subscriptions can emit an opt-in catch-up completion marker. */\n  shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),\n  /** Whether thread subscriptions can emit an opt-in catch-up completion marker. */\n  threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),\n});\nexport type ServerConfig = typeof ServerConfig.Type;\n\nconst ServerUpsertKeybindingReplaceTarget = Schema.Struct({\n  key: KeybindingValue,\n  command: KeybindingCommand,\n  when: Schema.optional(KeybindingWhen),\n});\n\nexport const ServerUpsertKeybindingInput = Schema.Struct({\n  key: KeybindingValue,\n  command: KeybindingCommand,\n  when: Schema.optional(KeybindingWhen),\n  replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),\n});\nexport type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;\n\nexport const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;\nexport type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;\n\nexport const ServerUpsertKeybindingResult = Schema.Struct({\n  keybindings: ResolvedKeybindingsConfig,\n  issues: ServerConfigIssues,\n});\nexport type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;\n\nexport const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;\nexport type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;\n\nexport const ServerConfigUpdatedPayload = Schema.Struct({\n  issues: ServerConfigIssues,\n  providers: ServerProviders,\n  settings: Schema.optional(ServerSettings),\n});\nexport type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;\n\nexport const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({\n  keybindings: ResolvedKeybindingsConfig,\n  issues: ServerConfigIssues,\n});\nexport type ServerConfigKeybindingsUpdatedPayload =\n  typeof ServerConfigKeybindingsUpdatedPayload.Type;\n\nexport const ServerConfigProviderStatusesPayload = Schema.Struct({\n  providers: ServerProviders,\n});\nexport type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;\n\nexport const ServerConfigSettingsUpdatedPayload = Schema.Struct({\n  settings: ServerSettings,\n});\nexport type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;\n\nexport const ServerConfigStreamSnapshotEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"snapshot\"),\n  config: ServerConfig,\n});\nexport type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;\n\nexport const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"keybindingsUpdated\"),\n  payload: ServerConfigKeybindingsUpdatedPayload,\n});\nexport type ServerConfigStreamKeybindingsUpdatedEvent =\n  typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;\n\nexport const ServerConfigStreamProviderStatusesEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"providerStatuses\"),\n  payload: ServerConfigProviderStatusesPayload,\n});\nexport type ServerConfigStreamProviderStatusesEvent =\n  typeof ServerConfigStreamProviderStatusesEvent.Type;\n\nexport const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"settingsUpdated\"),\n  payload: ServerConfigSettingsUpdatedPayload,\n});\nexport type ServerConfigStreamSettingsUpdatedEvent =\n  typeof ServerConfigStreamSettingsUpdatedEvent.Type;\n\nexport const ServerConfigStreamEvent = Schema.Union([\n  ServerConfigStreamSnapshotEvent,\n  ServerConfigStreamKeybindingsUpdatedEvent,\n  ServerConfigStreamProviderStatusesEvent,\n  ServerConfigStreamSettingsUpdatedEvent,\n]);\nexport type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;\n\n/** Terminal selection recorded by the service launcher for one update. */\nexport const ServerSelfUpdateOutcome = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  fromVersion: TrimmedNonEmptyString,\n  targetVersion: TrimmedNonEmptyString,\n  status: Schema.Literals([\"committed\", \"rolled-back\", \"failed\"]),\n  reason: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;\n\nexport const ServerLifecycleReadyPayload = Schema.Struct({\n  at: IsoDateTime,\n  environment: ExecutionEnvironmentDescriptor,\n  /** Present when this process resumed a launcher-managed update. */\n  updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),\n});\nexport type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;\n\nexport const ServerLifecycleWelcomePayload = Schema.Struct({\n  environment: ExecutionEnvironmentDescriptor,\n  cwd: TrimmedNonEmptyString,\n  projectName: TrimmedNonEmptyString,\n  bootstrapProjectId: Schema.optional(ProjectId),\n  bootstrapThreadId: Schema.optional(ThreadId),\n});\nexport type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;\n\nexport const ServerLifecycleStreamWelcomeEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  sequence: NonNegativeInt,\n  type: Schema.Literal(\"welcome\"),\n  payload: ServerLifecycleWelcomePayload,\n});\nexport type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;\n\nexport const ServerLifecycleStreamReadyEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  sequence: NonNegativeInt,\n  type: Schema.Literal(\"ready\"),\n  payload: ServerLifecycleReadyPayload,\n});\nexport type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;\n\nexport const ServerLifecycleStreamEvent = Schema.Union([\n  ServerLifecycleStreamWelcomeEvent,\n  ServerLifecycleStreamReadyEvent,\n]);\nexport type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;\n\nexport const ServerProviderUpdatedPayload = Schema.Struct({\n  providers: ServerProviders,\n});\nexport type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;\n\nexport const ServerProviderUpdateInput = Schema.Struct({\n  provider: ProviderDriverKind,\n  instanceId: Schema.optionalKey(ProviderInstanceId),\n});\nexport type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;\n\nexport class ServerProviderUpdateError extends Schema.TaggedErrorClass<ServerProviderUpdateError>()(\n  \"ServerProviderUpdateError\",\n  {\n    provider: ProviderDriverKind,\n    reason: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider update failed for ${this.provider}: ${this.reason}`;\n  }\n}\n\nexport const ServerSelfUpdateInput = Schema.Struct({\n  /** Exact npm version of the `t3` package to install (never a dist-tag, so\n      the server and the acknowledging client agree on what was requested). */\n  targetVersion: TrimmedNonEmptyString,\n});\nexport type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;\n\n/** Acknowledgement that the update artifact is installed and the server is\n    about to restart into it — the connection will drop moments later. */\nexport const ServerSelfUpdateResult = Schema.Struct({\n  targetVersion: TrimmedNonEmptyString,\n  method: ServerSelfUpdateMethod,\n  /** Launcher-generated correlation ID. Absent when talking to older servers. */\n  updateId: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;\n\nexport const ServerSelfUpdateProgressStage = Schema.Literals([\"downloading\", \"installing\"]);\nexport type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;\n\nexport const ServerSelfUpdateProgressEvent = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"progress\"),\n    stage: ServerSelfUpdateProgressStage,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"complete\"),\n    result: ServerSelfUpdateResult,\n  }),\n]);\nexport type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;\n\nexport class ServerSelfUpdateError extends Schema.TaggedErrorClass<ServerSelfUpdateError>()(\n  \"ServerSelfUpdateError\",\n  {\n    reason: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Server update failed: ${this.reason}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { NonNegativeInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const VcsDriverKind = Schema.Literals([\"git\", \"jj\", \"unknown\"]);\nexport type VcsDriverKind = typeof VcsDriverKind.Type;\n\nexport const VcsFreshnessSource = Schema.Literals([\n  \"live-local\",\n  \"cached-local\",\n  \"cached-remote\",\n  \"explicit-remote\",\n]);\nexport type VcsFreshnessSource = typeof VcsFreshnessSource.Type;\n\nexport const VcsFreshness = Schema.Struct({\n  source: VcsFreshnessSource,\n  observedAt: Schema.DateTimeUtc,\n  expiresAt: Schema.Option(Schema.DateTimeUtc),\n});\nexport type VcsFreshness = typeof VcsFreshness.Type;\n\nexport const VcsDriverCapabilities = Schema.Struct({\n  kind: VcsDriverKind,\n  supportsWorktrees: Schema.Boolean,\n  supportsBookmarks: Schema.Boolean,\n  supportsAtomicSnapshot: Schema.Boolean,\n  supportsPushDefaultRemote: Schema.Boolean,\n  ignoreClassifier: Schema.Literals([\"native\", \"git-compatible-fallback\"]),\n});\nexport type VcsDriverCapabilities = typeof VcsDriverCapabilities.Type;\n\nexport const VcsRepositoryIdentity = Schema.Struct({\n  kind: VcsDriverKind,\n  rootPath: TrimmedNonEmptyString,\n  metadataPath: Schema.NullOr(TrimmedNonEmptyString),\n  freshness: VcsFreshness,\n});\nexport type VcsRepositoryIdentity = typeof VcsRepositoryIdentity.Type;\n\nexport const VcsListWorkspaceFilesResult = Schema.Struct({\n  paths: Schema.Array(TrimmedNonEmptyString),\n  truncated: Schema.Boolean,\n  freshness: VcsFreshness,\n});\nexport type VcsListWorkspaceFilesResult = typeof VcsListWorkspaceFilesResult.Type;\n\nexport const VcsRemote = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  pushUrl: Schema.Option(TrimmedNonEmptyString),\n  isPrimary: Schema.Boolean,\n});\nexport type VcsRemote = typeof VcsRemote.Type;\n\nexport const VcsListRemotesResult = Schema.Struct({\n  remotes: Schema.Array(VcsRemote),\n  freshness: VcsFreshness,\n});\nexport type VcsListRemotesResult = typeof VcsListRemotesResult.Type;\n\nexport interface VcsProcessErrorContext {\n  readonly operation: string;\n  readonly command: string;\n  readonly cwd: string;\n  readonly argumentCount?: number;\n}\n\nexport interface VcsProcessSpawnFailure {\n  readonly cause: unknown;\n}\n\nexport interface VcsProcessTimeoutFailure {\n  readonly timeoutMs: number;\n}\n\nexport const VcsProcessExitFailureKind = Schema.Literals([\n  \"authentication\",\n  \"not-found\",\n  \"command-failed\",\n]);\nexport type VcsProcessExitFailureKind = typeof VcsProcessExitFailureKind.Type;\n\nexport interface VcsProcessExitFailure {\n  readonly exitCode: number;\n  readonly stderr: string;\n  readonly stderrTruncated: boolean;\n}\n\nexport class VcsProcessSpawnError extends Schema.TaggedErrorClass<VcsProcessSpawnError>()(\n  \"VcsProcessSpawnError\",\n  {\n    operation: Schema.String,\n    command: Schema.String,\n    cwd: Schema.String,\n    argumentCount: Schema.optional(NonNegativeInt),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed to spawn in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n\n  static fromProcessSpawnError(context: VcsProcessErrorContext, error: VcsProcessSpawnFailure) {\n    return new VcsProcessSpawnError({\n      ...context,\n      cause: error.cause,\n    });\n  }\n}\n\nexport class VcsProcessExitError extends Schema.TaggedErrorClass<VcsProcessExitError>()(\n  \"VcsProcessExitError\",\n  {\n    operation: Schema.String,\n    command: Schema.String,\n    cwd: Schema.String,\n    argumentCount: Schema.optional(NonNegativeInt),\n    exitCode: Schema.Number,\n    detail: Schema.String,\n    failureKind: Schema.optional(VcsProcessExitFailureKind),\n    stderrLength: Schema.optional(NonNegativeInt),\n    stderrTruncated: Schema.optional(Schema.Boolean),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed in ${this.operation}: ${this.command} (${this.cwd}) exited with ${this.exitCode} - ${this.detail}`;\n  }\n\n  static fromProcessExit(\n    context: VcsProcessErrorContext,\n    error: VcsProcessExitFailure,\n    failureKind: VcsProcessExitFailureKind,\n  ) {\n    const detail =\n      failureKind === \"authentication\"\n        ? \"Authentication failed.\"\n        : failureKind === \"not-found\"\n          ? context.command === \"glab\"\n            ? \"Merge request not found.\"\n            : context.command === \"gh\" || context.command === \"az\"\n              ? \"Pull request not found.\"\n              : \"VCS resource not found.\"\n          : \"Process exited with a non-zero status.\";\n\n    return new VcsProcessExitError({\n      ...context,\n      exitCode: error.exitCode,\n      detail,\n      failureKind,\n      stderrLength: error.stderr.length,\n      stderrTruncated: error.stderrTruncated,\n    });\n  }\n}\n\nexport class VcsProcessTimeoutError extends Schema.TaggedErrorClass<VcsProcessTimeoutError>()(\n  \"VcsProcessTimeoutError\",\n  {\n    operation: Schema.String,\n    command: Schema.String,\n    cwd: Schema.String,\n    argumentCount: Schema.optional(NonNegativeInt),\n    timeoutMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `VCS process timed out in ${this.operation}: ${this.command} (${this.cwd}) after ${this.timeoutMs}ms`;\n  }\n\n  static fromProcessTimeoutError(context: VcsProcessErrorContext, error: VcsProcessTimeoutFailure) {\n    return new VcsProcessTimeoutError({\n      ...context,\n      timeoutMs: error.timeoutMs,\n    });\n  }\n}\n\nconst VcsProcessBoundaryErrorFields = {\n  operation: Schema.String,\n  command: Schema.String,\n  cwd: Schema.String,\n  argumentCount: Schema.optional(NonNegativeInt),\n};\n\nexport class VcsProcessStdinWriteError extends Schema.TaggedErrorClass<VcsProcessStdinWriteError>()(\n  \"VcsProcessStdinWriteError\",\n  {\n    ...VcsProcessBoundaryErrorFields,\n    stdinBytes: NonNegativeInt,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed to write ${this.stdinBytes} bytes to stdin in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n}\n\nexport class VcsProcessOutputReadError extends Schema.TaggedErrorClass<VcsProcessOutputReadError>()(\n  \"VcsProcessOutputReadError\",\n  {\n    ...VcsProcessBoundaryErrorFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\", \"exitCode\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed to read ${this.stream} in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n}\n\nexport class VcsProcessOutputLimitError extends Schema.TaggedErrorClass<VcsProcessOutputLimitError>()(\n  \"VcsProcessOutputLimitError\",\n  {\n    ...VcsProcessBoundaryErrorFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\"]),\n    maxBytes: NonNegativeInt,\n    observedBytes: NonNegativeInt,\n  },\n) {\n  override get message(): string {\n    return `VCS process ${this.stream} produced ${this.observedBytes} bytes in ${this.operation}: ${this.command} (${this.cwd}), exceeding the ${this.maxBytes} byte limit`;\n  }\n}\n\nexport class VcsProcessMissingExitCodeError extends Schema.TaggedErrorClass<VcsProcessMissingExitCodeError>()(\n  \"VcsProcessMissingExitCodeError\",\n  VcsProcessBoundaryErrorFields,\n) {\n  override get message(): string {\n    return `VCS process completed without an exit code in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n}\n\nexport const VcsOutputDecodeError = Schema.Union([\n  VcsProcessStdinWriteError,\n  VcsProcessOutputReadError,\n  VcsProcessOutputLimitError,\n  VcsProcessMissingExitCodeError,\n]);\nexport type VcsOutputDecodeError = typeof VcsOutputDecodeError.Type;\n\nexport class VcsRepositoryDetectionError extends Schema.TaggedErrorClass<VcsRepositoryDetectionError>()(\n  \"VcsRepositoryDetectionError\",\n  {\n    operation: Schema.String,\n    cwd: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `VCS repository detection failed in ${this.operation}: ${this.cwd} - ${this.detail}`;\n  }\n}\n\nexport class VcsUnsupportedOperationError extends Schema.TaggedErrorClass<VcsUnsupportedOperationError>()(\n  \"VcsUnsupportedOperationError\",\n  {\n    operation: Schema.String,\n    kind: VcsDriverKind,\n    detail: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `VCS operation is unsupported for ${this.kind} in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport const VcsError = Schema.Union([\n  VcsProcessSpawnError,\n  VcsProcessExitError,\n  VcsProcessTimeoutError,\n  VcsProcessStdinWriteError,\n  VcsProcessOutputReadError,\n  VcsProcessOutputLimitError,\n  VcsProcessMissingExitCodeError,\n  VcsRepositoryDetectionError,\n  VcsUnsupportedOperationError,\n]);\nexport type VcsError = typeof VcsError.Type;\n","import * as Schema from \"effect/Schema\";\nimport { PositiveInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { VcsDriverKind } from \"./vcs.ts\";\n\nexport const SourceControlProviderKind = Schema.Literals([\n  \"github\",\n  \"gitlab\",\n  \"azure-devops\",\n  \"bitbucket\",\n  \"unknown\",\n]);\nexport type SourceControlProviderKind = typeof SourceControlProviderKind.Type;\n\nexport const SourceControlProviderInfo = Schema.Struct({\n  kind: SourceControlProviderKind,\n  name: TrimmedNonEmptyString,\n  baseUrl: Schema.String,\n});\nexport type SourceControlProviderInfo = typeof SourceControlProviderInfo.Type;\n\nexport const ChangeRequestState = Schema.Literals([\"open\", \"closed\", \"merged\"]);\nexport type ChangeRequestState = typeof ChangeRequestState.Type;\n\nexport const ChangeRequest = Schema.Struct({\n  provider: SourceControlProviderKind,\n  number: PositiveInt,\n  title: TrimmedNonEmptyString,\n  url: Schema.String,\n  baseRefName: TrimmedNonEmptyString,\n  headRefName: TrimmedNonEmptyString,\n  state: ChangeRequestState,\n  updatedAt: Schema.Option(Schema.DateTimeUtc),\n  isCrossRepository: Schema.optional(Schema.Boolean),\n  headRepositoryNameWithOwner: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  headRepositoryOwnerLogin: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n});\nexport type ChangeRequest = typeof ChangeRequest.Type;\n\nexport const SourceControlRepositoryCloneUrls = Schema.Struct({\n  nameWithOwner: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  sshUrl: TrimmedNonEmptyString,\n});\nexport type SourceControlRepositoryCloneUrls = typeof SourceControlRepositoryCloneUrls.Type;\n\nexport const SourceControlRepositoryVisibility = Schema.Literals([\"private\", \"public\"]);\nexport type SourceControlRepositoryVisibility = typeof SourceControlRepositoryVisibility.Type;\n\nexport const SourceControlCloneProtocol = Schema.Literals([\"auto\", \"ssh\", \"https\"]);\nexport type SourceControlCloneProtocol = typeof SourceControlCloneProtocol.Type;\n\nexport const SourceControlRepositoryInfo = Schema.Struct({\n  provider: SourceControlProviderKind,\n  nameWithOwner: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  sshUrl: TrimmedNonEmptyString,\n});\nexport type SourceControlRepositoryInfo = typeof SourceControlRepositoryInfo.Type;\n\nexport const SourceControlRepositoryLookupInput = Schema.Struct({\n  provider: SourceControlProviderKind,\n  repository: TrimmedNonEmptyString,\n  cwd: Schema.optional(TrimmedNonEmptyString),\n});\nexport type SourceControlRepositoryLookupInput = typeof SourceControlRepositoryLookupInput.Type;\n\nexport const SourceControlCloneRepositoryInput = Schema.Struct({\n  provider: Schema.optional(SourceControlProviderKind),\n  repository: Schema.optional(TrimmedNonEmptyString),\n  remoteUrl: Schema.optional(TrimmedNonEmptyString),\n  destinationPath: TrimmedNonEmptyString,\n  protocol: Schema.optional(SourceControlCloneProtocol),\n});\nexport type SourceControlCloneRepositoryInput = typeof SourceControlCloneRepositoryInput.Type;\n\nexport const SourceControlCloneRepositoryResult = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n  repository: Schema.NullOr(SourceControlRepositoryInfo),\n});\nexport type SourceControlCloneRepositoryResult = typeof SourceControlCloneRepositoryResult.Type;\n\nexport const SourceControlPublishRepositoryInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  provider: SourceControlProviderKind,\n  repository: TrimmedNonEmptyString,\n  visibility: SourceControlRepositoryVisibility,\n  remoteName: Schema.optional(TrimmedNonEmptyString),\n  protocol: Schema.optional(SourceControlCloneProtocol),\n});\nexport type SourceControlPublishRepositoryInput = typeof SourceControlPublishRepositoryInput.Type;\n\nexport const SourceControlPublishStatus = Schema.Literals([\"pushed\", \"remote_added\"]);\nexport type SourceControlPublishStatus = typeof SourceControlPublishStatus.Type;\n\nexport const SourceControlPublishRepositoryResult = Schema.Struct({\n  repository: SourceControlRepositoryInfo,\n  remoteName: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n  branch: TrimmedNonEmptyString,\n  upstreamBranch: Schema.optional(TrimmedNonEmptyString),\n  status: SourceControlPublishStatus,\n});\nexport type SourceControlPublishRepositoryResult = typeof SourceControlPublishRepositoryResult.Type;\n\nexport const SourceControlDiscoveryStatus = Schema.Literals([\"available\", \"missing\"]);\nexport type SourceControlDiscoveryStatus = typeof SourceControlDiscoveryStatus.Type;\n\nexport const SourceControlProviderAuthStatus = Schema.Literals([\n  \"authenticated\",\n  \"unauthenticated\",\n  \"unknown\",\n]);\nexport type SourceControlProviderAuthStatus = typeof SourceControlProviderAuthStatus.Type;\n\nexport const SourceControlProviderAuth = Schema.Struct({\n  status: SourceControlProviderAuthStatus,\n  account: Schema.Option(TrimmedNonEmptyString),\n  host: Schema.Option(TrimmedNonEmptyString),\n  detail: Schema.Option(TrimmedNonEmptyString),\n});\nexport type SourceControlProviderAuth = typeof SourceControlProviderAuth.Type;\n\nconst SourceControlDiscoverySharedFields = {\n  label: TrimmedNonEmptyString,\n  executable: Schema.optional(TrimmedNonEmptyString),\n  status: SourceControlDiscoveryStatus,\n  version: Schema.Option(TrimmedNonEmptyString),\n  installHint: TrimmedNonEmptyString,\n  detail: Schema.Option(TrimmedNonEmptyString),\n} as const;\n\nexport const VcsDiscoveryItem = Schema.Struct({\n  kind: VcsDriverKind,\n  implemented: Schema.Boolean,\n  ...SourceControlDiscoverySharedFields,\n});\nexport type VcsDiscoveryItem = typeof VcsDiscoveryItem.Type;\n\nexport const SourceControlProviderDiscoveryItem = Schema.Struct({\n  kind: SourceControlProviderKind,\n  ...SourceControlDiscoverySharedFields,\n  auth: SourceControlProviderAuth,\n});\nexport type SourceControlProviderDiscoveryItem = typeof SourceControlProviderDiscoveryItem.Type;\n\nexport const SourceControlDiscoveryResult = Schema.Struct({\n  versionControlSystems: Schema.Array(VcsDiscoveryItem),\n  sourceControlProviders: Schema.Array(SourceControlProviderDiscoveryItem),\n});\nexport type SourceControlDiscoveryResult = typeof SourceControlDiscoveryResult.Type;\n\nexport class SourceControlProviderError extends Schema.TaggedErrorClass<SourceControlProviderError>()(\n  \"SourceControlProviderError\",\n  {\n    provider: SourceControlProviderKind,\n    operation: Schema.String,\n    cwd: Schema.String,\n    command: Schema.optional(Schema.String),\n    repository: Schema.optional(Schema.String),\n    reference: Schema.optional(Schema.String),\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Source control provider ${this.provider} failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class SourceControlRepositoryError extends Schema.TaggedErrorClass<SourceControlRepositoryError>()(\n  \"SourceControlRepositoryError\",\n  {\n    provider: SourceControlProviderKind,\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Source control repository operation ${this.operation} failed for ${this.provider}: ${this.detail}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { SourceControlProviderError, SourceControlProviderInfo } from \"./sourceControl.ts\";\nimport { VcsDriverKind } from \"./vcs.ts\";\n\nconst TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\nconst GIT_LIST_BRANCHES_MAX_LIMIT = 200;\n\n// Domain Types\n\nexport const GitStackedAction = Schema.Literals([\n  \"commit\",\n  \"push\",\n  \"create_pr\",\n  \"commit_push\",\n  \"commit_push_pr\",\n]);\nexport type GitStackedAction = typeof GitStackedAction.Type;\nexport const GitActionProgressPhase = Schema.Literals([\"branch\", \"commit\", \"push\", \"pr\"]);\nexport type GitActionProgressPhase = typeof GitActionProgressPhase.Type;\nexport const GitActionProgressKind = Schema.Literals([\n  \"action_started\",\n  \"phase_started\",\n  \"hook_started\",\n  \"hook_output\",\n  \"hook_finished\",\n  \"action_finished\",\n  \"action_failed\",\n]);\nexport type GitActionProgressKind = typeof GitActionProgressKind.Type;\nexport const GitActionProgressStream = Schema.Literals([\"stdout\", \"stderr\"]);\nexport type GitActionProgressStream = typeof GitActionProgressStream.Type;\nconst GitCommitStepStatus = Schema.Literals([\n  \"created\",\n  \"skipped_no_changes\",\n  \"skipped_not_requested\",\n]);\nconst GitPushStepStatus = Schema.Literals([\n  \"pushed\",\n  \"skipped_not_requested\",\n  \"skipped_up_to_date\",\n]);\nconst GitBranchStepStatus = Schema.Literals([\"created\", \"skipped_not_requested\"]);\nconst GitPrStepStatus = Schema.Literals([\"created\", \"opened_existing\", \"skipped_not_requested\"]);\nconst VcsStatusChangeRequestState = Schema.Literals([\"open\", \"closed\", \"merged\"]);\nconst GitPullRequestReference = TrimmedNonEmptyStringSchema;\nconst GitPullRequestState = Schema.Literals([\"open\", \"closed\", \"merged\"]);\nconst GitPreparePullRequestThreadMode = Schema.Literals([\"local\", \"worktree\"]);\nexport const GitRunStackedActionToastRunAction = Schema.Struct({\n  kind: GitStackedAction,\n});\nexport type GitRunStackedActionToastRunAction = typeof GitRunStackedActionToastRunAction.Type;\nconst GitRunStackedActionToastCta = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"none\"),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"open_pr\"),\n    label: TrimmedNonEmptyStringSchema,\n    url: Schema.String,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"run_action\"),\n    label: TrimmedNonEmptyStringSchema,\n    action: GitRunStackedActionToastRunAction,\n  }),\n]);\nexport type GitRunStackedActionToastCta = typeof GitRunStackedActionToastCta.Type;\nconst GitRunStackedActionToast = Schema.Struct({\n  title: TrimmedNonEmptyStringSchema,\n  description: Schema.optional(TrimmedNonEmptyStringSchema),\n  cta: GitRunStackedActionToastCta,\n});\nexport type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type;\n\nexport const VcsRef = Schema.Struct({\n  name: TrimmedNonEmptyStringSchema,\n  isRemote: Schema.optional(Schema.Boolean),\n  remoteName: Schema.optional(TrimmedNonEmptyStringSchema),\n  current: Schema.Boolean,\n  isDefault: Schema.Boolean,\n  worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),\n});\nexport type VcsRef = typeof VcsRef.Type;\n\nconst VcsWorktree = Schema.Struct({\n  path: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n});\nconst GitResolvedPullRequest = Schema.Struct({\n  number: PositiveInt,\n  title: TrimmedNonEmptyStringSchema,\n  url: Schema.String,\n  baseBranch: TrimmedNonEmptyStringSchema,\n  headBranch: TrimmedNonEmptyStringSchema,\n  state: GitPullRequestState,\n});\nexport type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type;\n\n// RPC Inputs\n\nexport const VcsStatusInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n});\nexport type VcsStatusInput = typeof VcsStatusInput.Type;\n\nexport const VcsPullInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n});\nexport type VcsPullInput = typeof VcsPullInput.Type;\n\nexport const GitRunStackedActionInput = Schema.Struct({\n  actionId: TrimmedNonEmptyStringSchema,\n  cwd: TrimmedNonEmptyStringSchema,\n  action: GitStackedAction,\n  commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),\n  featureBranch: Schema.optional(Schema.Boolean),\n  filePaths: Schema.optional(\n    Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),\n  ),\n});\nexport type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;\n\nexport const VcsListRefsInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  query: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(256))),\n  cursor: Schema.optional(NonNegativeInt),\n  includeMatchingRemoteRefs: Schema.optional(Schema.Boolean),\n  refKind: Schema.optional(Schema.Literals([\"all\", \"local\", \"remote\"])),\n  refresh: Schema.optional(Schema.Boolean),\n  limit: Schema.optional(\n    PositiveInt.check(Schema.isLessThanOrEqualTo(GIT_LIST_BRANCHES_MAX_LIMIT)),\n  ),\n});\nexport type VcsListRefsInput = typeof VcsListRefsInput.Type;\n\nexport const VcsCreateWorktreeInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n  newRefName: Schema.optional(TrimmedNonEmptyStringSchema),\n  baseRefName: Schema.optional(TrimmedNonEmptyStringSchema),\n  path: Schema.NullOr(TrimmedNonEmptyStringSchema),\n});\nexport type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type;\n\nexport const GitPullRequestRefInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  reference: GitPullRequestReference,\n});\nexport type GitPullRequestRefInput = typeof GitPullRequestRefInput.Type;\n\nexport const GitPreparePullRequestThreadInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  reference: GitPullRequestReference,\n  mode: GitPreparePullRequestThreadMode,\n  threadId: Schema.optional(ThreadId),\n});\nexport type GitPreparePullRequestThreadInput = typeof GitPreparePullRequestThreadInput.Type;\n\nexport const VcsRemoveWorktreeInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  path: TrimmedNonEmptyStringSchema,\n  force: Schema.optional(Schema.Boolean),\n});\nexport type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type;\n\nexport const VcsCreateRefInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n  switchRef: Schema.optional(Schema.Boolean),\n});\nexport type VcsCreateRefInput = typeof VcsCreateRefInput.Type;\n\nexport const VcsCreateRefResult = Schema.Struct({\n  refName: TrimmedNonEmptyStringSchema,\n});\nexport type VcsCreateRefResult = typeof VcsCreateRefResult.Type;\n\nexport const VcsSwitchRefInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n});\nexport type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type;\n\nexport const VcsInitInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  kind: Schema.optional(VcsDriverKind),\n});\nexport type VcsInitInput = typeof VcsInitInput.Type;\n\n// RPC Results\n\nconst VcsStatusChangeRequest = Schema.Struct({\n  number: PositiveInt,\n  title: TrimmedNonEmptyStringSchema,\n  url: Schema.String,\n  baseRef: TrimmedNonEmptyStringSchema,\n  headRef: TrimmedNonEmptyStringSchema,\n  state: VcsStatusChangeRequestState,\n});\n\nconst VcsStatusLocalShape = {\n  isRepo: Schema.Boolean,\n  sourceControlProvider: Schema.optional(SourceControlProviderInfo),\n  hasPrimaryRemote: Schema.Boolean,\n  isDefaultRef: Schema.Boolean,\n  refName: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  hasWorkingTreeChanges: Schema.Boolean,\n  workingTree: Schema.Struct({\n    files: Schema.Array(\n      Schema.Struct({\n        path: TrimmedNonEmptyStringSchema,\n        insertions: NonNegativeInt,\n        deletions: NonNegativeInt,\n      }),\n    ),\n    insertions: NonNegativeInt,\n    deletions: NonNegativeInt,\n  }),\n};\n\nconst VcsStatusRemoteShape = {\n  hasUpstream: Schema.Boolean,\n  aheadCount: NonNegativeInt,\n  behindCount: NonNegativeInt,\n  aheadOfDefaultCount: Schema.optional(NonNegativeInt),\n  pr: Schema.NullOr(VcsStatusChangeRequest),\n};\n\nexport const VcsStatusLocalResult = Schema.Struct(VcsStatusLocalShape);\nexport type VcsStatusLocalResult = typeof VcsStatusLocalResult.Type;\n\nexport const VcsStatusRemoteResult = Schema.Struct(VcsStatusRemoteShape);\nexport type VcsStatusRemoteResult = typeof VcsStatusRemoteResult.Type;\n\nexport const VcsStatusResult = Schema.Struct({\n  ...VcsStatusLocalShape,\n  ...VcsStatusRemoteShape,\n});\nexport type VcsStatusResult = typeof VcsStatusResult.Type;\n\nexport const VcsStatusStreamEvent = Schema.Union([\n  Schema.TaggedStruct(\"snapshot\", {\n    local: VcsStatusLocalResult,\n    remote: Schema.NullOr(VcsStatusRemoteResult),\n  }),\n  Schema.TaggedStruct(\"localUpdated\", {\n    local: VcsStatusLocalResult,\n  }),\n  Schema.TaggedStruct(\"remoteUpdated\", {\n    remote: Schema.NullOr(VcsStatusRemoteResult),\n  }),\n]);\nexport type VcsStatusStreamEvent = typeof VcsStatusStreamEvent.Type;\n\nexport const VcsListRefsResult = Schema.Struct({\n  refs: Schema.Array(VcsRef),\n  isRepo: Schema.Boolean,\n  hasPrimaryRemote: Schema.Boolean,\n  nextCursor: NonNegativeInt.pipe(Schema.NullOr),\n  totalCount: NonNegativeInt,\n});\nexport type VcsListRefsResult = typeof VcsListRefsResult.Type;\n\nexport const VcsCreateWorktreeResult = Schema.Struct({\n  worktree: VcsWorktree,\n});\nexport type VcsCreateWorktreeResult = typeof VcsCreateWorktreeResult.Type;\n\nexport const GitResolvePullRequestResult = Schema.Struct({\n  pullRequest: GitResolvedPullRequest,\n});\nexport type GitResolvePullRequestResult = typeof GitResolvePullRequestResult.Type;\n\nexport const GitPreparePullRequestThreadResult = Schema.Struct({\n  pullRequest: GitResolvedPullRequest,\n  branch: TrimmedNonEmptyStringSchema,\n  worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),\n});\nexport type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type;\n\nexport const VcsSwitchRefResult = Schema.Struct({\n  refName: Schema.NullOr(TrimmedNonEmptyStringSchema),\n});\nexport type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type;\n\nexport const GitRunStackedActionResult = Schema.Struct({\n  action: GitStackedAction,\n  branch: Schema.Struct({\n    status: GitBranchStepStatus,\n    name: Schema.optional(TrimmedNonEmptyStringSchema),\n  }),\n  commit: Schema.Struct({\n    status: GitCommitStepStatus,\n    commitSha: Schema.optional(TrimmedNonEmptyStringSchema),\n    subject: Schema.optional(TrimmedNonEmptyStringSchema),\n  }),\n  push: Schema.Struct({\n    status: GitPushStepStatus,\n    branch: Schema.optional(TrimmedNonEmptyStringSchema),\n    upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema),\n    setUpstream: Schema.optional(Schema.Boolean),\n  }),\n  pr: Schema.Struct({\n    status: GitPrStepStatus,\n    url: Schema.optional(Schema.String),\n    number: Schema.optional(PositiveInt),\n    baseBranch: Schema.optional(TrimmedNonEmptyStringSchema),\n    headBranch: Schema.optional(TrimmedNonEmptyStringSchema),\n    title: Schema.optional(TrimmedNonEmptyStringSchema),\n  }),\n  toast: GitRunStackedActionToast,\n});\nexport type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type;\n\nexport const VcsPullResult = Schema.Struct({\n  status: Schema.Literals([\"pulled\", \"skipped_up_to_date\"]),\n  refName: TrimmedNonEmptyStringSchema,\n  upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),\n});\nexport type VcsPullResult = typeof VcsPullResult.Type;\n\n// RPC / domain errors\nexport class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()(\"GitCommandError\", {\n  operation: Schema.String,\n  command: Schema.String,\n  cwd: Schema.String,\n  argumentCount: Schema.optional(Schema.Number),\n  exitCode: Schema.optional(Schema.Number),\n  stdoutLength: Schema.optional(Schema.Number),\n  stderrLength: Schema.optional(Schema.Number),\n  outputLength: Schema.optional(Schema.Number),\n  detail: Schema.String,\n  cause: Schema.optional(Schema.Defect()),\n}) {\n  override get message(): string {\n    return `Git command failed in ${this.operation} (${this.cwd}): ${this.detail}`;\n  }\n}\n\nexport class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(\n  \"TextGenerationError\",\n  {\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Text generation failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()(\"GitManagerError\", {\n  operation: Schema.String,\n  cwd: Schema.String,\n  detail: Schema.String,\n  cause: Schema.optional(Schema.Defect()),\n}) {\n  override get message(): string {\n    return `Git manager failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitPullRequestMaterializationError extends Schema.TaggedErrorClass<GitPullRequestMaterializationError>()(\n  \"GitPullRequestMaterializationError\",\n  {\n    cwd: TrimmedNonEmptyStringSchema,\n    pullRequestNumber: PositiveInt,\n    headRepository: Schema.NullOr(TrimmedNonEmptyStringSchema),\n    headBranch: TrimmedNonEmptyStringSchema,\n    localBranch: TrimmedNonEmptyStringSchema,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to materialize pull request #${this.pullRequestNumber} branch ${this.headBranch} as ${this.localBranch}.`;\n  }\n}\n\nexport const GitManagerServiceError = Schema.Union([\n  GitManagerError,\n  GitPullRequestMaterializationError,\n  GitCommandError,\n  SourceControlProviderError,\n  TextGenerationError,\n]);\nexport type GitManagerServiceError = typeof GitManagerServiceError.Type;\n\nconst GitActionProgressBase = Schema.Struct({\n  actionId: TrimmedNonEmptyStringSchema,\n  cwd: TrimmedNonEmptyStringSchema,\n  action: GitStackedAction,\n});\n\nconst GitActionStartedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"action_started\"),\n  phases: Schema.Array(GitActionProgressPhase),\n});\nconst GitActionPhaseStartedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"phase_started\"),\n  phase: GitActionProgressPhase,\n  label: TrimmedNonEmptyStringSchema,\n});\nconst GitActionHookStartedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"hook_started\"),\n  hookName: TrimmedNonEmptyStringSchema,\n});\nconst GitActionHookOutputEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"hook_output\"),\n  hookName: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  stream: GitActionProgressStream,\n  text: TrimmedNonEmptyStringSchema,\n});\nconst GitActionHookFinishedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"hook_finished\"),\n  hookName: TrimmedNonEmptyStringSchema,\n  exitCode: Schema.NullOr(Schema.Int),\n  durationMs: Schema.NullOr(NonNegativeInt),\n});\nconst GitActionFinishedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"action_finished\"),\n  result: GitRunStackedActionResult,\n});\nconst GitActionFailedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"action_failed\"),\n  phase: Schema.NullOr(GitActionProgressPhase),\n  message: TrimmedNonEmptyStringSchema,\n});\n\nexport const GitActionProgressEvent = Schema.Union([\n  GitActionStartedEvent,\n  GitActionPhaseStartedEvent,\n  GitActionHookStartedEvent,\n  GitActionHookOutputEvent,\n  GitActionHookFinishedEvent,\n  GitActionFinishedEvent,\n  GitActionFailedEvent,\n]);\nexport type GitActionProgressEvent = typeof GitActionProgressEvent.Type;\n","import * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nimport { ProjectScriptIcon } from \"./orchestration.ts\";\n\n/** File name of the checked-in T3 project file, resolved at the workspace root. */\nexport const T3_PROJECT_FILE_NAME = \"t3.json\";\n\n/** Public URL of the published JSON Schema for {@link T3ProjectFile}. */\nexport const T3_PROJECT_FILE_SCHEMA_URL = \"https://t3.codes/schema/t3.json\";\n\nconst T3_PROJECT_FILE_PATH_MAX_LENGTH = 512;\nconst T3_PROJECT_FILE_MAX_SCRIPTS = 50;\n\n// Annotations go on the encoded (string) side so they survive into the\n// published JSON Schema; decoding still trims and re-validates non-emptiness.\nconst trimmedNonEmpty = (annotations: { readonly description: string }, maxLength?: number) => {\n  const annotated = Schema.String.annotate(annotations);\n  const encoded =\n    maxLength === undefined\n      ? annotated.check(Schema.isNonEmpty())\n      : annotated.check(Schema.isNonEmpty(), Schema.isMaxLength(maxLength));\n  return encoded.pipe(Schema.decodeTo(encoded, SchemaTransformation.trim()));\n};\n\nexport const T3ProjectFileScript = Schema.Struct({\n  name: trimmedNonEmpty({\n    description: \"Display name for the script, shown in the AgentLink scripts menu.\",\n  }),\n  command: trimmedNonEmpty({\n    description: \"Shell command executed in an AgentLink terminal at the project root.\",\n  }),\n  icon: Schema.optionalKey(\n    ProjectScriptIcon.annotate({\n      description: 'Icon shown next to the script in the scripts menu. Defaults to \"play\".',\n    }),\n  ),\n  runOnWorktreeCreate: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, the script runs automatically after a worktree is created for a new thread.\",\n    }),\n  ),\n  previewUrl: Schema.optionalKey(\n    trimmedNonEmpty({\n      description:\n        \"URL opened in the in-app browser preview when this script runs. Only honored on the desktop build.\",\n    }),\n  ),\n  autoOpenPreview: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, automatically open the preview panel at `previewUrl` the moment the script starts.\",\n    }),\n  ),\n}).annotate({\n  description: \"A project script that team members can import into AgentLink.\",\n});\nexport type T3ProjectFileScript = typeof T3ProjectFileScript.Type;\n\nexport const T3ProjectFile = Schema.Struct({\n  $schema: Schema.optionalKey(\n    Schema.String.annotate({\n      description: `URL of the JSON Schema for this file, typically \"${T3_PROJECT_FILE_SCHEMA_URL}\".`,\n    }),\n  ),\n  iconPath: Schema.optionalKey(\n    trimmedNonEmpty(\n      {\n        description:\n          'Workspace-relative path to the project icon (e.g. \"assets/logo.svg\"). Checked before AgentLink\\'s built-in icon locations.',\n      },\n      T3_PROJECT_FILE_PATH_MAX_LENGTH,\n    ),\n  ),\n  scripts: Schema.optionalKey(\n    Schema.Array(T3ProjectFileScript)\n      .annotate({\n        description: \"Project scripts shared with everyone who opens this repository in AgentLink.\",\n      })\n      .check(Schema.isMaxLength(T3_PROJECT_FILE_MAX_SCRIPTS)),\n  ),\n}).annotate({\n  title: \"T3 project file\",\n  description:\n    \"Checked-in project configuration for AgentLink (t3.json at the repository root).\",\n});\nexport type T3ProjectFile = typeof T3ProjectFile.Type;\n","import * as Schema from \"effect/Schema\";\nimport {\n  NonNegativeInt,\n  PositiveInt,\n  TrimmedNonEmptyString,\n  TrimmedString,\n} from \"./baseSchemas.ts\";\n\nconst PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;\nconst PROJECT_SEARCH_CONTENTS_MAX_LIMIT = 500;\nconst PROJECT_WRITE_FILE_PATH_MAX_LENGTH = 512;\nconst PROJECT_READ_FILE_PATH_MAX_LENGTH = 512;\n\nexport const ProjectEntryKind = Schema.Literals([\"file\", \"directory\"]);\nexport type ProjectEntryKind = typeof ProjectEntryKind.Type;\n\nexport const ProjectSearchEntriesInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  // An empty query is a bounded browse: the index returns frecency-ordered\n  // entries, which the file picker uses for its initial results.\n  query: TrimmedString.check(Schema.isMaxLength(256)),\n  limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)),\n  kind: Schema.optional(ProjectEntryKind),\n});\nexport type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;\n\nexport const ProjectEntry = Schema.Struct({\n  path: TrimmedNonEmptyString,\n  kind: ProjectEntryKind,\n});\nexport type ProjectEntry = typeof ProjectEntry.Type;\n\nexport const ProjectSearchEntriesResult = Schema.Struct({\n  entries: Schema.Array(ProjectEntry),\n  truncated: Schema.Boolean,\n});\nexport type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;\n\nexport const ProjectSearchContentsInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  // Whitespace is significant in content queries (\" foo\", regex trailing\n  // spaces), so the query is deliberately not trimmed on the wire.\n  query: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)),\n  limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_CONTENTS_MAX_LIMIT)),\n  caseSensitive: Schema.Boolean,\n  wholeWord: Schema.Boolean,\n  useRegex: Schema.Boolean,\n});\nexport type ProjectSearchContentsInput = typeof ProjectSearchContentsInput.Type;\n\nexport const ProjectContentMatchRange = Schema.Struct({\n  start: NonNegativeInt,\n  end: NonNegativeInt,\n});\nexport type ProjectContentMatchRange = typeof ProjectContentMatchRange.Type;\n\nexport const ProjectContentMatch = Schema.Struct({\n  path: TrimmedNonEmptyString,\n  lineNumber: PositiveInt,\n  lineContent: Schema.String,\n  matchRanges: Schema.Array(ProjectContentMatchRange),\n});\nexport type ProjectContentMatch = typeof ProjectContentMatch.Type;\n\nexport const ProjectSearchContentsResult = Schema.Struct({\n  matches: Schema.Array(ProjectContentMatch),\n  truncated: Schema.Boolean,\n  regexFallbackError: Schema.optional(Schema.String),\n});\nexport type ProjectSearchContentsResult = typeof ProjectSearchContentsResult.Type;\n\nexport const ProjectListEntriesInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n});\nexport type ProjectListEntriesInput = typeof ProjectListEntriesInput.Type;\n\nexport const ProjectListEntriesResult = Schema.Struct({\n  entries: Schema.Array(ProjectEntry),\n  truncated: Schema.Boolean,\n});\nexport type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;\n\nexport const ProjectEntriesFailure = Schema.Literals([\n  \"workspace_root_not_found\",\n  \"workspace_root_create_failed\",\n  \"workspace_root_stat_failed\",\n  \"workspace_root_not_directory\",\n  \"search_index_create_failed\",\n  \"search_index_scan_timed_out\",\n  \"search_index_search_failed\",\n]);\nexport type ProjectEntriesFailure = typeof ProjectEntriesFailure.Type;\n\ntype ProjectEntriesFailureContext = {\n  readonly failure: ProjectEntriesFailure;\n  readonly normalizedCwd?: string;\n  readonly timeout?: string;\n  readonly detail?: string;\n  readonly cause?: unknown;\n};\n\nfunction decodedProjectErrorMessage(props: object): string | undefined {\n  if (!(\"message\" in props)) return undefined;\n  return typeof props.message === \"string\" ? props.message : undefined;\n}\n\nexport class ProjectSearchEntriesError extends Schema.TaggedErrorClass<ProjectSearchEntriesError>()(\n  \"ProjectSearchEntriesError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    queryLength: Schema.optional(NonNegativeInt),\n    limit: Schema.optional(PositiveInt),\n    failure: Schema.optional(ProjectEntriesFailure),\n    normalizedCwd: Schema.optional(TrimmedNonEmptyString),\n    timeout: Schema.optional(TrimmedNonEmptyString),\n    detail: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // The structured fields are optional on the wire so newer peers can decode legacy message-only\n  // failures. New application code must provide them through this constructor.\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(\n    props: ProjectEntriesFailureContext & {\n      readonly cwd: string;\n      readonly queryLength: number;\n      readonly limit: number;\n    },\n  ) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to search workspace entries in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport class ProjectSearchContentsError extends Schema.TaggedErrorClass<ProjectSearchContentsError>()(\n  \"ProjectSearchContentsError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    queryLength: Schema.optional(NonNegativeInt),\n    limit: Schema.optional(PositiveInt),\n    failure: Schema.optional(ProjectEntriesFailure),\n    normalizedCwd: Schema.optional(TrimmedNonEmptyString),\n    timeout: Schema.optional(TrimmedNonEmptyString),\n    detail: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(\n    props: ProjectEntriesFailureContext & {\n      readonly cwd: string;\n      readonly queryLength: number;\n      readonly limit: number;\n    },\n  ) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to search workspace contents in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport class ProjectListEntriesError extends Schema.TaggedErrorClass<ProjectListEntriesError>()(\n  \"ProjectListEntriesError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(ProjectEntriesFailure),\n    normalizedCwd: Schema.optional(TrimmedNonEmptyString),\n    timeout: Schema.optional(TrimmedNonEmptyString),\n    detail: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: ProjectEntriesFailureContext & { readonly cwd: string }) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ?? `Failed to list workspace entries in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport const ProjectReadFileInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_READ_FILE_PATH_MAX_LENGTH)),\n});\nexport type ProjectReadFileInput = typeof ProjectReadFileInput.Type;\n\nexport const ProjectReadFileResult = Schema.Struct({\n  relativePath: TrimmedNonEmptyString,\n  contents: Schema.String,\n  byteLength: NonNegativeInt,\n  truncated: Schema.Boolean,\n});\nexport type ProjectReadFileResult = typeof ProjectReadFileResult.Type;\n\nexport const ProjectFileFailure = Schema.Literals([\n  \"workspace_path_outside_root\",\n  \"resolved_path_outside_root\",\n  \"path_not_file\",\n  \"binary_file\",\n  \"operation_failed\",\n]);\nexport type ProjectFileFailure = typeof ProjectFileFailure.Type;\n\nexport const ProjectFileOperation = Schema.Literals([\n  \"realpath-workspace-root\",\n  \"realpath-target\",\n  \"open\",\n  \"stat\",\n  \"read\",\n  \"close\",\n  \"make-directory\",\n  \"write-file\",\n]);\nexport type ProjectFileOperation = typeof ProjectFileOperation.Type;\n\ntype ProjectFileFailureContext = {\n  readonly cwd: string;\n  readonly relativePath: string;\n  readonly failure: ProjectFileFailure;\n  readonly resolvedPath?: string;\n  readonly resolvedWorkspaceRoot?: string;\n  readonly operation?: ProjectFileOperation;\n  readonly operationPath?: string;\n  readonly cause?: unknown;\n};\n\nexport class ProjectReadFileError extends Schema.TaggedErrorClass<ProjectReadFileError>()(\n  \"ProjectReadFileError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    relativePath: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(ProjectFileFailure),\n    resolvedPath: Schema.optional(TrimmedNonEmptyString),\n    resolvedWorkspaceRoot: Schema.optional(TrimmedNonEmptyString),\n    operation: Schema.optional(ProjectFileOperation),\n    operationPath: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: ProjectFileFailureContext) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to read workspace file '${props.relativePath}' in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport const ProjectWriteFileInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)),\n  contents: Schema.String,\n});\nexport type ProjectWriteFileInput = typeof ProjectWriteFileInput.Type;\n\nexport const ProjectWriteFileResult = Schema.Struct({\n  relativePath: TrimmedNonEmptyString,\n});\nexport type ProjectWriteFileResult = typeof ProjectWriteFileResult.Type;\n\nexport class ProjectWriteFileError extends Schema.TaggedErrorClass<ProjectWriteFileError>()(\n  \"ProjectWriteFileError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    relativePath: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(ProjectFileFailure),\n    resolvedPath: Schema.optional(TrimmedNonEmptyString),\n    resolvedWorkspaceRoot: Schema.optional(TrimmedNonEmptyString),\n    operation: Schema.optional(ProjectFileOperation),\n    operationPath: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: ProjectFileFailureContext) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to write workspace file '${props.relativePath}' in '${props.cwd}'.`,\n    } as any);\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst FILESYSTEM_PATH_MAX_LENGTH = 512;\n\nexport const FilesystemBrowseInput = Schema.Struct({\n  partialPath: TrimmedNonEmptyString.check(Schema.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)),\n  cwd: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH))),\n});\nexport type FilesystemBrowseInput = typeof FilesystemBrowseInput.Type;\n\nexport const FilesystemBrowseEntry = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  fullPath: TrimmedNonEmptyString,\n});\nexport type FilesystemBrowseEntry = typeof FilesystemBrowseEntry.Type;\n\nexport const FilesystemBrowseResult = Schema.Struct({\n  parentPath: TrimmedNonEmptyString,\n  entries: Schema.Array(FilesystemBrowseEntry),\n});\nexport type FilesystemBrowseResult = typeof FilesystemBrowseResult.Type;\n\nexport const FilesystemBrowseFailure = Schema.Literals([\n  \"windows_path_unsupported\",\n  \"current_project_required\",\n  \"read_directory_failed\",\n]);\nexport type FilesystemBrowseFailure = typeof FilesystemBrowseFailure.Type;\n\nfunction decodedFilesystemBrowseErrorMessage(props: object): string | undefined {\n  if (!(\"message\" in props)) return undefined;\n  return typeof props.message === \"string\" ? props.message : undefined;\n}\n\nexport class FilesystemBrowseError extends Schema.TaggedErrorClass<FilesystemBrowseError>()(\n  \"FilesystemBrowseError\",\n  {\n    partialPath: Schema.optional(TrimmedNonEmptyString),\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(FilesystemBrowseFailure),\n    parentPath: Schema.optional(TrimmedNonEmptyString),\n    platform: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // Structured diagnostics stay optional for rolling compatibility with legacy message-only\n  // payloads, while new call sites must provide the request context and failure classification.\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: {\n    readonly partialPath: string;\n    readonly cwd?: string | undefined;\n    readonly failure: FilesystemBrowseFailure;\n    readonly parentPath?: string;\n    readonly platform?: string;\n    readonly cause?: unknown;\n  }) {\n    const cwd = props.cwd === undefined ? \"\" : ` from '${props.cwd}'`;\n    super({\n      ...props,\n      message:\n        decodedFilesystemBrowseErrorMessage(props) ??\n        `Failed to browse filesystem path '${props.partialPath}'${cwd}.`,\n    } as any);\n  }\n}\n","import * as Schema from \"effect/Schema\";\n\nimport { ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst ASSET_PATH_MAX_LENGTH = 1024;\n\nexport const AssetResource = Schema.Union([\n  Schema.TaggedStruct(\"workspace-file\", {\n    threadId: ThreadId,\n    path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),\n  }),\n  Schema.TaggedStruct(\"attachment\", {\n    attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),\n  }),\n  Schema.TaggedStruct(\"project-favicon\", {\n    cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),\n  }),\n]);\nexport type AssetResource = typeof AssetResource.Type;\n\nexport const AssetCreateUrlInput = Schema.Struct({\n  resource: AssetResource,\n});\nexport type AssetCreateUrlInput = typeof AssetCreateUrlInput.Type;\n\nexport const AssetCreateUrlResult = Schema.Struct({\n  relativeUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),\n  expiresAt: Schema.Number,\n});\nexport type AssetCreateUrlResult = typeof AssetCreateUrlResult.Type;\n\nexport class AssetWorkspaceContextNotFoundError extends Schema.TaggedErrorClass<AssetWorkspaceContextNotFoundError>()(\n  \"AssetWorkspaceContextNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Workspace context was not found.\";\n  }\n}\n\nexport class AssetWorkspaceContextResolutionError extends Schema.TaggedErrorClass<AssetWorkspaceContextResolutionError>()(\n  \"AssetWorkspaceContextResolutionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to resolve workspace context.\";\n  }\n}\n\nexport class AssetWorkspaceRootNormalizationError extends Schema.TaggedErrorClass<AssetWorkspaceRootNormalizationError>()(\n  \"AssetWorkspaceRootNormalizationError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to normalize the workspace root.\";\n  }\n}\n\nexport class AssetWorkspacePathValidationError extends Schema.TaggedErrorClass<AssetWorkspacePathValidationError>()(\n  \"AssetWorkspacePathValidationError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Workspace file path must be relative to the project root.\";\n  }\n}\n\nexport class AssetPreviewTypeValidationError extends Schema.TaggedErrorClass<AssetPreviewTypeValidationError>()(\n  \"AssetPreviewTypeValidationError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Only browser documents and images can be previewed.\";\n  }\n}\n\nexport class AssetWorkspaceAssetInspectionError extends Schema.TaggedErrorClass<AssetWorkspaceAssetInspectionError>()(\n  \"AssetWorkspaceAssetInspectionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to inspect the workspace asset.\";\n  }\n}\n\nexport class AssetWorkspaceAssetNotFoundError extends Schema.TaggedErrorClass<AssetWorkspaceAssetNotFoundError>()(\n  \"AssetWorkspaceAssetNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Workspace asset was not found.\";\n  }\n}\n\nexport class AssetWorkspaceResolutionError extends Schema.TaggedErrorClass<AssetWorkspaceResolutionError>()(\n  \"AssetWorkspaceResolutionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to resolve workspace.\";\n  }\n}\n\nexport class AssetAttachmentNotFoundError extends Schema.TaggedErrorClass<AssetAttachmentNotFoundError>()(\n  \"AssetAttachmentNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Attachment was not found.\";\n  }\n}\n\nexport class AssetProjectFaviconResolutionError extends Schema.TaggedErrorClass<AssetProjectFaviconResolutionError>()(\n  \"AssetProjectFaviconResolutionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to resolve project favicon.\";\n  }\n}\n\nexport class AssetProjectFaviconInspectionError extends Schema.TaggedErrorClass<AssetProjectFaviconInspectionError>()(\n  \"AssetProjectFaviconInspectionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to inspect the project favicon.\";\n  }\n}\n\nexport class AssetProjectFaviconNotFoundError extends Schema.TaggedErrorClass<AssetProjectFaviconNotFoundError>()(\n  \"AssetProjectFaviconNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Project favicon was not found.\";\n  }\n}\n\nexport class AssetSigningKeyLoadError extends Schema.TaggedErrorClass<AssetSigningKeyLoadError>()(\n  \"AssetSigningKeyLoadError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to load the asset signing key.\";\n  }\n}\n\nexport const AssetAccessError = Schema.Union([\n  AssetWorkspaceContextNotFoundError,\n  AssetWorkspaceContextResolutionError,\n  AssetWorkspaceRootNormalizationError,\n  AssetWorkspacePathValidationError,\n  AssetPreviewTypeValidationError,\n  AssetWorkspaceAssetInspectionError,\n  AssetWorkspaceAssetNotFoundError,\n  AssetWorkspaceResolutionError,\n  AssetAttachmentNotFoundError,\n  AssetProjectFaviconResolutionError,\n  AssetProjectFaviconInspectionError,\n  AssetProjectFaviconNotFoundError,\n  AssetSigningKeyLoadError,\n]);\nexport type AssetAccessError = typeof AssetAccessError.Type;\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { GitCommandError } from \"./git.ts\";\nimport { VcsError } from \"./vcs.ts\";\n\nexport const ReviewDiffPreviewInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  baseRef: Schema.optional(TrimmedNonEmptyString),\n  ignoreWhitespace: Schema.optionalKey(Schema.Boolean),\n});\nexport type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;\n\nexport const ReviewDiffPreviewSourceKind = Schema.Literals([\"working-tree\", \"branch-range\"]);\nexport type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;\n\nexport const ReviewDiffPreviewSource = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  kind: ReviewDiffPreviewSourceKind,\n  title: TrimmedNonEmptyString,\n  baseRef: Schema.NullOr(TrimmedNonEmptyString),\n  headRef: Schema.NullOr(TrimmedNonEmptyString),\n  diff: Schema.String,\n  diffHash: TrimmedNonEmptyString,\n  truncated: Schema.Boolean,\n});\nexport type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type;\n\nexport const ReviewDiffFileContentsInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  sourceKind: ReviewDiffPreviewSourceKind,\n  changeType: Schema.Literals([\"change\", \"rename-pure\", \"rename-changed\", \"new\", \"deleted\"]),\n  baseRef: Schema.NullOr(TrimmedNonEmptyString),\n  headRef: Schema.NullOr(TrimmedNonEmptyString),\n  oldPath: TrimmedNonEmptyString,\n  newPath: TrimmedNonEmptyString,\n});\nexport type ReviewDiffFileContentsInput = typeof ReviewDiffFileContentsInput.Type;\n\nexport const ReviewDiffFileContentsResult = Schema.Struct({\n  oldContents: Schema.String,\n  newContents: Schema.String,\n});\nexport type ReviewDiffFileContentsResult = typeof ReviewDiffFileContentsResult.Type;\n\nexport const ReviewDiffPreviewResult = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  generatedAt: Schema.DateTimeUtc,\n  sources: Schema.Array(ReviewDiffPreviewSource),\n});\nexport type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;\n\nexport const ReviewDiffPreviewError = Schema.Union([VcsError, GitCommandError]);\nexport type ReviewDiffPreviewError = typeof ReviewDiffPreviewError.Type;\n","import * as Schema from \"effect/Schema\";\n\nimport { PortSchema } from \"./baseSchemas.ts\";\n\nexport const PortProxyPort = PortSchema.pipe(Schema.brand(\"PortProxyPort\"));\nexport type PortProxyPort = typeof PortProxyPort.Type;\n\nexport const PortProxyListResult = Schema.Struct({ ports: Schema.Array(PortProxyPort) });\nexport type PortProxyListResult = typeof PortProxyListResult.Type;\n\nexport const PortProxyPortInput = Schema.Struct({ port: PortProxyPort });\nexport type PortProxyPortInput = typeof PortProxyPortInput.Type;\n","import * as Schema from \"effect/Schema\";\n\nimport { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { HostPowerSnapshot } from \"./background.ts\";\n\nexport const RESOURCE_MONITOR_PROTOCOL_VERSION = 2 as const;\n\nexport const ResourceTelemetryIoSemantics = Schema.Literals([\n  \"storage\",\n  \"logical\",\n  \"all-io\",\n  \"unavailable\",\n]);\nexport type ResourceTelemetryIoSemantics = typeof ResourceTelemetryIoSemantics.Type;\n\nexport const ResourceTelemetryProcessCategory = Schema.Literals([\n  \"server\",\n  \"server-child\",\n  \"provider-root\",\n  \"terminal-root\",\n  \"electron-main\",\n  \"electron-renderer\",\n  \"electron-gpu\",\n  \"electron-utility\",\n  \"resource-monitor\",\n  \"unknown-t3\",\n]);\nexport type ResourceTelemetryProcessCategory = typeof ResourceTelemetryProcessCategory.Type;\n\nexport const ResourceTelemetrySourceStatus = Schema.Literals([\n  \"starting\",\n  \"healthy\",\n  \"degraded\",\n  \"unavailable\",\n  \"stopped\",\n]);\nexport type ResourceTelemetrySourceStatus = typeof ResourceTelemetrySourceStatus.Type;\n\nexport const ResourceTelemetryProcessIdentity = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: NonNegativeInt,\n});\nexport type ResourceTelemetryProcessIdentity = typeof ResourceTelemetryProcessIdentity.Type;\n\nexport const ResourceMonitorExternalProcess = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: Schema.optionalKey(NonNegativeInt),\n});\nexport type ResourceMonitorExternalProcess = typeof ResourceMonitorExternalProcess.Type;\n\nexport const ResourceMonitorCapabilities = Schema.Struct({\n  cumulativeCpuTime: Schema.Boolean,\n  currentCpuPercent: Schema.Boolean,\n  residentMemory: Schema.Boolean,\n  virtualMemory: Schema.Boolean,\n  ioBytes: Schema.Boolean,\n  processStartTime: Schema.Boolean,\n  processTree: Schema.Boolean,\n});\nexport type ResourceMonitorCapabilities = typeof ResourceMonitorCapabilities.Type;\n\nexport const ResourceMonitorProcessSample = Schema.Struct({\n  pid: PositiveInt,\n  ppid: NonNegativeInt,\n  startTimeMs: NonNegativeInt,\n  runTimeMs: NonNegativeInt,\n  name: Schema.String,\n  command: Schema.String,\n  status: Schema.String,\n  cpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  residentBytes: NonNegativeInt,\n  virtualBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioSemantics: Schema.Literals([\"storage\", \"all-io\"]),\n});\nexport type ResourceMonitorProcessSample = typeof ResourceMonitorProcessSample.Type;\n\nexport const ResourceMonitorConfigureCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"configure\"),\n  rootPid: PositiveInt,\n  sampleIntervalMs: NonNegativeInt,\n  externalProcesses: Schema.Array(ResourceMonitorExternalProcess),\n});\nexport type ResourceMonitorConfigureCommand = typeof ResourceMonitorConfigureCommand.Type;\n\nexport const ResourceMonitorSetExternalProcessesCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"setExternalProcesses\"),\n  processes: Schema.Array(ResourceMonitorExternalProcess),\n});\nexport type ResourceMonitorSetExternalProcessesCommand =\n  typeof ResourceMonitorSetExternalProcessesCommand.Type;\n\nexport const ResourceMonitorSampleNowCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"sampleNow\"),\n  requestId: TrimmedNonEmptyString,\n});\nexport type ResourceMonitorSampleNowCommand = typeof ResourceMonitorSampleNowCommand.Type;\n\nexport const ResourceMonitorSetSampleIntervalCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"setSampleInterval\"),\n  sampleIntervalMs: NonNegativeInt,\n});\nexport type ResourceMonitorSetSampleIntervalCommand =\n  typeof ResourceMonitorSetSampleIntervalCommand.Type;\n\nexport const ResourceMonitorSetStreamingCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"setStreaming\"),\n  enabled: Schema.Boolean,\n});\nexport type ResourceMonitorSetStreamingCommand = typeof ResourceMonitorSetStreamingCommand.Type;\n\nexport const ResourceMonitorReadHistoryCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"readHistory\"),\n  requestId: TrimmedNonEmptyString,\n  windowMs: NonNegativeInt,\n});\nexport type ResourceMonitorReadHistoryCommand = typeof ResourceMonitorReadHistoryCommand.Type;\n\nexport const ResourceMonitorShutdownCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"shutdown\"),\n});\nexport type ResourceMonitorShutdownCommand = typeof ResourceMonitorShutdownCommand.Type;\n\nexport const ResourceMonitorCommand = Schema.Union([\n  ResourceMonitorConfigureCommand,\n  ResourceMonitorSetExternalProcessesCommand,\n  ResourceMonitorSetSampleIntervalCommand,\n  ResourceMonitorSetStreamingCommand,\n  ResourceMonitorSampleNowCommand,\n  ResourceMonitorReadHistoryCommand,\n  ResourceMonitorShutdownCommand,\n]);\nexport type ResourceMonitorCommand = typeof ResourceMonitorCommand.Type;\n\nexport const ResourceMonitorHelloEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"hello\"),\n  sidecarVersion: TrimmedNonEmptyString,\n  sidecarPid: PositiveInt,\n  platform: TrimmedNonEmptyString,\n  arch: TrimmedNonEmptyString,\n  capabilities: ResourceMonitorCapabilities,\n});\nexport type ResourceMonitorHelloEvent = typeof ResourceMonitorHelloEvent.Type;\n\nexport const ResourceMonitorSnapshotEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"snapshot\"),\n  sequence: NonNegativeInt,\n  sampledAtUnixMs: NonNegativeInt,\n  collectionDurationMicros: NonNegativeInt,\n  scannedProcessCount: NonNegativeInt,\n  retainedProcessCount: NonNegativeInt,\n  inaccessibleProcessCount: NonNegativeInt,\n  requestId: Schema.optionalKey(TrimmedNonEmptyString),\n  externalProcesses: Schema.optionalKey(Schema.Array(ResourceMonitorExternalProcess)),\n  processes: Schema.Array(ResourceMonitorProcessSample),\n});\nexport type ResourceMonitorSnapshotEvent = typeof ResourceMonitorSnapshotEvent.Type;\n\nexport const ResourceMonitorHistoryChunkEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"historyChunk\"),\n  requestId: TrimmedNonEmptyString,\n  done: Schema.Boolean,\n  snapshots: Schema.Array(ResourceMonitorSnapshotEvent),\n});\nexport type ResourceMonitorHistoryChunkEvent = typeof ResourceMonitorHistoryChunkEvent.Type;\n\nexport const ResourceMonitorErrorEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"error\"),\n  code: TrimmedNonEmptyString,\n  message: TrimmedNonEmptyString,\n  recoverable: Schema.Boolean,\n});\nexport type ResourceMonitorErrorEvent = typeof ResourceMonitorErrorEvent.Type;\n\nexport const ResourceMonitorEvent = Schema.Union([\n  ResourceMonitorHelloEvent,\n  ResourceMonitorSnapshotEvent,\n  ResourceMonitorHistoryChunkEvent,\n  ResourceMonitorErrorEvent,\n]);\nexport type ResourceMonitorEvent = typeof ResourceMonitorEvent.Type;\n\nexport const DesktopElectronProcessType = Schema.Literals([\n  \"Browser\",\n  \"Tab\",\n  \"Utility\",\n  \"Zygote\",\n  \"Sandbox helper\",\n  \"GPU\",\n  \"Pepper Plugin\",\n  \"Pepper Plugin Broker\",\n  \"Unknown\",\n]);\nexport type DesktopElectronProcessType = typeof DesktopElectronProcessType.Type;\n\nexport const DesktopElectronProcessMetric = Schema.Struct({\n  pid: PositiveInt,\n  creationTimeMs: NonNegativeInt,\n  type: DesktopElectronProcessType,\n  name: Schema.optionalKey(Schema.String),\n  serviceName: Schema.optionalKey(Schema.String),\n  cpuPercent: Schema.Number,\n  cumulativeCpuSeconds: Schema.optionalKey(Schema.Number),\n  idleWakeupsPerSecond: Schema.Number,\n  workingSetBytes: NonNegativeInt,\n  peakWorkingSetBytes: NonNegativeInt,\n});\nexport type DesktopElectronProcessMetric = typeof DesktopElectronProcessMetric.Type;\n\nconst DesktopHostPowerSnapshot = Schema.Struct({\n  ...HostPowerSnapshot.fields,\n  updatedAt: Schema.DateTimeUtcFromString,\n});\n\nexport const DesktopHostTelemetrySnapshot = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"desktopTelemetry\"),\n  sequence: NonNegativeInt,\n  sampledAtUnixMs: NonNegativeInt,\n  electronPid: PositiveInt,\n  power: DesktopHostPowerSnapshot,\n  speedLimitPercent: Schema.OptionFromNullOr(Schema.Number),\n  electronProcesses: Schema.Array(DesktopElectronProcessMetric),\n});\nexport type DesktopHostTelemetrySnapshot = typeof DesktopHostTelemetrySnapshot.Type;\n\nexport const DesktopHostTelemetryHello = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"desktopTelemetryHello\"),\n  electronPid: PositiveInt,\n});\nexport type DesktopHostTelemetryHello = typeof DesktopHostTelemetryHello.Type;\n\nexport const DesktopHostTelemetryMessage = Schema.Union([\n  DesktopHostTelemetryHello,\n  DesktopHostTelemetrySnapshot,\n]);\nexport type DesktopHostTelemetryMessage = typeof DesktopHostTelemetryMessage.Type;\n\nexport const DesktopTelemetrySetDiagnosticsDemand = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"setDiagnosticsDemand\"),\n  enabled: Schema.Boolean,\n});\nexport type DesktopTelemetrySetDiagnosticsDemand = typeof DesktopTelemetrySetDiagnosticsDemand.Type;\n\nexport const DesktopTelemetrySetHostPowerIntervals = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"setHostPowerIntervals\"),\n  activeIntervalMs: PositiveInt,\n  idleIntervalMs: PositiveInt,\n});\nexport type DesktopTelemetrySetHostPowerIntervals =\n  typeof DesktopTelemetrySetHostPowerIntervals.Type;\n\nexport const DesktopTelemetryControlMessage = Schema.Union([\n  DesktopTelemetrySetDiagnosticsDemand,\n  DesktopTelemetrySetHostPowerIntervals,\n]);\nexport type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;\n\nexport const ResourceTelemetryProcess = Schema.Struct({\n  identity: ResourceTelemetryProcessIdentity,\n  ppid: NonNegativeInt,\n  childPids: Schema.Array(PositiveInt),\n  depth: NonNegativeInt,\n  name: Schema.String,\n  command: Schema.String,\n  status: Schema.String,\n  category: ResourceTelemetryProcessCategory,\n  electronType: Schema.optionalKey(DesktopElectronProcessType),\n  electronServiceName: Schema.optionalKey(Schema.String),\n  cpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  residentBytes: NonNegativeInt,\n  peakResidentBytes: NonNegativeInt,\n  virtualBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioReadBytesPerSecond: Schema.Number,\n  ioWriteBytesPerSecond: Schema.Number,\n  ioSemantics: ResourceTelemetryIoSemantics,\n  idleWakeupsPerSecond: Schema.optionalKey(Schema.Number),\n  runTimeMs: NonNegativeInt,\n  firstSeenAt: Schema.DateTimeUtc,\n  lastSeenAt: Schema.DateTimeUtc,\n});\nexport type ResourceTelemetryProcess = typeof ResourceTelemetryProcess.Type;\n\nexport const ResourceTelemetryAggregate = Schema.Struct({\n  processCount: NonNegativeInt,\n  currentCpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  currentRssBytes: NonNegativeInt,\n  peakRssBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioReadBytesPerSecond: Schema.Number,\n  ioWriteBytesPerSecond: Schema.Number,\n  processStarts: NonNegativeInt,\n  processExits: NonNegativeInt,\n});\nexport type ResourceTelemetryAggregate = typeof ResourceTelemetryAggregate.Type;\n\nexport const ResourceTelemetryGroups = Schema.Struct({\n  backend: ResourceTelemetryAggregate,\n  electron: ResourceTelemetryAggregate,\n  monitor: ResourceTelemetryAggregate,\n  allT3: ResourceTelemetryAggregate,\n});\nexport type ResourceTelemetryGroups = typeof ResourceTelemetryGroups.Type;\n\nexport const ResourceTelemetrySourceHealth = Schema.Struct({\n  status: ResourceTelemetrySourceStatus,\n  lastSampleAt: Schema.Option(Schema.DateTimeUtc),\n  lastError: Schema.Option(TrimmedNonEmptyString),\n});\nexport type ResourceTelemetrySourceHealth = typeof ResourceTelemetrySourceHealth.Type;\n\nexport const ResourceTelemetryHealth = Schema.Struct({\n  native: ResourceTelemetrySourceHealth,\n  desktop: ResourceTelemetrySourceHealth,\n  sidecarVersion: Schema.Option(TrimmedNonEmptyString),\n  sidecarPid: Schema.Option(PositiveInt),\n  restartCount: NonNegativeInt,\n  collectionDurationMicros: NonNegativeInt,\n  scannedProcessCount: NonNegativeInt,\n  retainedProcessCount: NonNegativeInt,\n  inaccessibleProcessCount: NonNegativeInt,\n});\nexport type ResourceTelemetryHealth = typeof ResourceTelemetryHealth.Type;\n\nexport const ResourceAttributionEntry = Schema.Struct({\n  component: TrimmedNonEmptyString,\n  operation: TrimmedNonEmptyString,\n  logicalReadBytes: NonNegativeInt,\n  logicalWriteBytes: NonNegativeInt,\n  count: NonNegativeInt,\n  durationMs: NonNegativeInt,\n});\nexport type ResourceAttributionEntry = typeof ResourceAttributionEntry.Type;\n\nexport const ResourceAttributionSnapshot = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  entries: Schema.Array(ResourceAttributionEntry),\n});\nexport type ResourceAttributionSnapshot = typeof ResourceAttributionSnapshot.Type;\n\nexport const ResourceTelemetrySnapshot = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  sampleIntervalMs: NonNegativeInt,\n  processes: Schema.Array(ResourceTelemetryProcess),\n  groups: ResourceTelemetryGroups,\n  power: HostPowerSnapshot,\n  speedLimitPercent: Schema.Option(Schema.Number),\n  attribution: ResourceAttributionSnapshot,\n  health: ResourceTelemetryHealth,\n});\nexport type ResourceTelemetrySnapshot = typeof ResourceTelemetrySnapshot.Type;\n\nexport const ResourceTelemetryHistoryInput = Schema.Struct({\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n});\nexport type ResourceTelemetryHistoryInput = typeof ResourceTelemetryHistoryInput.Type;\n\nexport const ResourceTelemetryHistoryBucket = Schema.Struct({\n  startedAt: Schema.DateTimeUtc,\n  endedAt: Schema.DateTimeUtc,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  maxRssBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  maxProcessCount: NonNegativeInt,\n});\nexport type ResourceTelemetryHistoryBucket = typeof ResourceTelemetryHistoryBucket.Type;\n\nexport const ResourceTelemetryProcessSummary = Schema.Struct({\n  identity: ResourceTelemetryProcessIdentity,\n  ppid: NonNegativeInt,\n  depth: NonNegativeInt,\n  name: Schema.String,\n  command: Schema.String,\n  category: ResourceTelemetryProcessCategory,\n  firstSeenAt: Schema.DateTimeUtc,\n  lastSeenAt: Schema.DateTimeUtc,\n  currentCpuPercent: Schema.Number,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  currentRssBytes: NonNegativeInt,\n  peakRssBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioSemantics: ResourceTelemetryIoSemantics,\n  sampleCount: NonNegativeInt,\n});\nexport type ResourceTelemetryProcessSummary = typeof ResourceTelemetryProcessSummary.Type;\n\nexport const ResourceTelemetryHistory = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n  sampleIntervalMs: NonNegativeInt,\n  retainedSampleCount: NonNegativeInt,\n  buckets: Schema.Array(ResourceTelemetryHistoryBucket),\n  topProcesses: Schema.Array(ResourceTelemetryProcessSummary),\n  health: ResourceTelemetryHealth,\n});\nexport type ResourceTelemetryHistory = typeof ResourceTelemetryHistory.Type;\n\nexport const ResourceTelemetryRetryResult = Schema.Struct({\n  accepted: Schema.Boolean,\n  snapshot: ResourceTelemetrySnapshot,\n});\nexport type ResourceTelemetryRetryResult = typeof ResourceTelemetryRetryResult.Type;\n","/**\n * RPC schema markers and interruption annotations.\n *\n * This module contains the small pieces of schema metadata that the RPC\n * declaration, client, server, cluster, and reactivity layers share. It marks\n * streamed responses and annotates interruptions that came from a remote client\n * closing or cancelling a request.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport { constUndefined } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Stream_ from \"../../Stream.js\";\nconst StreamSchemaTypeId = \"~effect/rpc/RpcSchema/StreamSchema\";\n/**\n * Returns `true` when a schema is an RPC stream schema created by\n * `RpcSchema.Stream`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport function isStreamSchema(schema) {\n  return Predicate.hasProperty(schema, StreamSchemaTypeId);\n}\n/** @internal */\nexport function getStreamSchemas(schema) {\n  return isStreamSchema(schema) ? Option.some({\n    success: schema.success,\n    error: schema.error\n  }) : Option.none();\n}\nconst schema = /*#__PURE__*/Schema.declare(Stream_.isStream);\n/**\n * Creates an RPC stream schema from a stream element success schema and stream\n * error schema.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport function Stream(success, error) {\n  return Schema.make(schema.ast, {\n    [StreamSchemaTypeId]: StreamSchemaTypeId,\n    success,\n    error\n  });\n}\n/**\n * Annotation that marks interruptions that originate from an RPC client\n * abort.\n *\n * @category services\n * @since 4.0.0\n */\nexport class ClientAbort extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcSchema/ClientAbort\") {\n  static annotation = /*#__PURE__*/this.context(true).pipe(/*#__PURE__*/Context.add(Cause.StackTrace, {\n    name: \"ClientAbort\",\n    stack: constUndefined,\n    parent: undefined\n  }));\n}\n//# sourceMappingURL=RpcSchema.js.map","import * as Context from \"../../Context.js\";\nimport * as Option from \"../../Option.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as PrimaryKey from \"../../PrimaryKey.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nconst TypeId = \"~effect/rpc/Rpc\";\n/**\n * Returns `true` when the value is an `Rpc` definition.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isRpc = u => Predicate.hasProperty(u, TypeId);\n/**\n * Represents server-side metadata for the client associated with an RPC request.\n *\n * **When to use**\n *\n * Use to inspect or annotate the connected client while handling an RPC request\n * on the server.\n *\n * **Details**\n *\n * It stores the client id and request annotations that handlers can read or\n * extend.\n *\n * @category models\n * @since 4.0.0\n */\nexport class ServerClient {\n  id;\n  annotations;\n  constructor(id) {\n    this.id = id;\n    this.annotations = Context.empty();\n  }\n  annotate(tag, value) {\n    this.annotations = Context.add(this.annotations, tag, value);\n    return this;\n  }\n}\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments);\n  },\n  setSuccess(successSchema) {\n    return makeProto({\n      _tag: this._tag,\n      payloadSchema: this.payloadSchema,\n      successSchema,\n      errorSchema: this.errorSchema,\n      defectSchema: this.defectSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    });\n  },\n  setError(errorSchema) {\n    return makeProto({\n      _tag: this._tag,\n      payloadSchema: this.payloadSchema,\n      successSchema: this.successSchema,\n      errorSchema,\n      defectSchema: this.defectSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    });\n  },\n  setPayload(payloadSchema) {\n    return makeProto({\n      _tag: this._tag,\n      payloadSchema: Schema.isSchema(payloadSchema) ? payloadSchema : Schema.Struct(payloadSchema),\n      successSchema: this.successSchema,\n      errorSchema: this.errorSchema,\n      defectSchema: this.defectSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    });\n  },\n  middleware(middleware) {\n    return makeProto({\n      _tag: this._tag,\n      payloadSchema: this.payloadSchema,\n      successSchema: this.successSchema,\n      errorSchema: this.errorSchema,\n      defectSchema: this.defectSchema,\n      annotations: this.annotations,\n      middlewares: new Set([...this.middlewares, middleware])\n    });\n  },\n  prefix(prefix) {\n    return makeProto({\n      _tag: `${prefix}${this._tag}`,\n      payloadSchema: this.payloadSchema,\n      successSchema: this.successSchema,\n      errorSchema: this.errorSchema,\n      defectSchema: this.defectSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    });\n  },\n  annotate(tag, value) {\n    return makeProto({\n      _tag: this._tag,\n      payloadSchema: this.payloadSchema,\n      successSchema: this.successSchema,\n      errorSchema: this.errorSchema,\n      defectSchema: this.defectSchema,\n      middlewares: this.middlewares,\n      annotations: Context.add(this.annotations, tag, value)\n    });\n  },\n  annotateMerge(context) {\n    return makeProto({\n      _tag: this._tag,\n      payloadSchema: this.payloadSchema,\n      successSchema: this.successSchema,\n      errorSchema: this.errorSchema,\n      defectSchema: this.defectSchema,\n      middlewares: this.middlewares,\n      annotations: Context.merge(this.annotations, context)\n    });\n  }\n};\nconst makeProto = options => {\n  function Rpc() {}\n  Object.setPrototypeOf(Rpc, Proto);\n  Object.assign(Rpc, options);\n  Rpc.key = `effect/rpc/Rpc/${options._tag}`;\n  return Rpc;\n};\n/**\n * Creates an RPC definition with the supplied tag and optional schemas.\n *\n * **Details**\n *\n * Payload options can be either a schema or struct fields. `stream: true` wraps\n * the success and error schemas in a stream schema and sets the normal error\n * schema to `Schema.Never`. `primaryKey` creates a payload class with a\n * primary key derived from the payload value.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (tag, options) => {\n  const successSchema = options?.success ?? Schema.Void;\n  const errorSchema = options?.error ?? Schema.Never;\n  const defectSchema = options?.defect ?? Schema.Defect();\n  let payloadSchema;\n  if (options?.primaryKey) {\n    payloadSchema = class Payload extends Schema.Class(`effect/rpc/Rpc/${tag}`)(options.payload) {\n      [PrimaryKey.symbol]() {\n        return options.primaryKey(this);\n      }\n    };\n  } else {\n    payloadSchema = Schema.isSchema(options?.payload) ? options?.payload : options?.payload ? Schema.Struct(options?.payload) : Schema.Void;\n  }\n  return makeProto({\n    _tag: tag,\n    payloadSchema,\n    successSchema: options?.stream ? RpcSchema.Stream(successSchema, errorSchema) : successSchema,\n    errorSchema: options?.stream ? Schema.Never : errorSchema,\n    defectSchema,\n    annotations: Context.empty(),\n    middlewares: new Set()\n  });\n};\n/**\n * Creates a custom `Rpc` constructor that can transform the output schemas.\n *\n * **Example** (Defining a paginated RPC constructor)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { Rpc } from \"effect/unstable/rpc\"\n *\n * // Create a custom Rpc wrapper definition by transforming the success and error\n * // schemas.\n * export interface RpcWithPagination extends Rpc.Custom {\n *   readonly out: Rpc.Custom.Out<\n *     Paginated<this[\"success\"]>,\n *     this[\"error\"]\n *   >\n * }\n *\n * // The type definition for the transformed success schema.\n * export interface Paginated<S extends Schema.Constraint> extends\n *   Schema.Struct<{\n *     readonly offset: Schema.Number\n *     readonly total: Schema.Number\n *     readonly results: Schema.$Array<S>\n *   }>\n * {}\n *\n * // You can then implement the schema transformation using `Rpc.custom`\n * export const makePaginated = Rpc.custom<RpcWithPagination>((schemas) => ({\n *   ...schemas,\n *   success: Schema.Struct({\n *     offset: Schema.Number,\n *     total: Schema.Number,\n *     results: Schema.Array(schemas.success)\n *   })\n * }))\n *\n * // You can then use the custom constructor in the same way `Rpc.make` is used.\n * export const listAllRpc = makePaginated(\"listAll\", {\n *   success: Schema.String\n * })\n *\n * const result = [listAllRpc._tag, Schema.isSchema(listAllRpc.successSchema)] // => [\"listAll\", true]\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const custom = f => (tag, options) => {\n  const success = options?.success ?? Schema.Void;\n  const error = options?.error ?? Schema.Never;\n  const defect = options?.defect ?? Schema.Defect();\n  const out = f({\n    success,\n    error,\n    defect\n  });\n  return make(tag, {\n    ...out,\n    primaryKey: options?.primaryKey,\n    payload: options?.payload,\n    stream: options?.stream\n  });\n};\nconst exitSchemaCache = /*#__PURE__*/new WeakMap();\n/**\n * Builds the `Schema.Exit` used to encode and decode RPC results.\n *\n * **Details**\n *\n * The failure side includes the RPC error schema, middleware error schemas, and\n * stream error schema for streaming RPCs. Streaming RPCs use `Schema.Void` for\n * the exit success value. The schema is cached per RPC definition.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const exitSchema = self => {\n  if (exitSchemaCache.has(self)) {\n    return exitSchemaCache.get(self);\n  }\n  const rpc = self;\n  const failures = new Set([rpc.errorSchema]);\n  const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n  if (Option.isSome(streamSchemas)) {\n    failures.add(streamSchemas.value.error);\n  }\n  for (const middleware of rpc.middlewares) {\n    failures.add(middleware.error);\n  }\n  const schema = Schema.Exit(Option.isSome(streamSchemas) ? Schema.Void : rpc.successSchema, Schema.Union([...failures]), rpc.defectSchema);\n  exitSchemaCache.set(self, schema);\n  return schema;\n};\nconst WrapperTypeId = \"~effect/rpc/Rpc/Wrapper\";\n/**\n * Returns `true` when the value is an RPC `Wrapper`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isWrapper = u => WrapperTypeId in u;\n/**\n * Wraps a handler result with RPC server execution options.\n *\n * **Details**\n *\n * When the value is already wrapped, unspecified options are inherited from the\n * existing wrapper.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const wrap = options => value => isWrapper(value) ? {\n  [WrapperTypeId]: WrapperTypeId,\n  value: value.value,\n  fork: options.fork ?? value.fork,\n  uninterruptible: options.uninterruptible ?? value.uninterruptible\n} : {\n  [WrapperTypeId]: WrapperTypeId,\n  value,\n  fork: options.fork ?? false,\n  uninterruptible: options.uninterruptible ?? false\n};\n/**\n * Returns the wrapped response value when the input is an RPC `Wrapper`, or the\n * input itself when it is already unwrapped.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const unwrap = value => isWrapper(value) ? value.value : value;\n/**\n * Maps the value inside an RPC wrapper, preserving wrapper options such as\n * `fork` and `uninterruptible`; unwrapped values are mapped directly.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const wrapMap = (self, f) => {\n  if (isWrapper(self)) {\n    return wrap(self)(f(self.value));\n  }\n  return f(self);\n};\n/**\n * Wraps a response Effect or Stream so the RPC server executes it concurrently\n * regardless of the server concurrency setting.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const fork = /*#__PURE__*/wrap({\n  fork: true\n});\n/**\n * Wraps a response Effect or Stream so the RPC server runs it in an uninterruptible region.\n *\n * @category wrapping\n * @since 4.0.0\n */\nexport const uninterruptible = /*#__PURE__*/wrap({\n  uninterruptible: true\n});\n//# sourceMappingURL=Rpc.js.map","import * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Rpc from \"./Rpc.js\";\nconst TypeId = \"~effect/rpc/RpcGroup\";\nconst RpcGroupProto = {\n  add(...rpcs) {\n    const requests = new Map(this.requests);\n    for (const rpc of rpcs) {\n      requests.set(rpc._tag, rpc);\n    }\n    return makeProto({\n      requests,\n      annotations: this.annotations\n    });\n  },\n  merge(...groups) {\n    const requests = new Map(this.requests);\n    const annotations = new Map(this.annotations.mapUnsafe);\n    for (const group of groups) {\n      for (const [tag, rpc] of group.requests) {\n        requests.set(tag, rpc);\n      }\n      for (const [key, value] of group.annotations.mapUnsafe) {\n        annotations.set(key, value);\n      }\n    }\n    return makeProto({\n      requests,\n      annotations: Context.makeUnsafe(annotations)\n    });\n  },\n  omit(...tags) {\n    const requests = new Map(this.requests);\n    for (const tag of tags) {\n      requests.delete(tag);\n    }\n    return makeProto({\n      requests,\n      annotations: this.annotations\n    });\n  },\n  middleware(middleware) {\n    const requests = new Map();\n    for (const [tag, rpc] of this.requests) {\n      requests.set(tag, rpc.middleware(middleware));\n    }\n    return makeProto({\n      requests,\n      annotations: this.annotations\n    });\n  },\n  toHandlers(build) {\n    // oxlint-disable-next-line no-this-alias\n    const self = this;\n    return Effect.gen(function* () {\n      const services = yield* Effect.context();\n      const handlers = Effect.isEffect(build) ? yield* build : build;\n      const contextMap = new Map();\n      self.requests.forEach((rpc, tag) => {\n        contextMap.set(rpc.key, {\n          tag: rpc._tag,\n          handler: handlers[tag],\n          context: services\n        });\n      });\n      return Context.makeUnsafe(contextMap);\n    });\n  },\n  prefix(prefix) {\n    const requests = new Map();\n    for (const rpc of this.requests.values()) {\n      const newRpc = rpc.prefix(prefix);\n      requests.set(newRpc._tag, newRpc);\n    }\n    return makeProto({\n      requests,\n      annotations: this.annotations\n    });\n  },\n  toLayer(build) {\n    return Layer.effectContext(this.toHandlers(build));\n  },\n  of: identity,\n  toLayerHandler(service, build) {\n    // oxlint-disable-next-line no-this-alias\n    const self = this;\n    return Layer.effectContext(Effect.gen(function* () {\n      const services = yield* Effect.context();\n      const handler = Effect.isEffect(build) ? yield* build : build;\n      const contextMap = new Map();\n      const rpc = self.requests.get(service);\n      contextMap.set(rpc.key, {\n        handler,\n        context: services\n      });\n      return Context.makeUnsafe(contextMap);\n    }));\n  },\n  accessHandler(service) {\n    return Effect.contextWith(parentContext => {\n      const rpc = this.requests.get(service);\n      const {\n        handler,\n        context\n      } = parentContext.mapUnsafe.get(rpc.key);\n      return Effect.succeed((payload, options) => {\n        options.rpc = rpc;\n        const result = handler(payload, options);\n        const effectOrStream = Rpc.isWrapper(result) ? result.value : result;\n        return Effect.isEffect(effectOrStream) ? Effect.provide(effectOrStream, context) : Stream.provideContext(effectOrStream, context);\n      });\n    });\n  },\n  annotate(service, value) {\n    return makeProto({\n      requests: this.requests,\n      annotations: Context.add(this.annotations, service, value)\n    });\n  },\n  annotateRpcs(service, value) {\n    return this.annotateRpcsMerge(Context.make(service, value));\n  },\n  annotateMerge(context) {\n    return makeProto({\n      requests: this.requests,\n      annotations: Context.merge(this.annotations, context)\n    });\n  },\n  annotateRpcsMerge(context) {\n    const requests = new Map();\n    for (const [tag, rpc] of this.requests) {\n      requests.set(tag, rpc.annotateMerge(Context.merge(context, rpc.annotations)));\n    }\n    return makeProto({\n      requests,\n      annotations: this.annotations\n    });\n  }\n};\nconst makeProto = options => Object.assign(function () {}, RpcGroupProto, {\n  requests: options.requests,\n  annotations: options.annotations\n});\n/**\n * Creates an `RpcGroup` from one or more RPC definitions.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (...rpcs) => makeProto({\n  requests: new Map(rpcs.map(rpc => [rpc._tag, rpc])),\n  annotations: Context.empty()\n});\n//# sourceMappingURL=RpcGroup.js.map","import * as Schema from \"effect/Schema\";\nimport * as Rpc from \"effect/unstable/rpc/Rpc\";\nimport * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\nimport { NonNegativeInt, ThreadId } from \"./baseSchemas.ts\";\n\nimport { ExternalLauncherError, LaunchEditorInput } from \"./editor.ts\";\nimport {\n  AuthAccessStreamError,\n  AuthAccessStreamEvent,\n  EnvironmentAuthorizationError,\n} from \"./auth.ts\";\nimport {\n  BackgroundPolicySnapshot,\n  ClientActivityReportInput,\n  HostPowerSnapshot,\n} from \"./background.ts\";\nimport {\n  FilesystemBrowseInput,\n  FilesystemBrowseResult,\n  FilesystemBrowseError,\n} from \"./filesystem.ts\";\nimport { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from \"./assets.ts\";\nimport {\n  GitActionProgressEvent,\n  VcsSwitchRefInput,\n  VcsSwitchRefResult,\n  GitCommandError,\n  VcsCreateRefInput,\n  VcsCreateRefResult,\n  VcsCreateWorktreeInput,\n  VcsCreateWorktreeResult,\n  VcsInitInput,\n  VcsListRefsInput,\n  VcsListRefsResult,\n  GitManagerServiceError,\n  GitPreparePullRequestThreadInput,\n  GitPreparePullRequestThreadResult,\n  VcsPullInput,\n  GitPullRequestRefInput,\n  VcsPullResult,\n  VcsRemoveWorktreeInput,\n  GitResolvePullRequestResult,\n  GitRunStackedActionInput,\n  VcsStatusInput,\n  VcsStatusResult,\n  VcsStatusStreamEvent,\n} from \"./git.ts\";\nimport {\n  ReviewDiffFileContentsInput,\n  ReviewDiffFileContentsResult,\n  ReviewDiffPreviewError,\n  ReviewDiffPreviewInput,\n  ReviewDiffPreviewResult,\n} from \"./review.ts\";\nimport { KeybindingsConfigError } from \"./keybindings.ts\";\nimport {\n  ClientOrchestrationCommand,\n  ORCHESTRATION_WS_METHODS,\n  OrchestrationDispatchCommandError,\n  OrchestrationGetFullThreadDiffError,\n  OrchestrationGetFullThreadDiffInput,\n  OrchestrationGetSnapshotError,\n  OrchestrationSearchThreadsError,\n  OrchestrationSearchThreadsInput,\n  OrchestrationGetTurnDiffError,\n  OrchestrationGetTurnDiffInput,\n  OrchestrationRpcSchemas,\n  OrchestrationGetWorkflowScriptError,\n} from \"./orchestration.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\nimport {\n  RelayClientInstallFailedError,\n  RelayClientInstallProgressEventSchema,\n  RelayClientStatusSchema,\n} from \"./relayClient.ts\";\nimport {\n  ProjectListEntriesError,\n  ProjectListEntriesInput,\n  ProjectListEntriesResult,\n  ProjectReadFileError,\n  ProjectReadFileInput,\n  ProjectReadFileResult,\n  ProjectSearchContentsError,\n  ProjectSearchContentsInput,\n  ProjectSearchContentsResult,\n  ProjectSearchEntriesError,\n  ProjectSearchEntriesInput,\n  ProjectSearchEntriesResult,\n  ProjectWriteFileError,\n  ProjectWriteFileInput,\n  ProjectWriteFileResult,\n} from \"./project.ts\";\nimport {\n  TerminalAttachInput,\n  TerminalAttachStreamEvent,\n  TerminalClearInput,\n  TerminalCloseInput,\n  TerminalError,\n  TerminalEvent,\n  TerminalMetadataStreamEvent,\n  TerminalOpenInput,\n  TerminalResizeInput,\n  TerminalRestartInput,\n  TerminalSessionSnapshot,\n  TerminalWriteInput,\n} from \"./terminal.ts\";\nimport {\n  DiscoveredLocalServerList,\n  PreviewCloseInput,\n  PreviewError,\n  PreviewEvent,\n  PreviewListInput,\n  PreviewListResult,\n  PreviewNavigateInput,\n  PreviewOpenInput,\n  PreviewRefreshInput,\n  PreviewReportStatusInput,\n  PreviewResizeInput,\n  PreviewSessionSnapshot,\n} from \"./preview.ts\";\nimport { PortProxyListResult, PortProxyPortInput } from \"./portProxy.ts\";\nimport {\n  PreviewAutomationError,\n  PreviewAutomationHost,\n  PreviewAutomationHostFocus,\n  PreviewAutomationResponse,\n  PreviewAutomationStreamEvent,\n} from \"./previewAutomation.ts\";\nimport {\n  ServerConfigStreamEvent,\n  ServerConfig,\n  ServerProviderUpdateError,\n  ServerProviderUpdateInput,\n  ServerLifecycleStreamEvent,\n  ServerRemoveKeybindingInput,\n  ServerRemoveKeybindingResult,\n  ServerProviderUpdatedPayload,\n  ServerSelfUpdateError,\n  ServerSelfUpdateInput,\n  ServerSelfUpdateProgressEvent,\n  ServerSelfUpdateResult,\n  ServerTraceDiagnosticsResult,\n  ServerProcessDiagnosticsResult,\n  ServerProcessResourceHistoryInput,\n  ServerProcessResourceHistoryResult,\n  ServerSignalProcessInput,\n  ServerSignalProcessResult,\n  ServerUpsertKeybindingInput,\n  ServerUpsertKeybindingResult,\n} from \"./server.ts\";\nimport {\n  ResourceTelemetryHistory,\n  ResourceTelemetryHistoryInput,\n  ResourceTelemetryRetryResult,\n  ResourceTelemetrySnapshot,\n} from \"./resourceTelemetry.ts\";\nimport { ServerSettings, ServerSettingsError, ServerSettingsPatch } from \"./settings.ts\";\nimport {\n  SourceControlCloneRepositoryInput,\n  SourceControlCloneRepositoryResult,\n  SourceControlDiscoveryResult,\n  SourceControlPublishRepositoryInput,\n  SourceControlPublishRepositoryResult,\n  SourceControlRepositoryError,\n  SourceControlRepositoryInfo,\n  SourceControlRepositoryLookupInput,\n} from \"./sourceControl.ts\";\nimport { VcsError } from \"./vcs.ts\";\n\nexport const WS_METHODS = {\n  // Project registry methods\n  projectsList: \"projects.list\",\n  projectsAdd: \"projects.add\",\n  projectsRemove: \"projects.remove\",\n  projectsListEntries: \"projects.listEntries\",\n  projectsReadFile: \"projects.readFile\",\n  projectsSearchContents: \"projects.searchContents\",\n  projectsSearchEntries: \"projects.searchEntries\",\n  projectsWriteFile: \"projects.writeFile\",\n\n  // Shell methods\n  shellOpenInEditor: \"shell.openInEditor\",\n\n  // Filesystem methods\n  filesystemBrowse: \"filesystem.browse\",\n  assetsCreateUrl: \"assets.createUrl\",\n\n  // VCS methods\n  vcsPull: \"vcs.pull\",\n  vcsRefreshStatus: \"vcs.refreshStatus\",\n  vcsListRefs: \"vcs.listRefs\",\n  vcsCreateWorktree: \"vcs.createWorktree\",\n  vcsRemoveWorktree: \"vcs.removeWorktree\",\n  vcsCreateRef: \"vcs.createRef\",\n  vcsSwitchRef: \"vcs.switchRef\",\n  vcsInit: \"vcs.init\",\n\n  // Git workflow methods\n  gitRunStackedAction: \"git.runStackedAction\",\n  gitResolvePullRequest: \"git.resolvePullRequest\",\n  gitPreparePullRequestThread: \"git.preparePullRequestThread\",\n\n  // Review methods\n  reviewGetDiffPreview: \"review.getDiffPreview\",\n  reviewGetDiffFileContents: \"review.getDiffFileContents\",\n\n  // Terminal methods\n  terminalOpen: \"terminal.open\",\n  terminalAttach: \"terminal.attach\",\n  terminalWrite: \"terminal.write\",\n  terminalResize: \"terminal.resize\",\n  terminalClear: \"terminal.clear\",\n  terminalRestart: \"terminal.restart\",\n  terminalClose: \"terminal.close\",\n\n  // Preview methods\n  previewOpen: \"preview.open\",\n  previewNavigate: \"preview.navigate\",\n  previewResize: \"preview.resize\",\n  previewRefresh: \"preview.refresh\",\n  previewClose: \"preview.close\",\n  previewList: \"preview.list\",\n  previewReportStatus: \"preview.reportStatus\",\n  previewAutomationConnect: \"previewAutomation.connect\",\n  previewAutomationRespond: \"previewAutomation.respond\",\n  previewAutomationFocusHost: \"previewAutomation.focusHost\",\n\n  // Server meta\n  serverProbe: \"server.probe\",\n  serverGetConfig: \"server.getConfig\",\n  serverRefreshProviders: \"server.refreshProviders\",\n  serverUpdateProvider: \"server.updateProvider\",\n  serverUpdateServer: \"server.updateServer\",\n  serverUpdateServerWithProgress: \"server.updateServerWithProgress\",\n  serverUpsertKeybinding: \"server.upsertKeybinding\",\n  serverRemoveKeybinding: \"server.removeKeybinding\",\n  serverGetSettings: \"server.getSettings\",\n  serverUpdateSettings: \"server.updateSettings\",\n  serverDiscoverSourceControl: \"server.discoverSourceControl\",\n  serverGetTraceDiagnostics: \"server.getTraceDiagnostics\",\n  serverGetProcessDiagnostics: \"server.getProcessDiagnostics\",\n  serverGetProcessResourceHistory: \"server.getProcessResourceHistory\",\n  serverGetResourceTelemetryHistory: \"server.getResourceTelemetryHistory\",\n  serverRetryResourceTelemetry: \"server.retryResourceTelemetry\",\n  serverSignalProcess: \"server.signalProcess\",\n  serverReportClientActivity: \"server.reportClientActivity\",\n  serverReportHostPowerState: \"server.reportHostPowerState\",\n  serverGetBackgroundPolicy: \"server.getBackgroundPolicy\",\n\n  // Temporary loopback HTTP port authorization\n  portProxyList: \"portProxy.list\",\n  portProxyAuthorize: \"portProxy.authorize\",\n  portProxyRevoke: \"portProxy.revoke\",\n\n  // Cloud environment methods\n  cloudGetRelayClientStatus: \"cloud.getRelayClientStatus\",\n  cloudInstallRelayClient: \"cloud.installRelayClient\",\n\n  // Experimental Codex realtime voice input. Audio stays on the authenticated daemon RPC.\n  voiceInputStart: \"voiceInput.start\",\n  voiceInputAppendAudio: \"voiceInput.appendAudio\",\n  voiceInputStop: \"voiceInput.stop\",\n  subscribeVoiceInputTranscript: \"subscribeVoiceInputTranscript\",\n\n  // Source control methods\n  sourceControlLookupRepository: \"sourceControl.lookupRepository\",\n  sourceControlCloneRepository: \"sourceControl.cloneRepository\",\n  sourceControlPublishRepository: \"sourceControl.publishRepository\",\n\n  // Streaming subscriptions\n  subscribeVcsStatus: \"subscribeVcsStatus\",\n  subscribeTerminalEvents: \"subscribeTerminalEvents\",\n  subscribeTerminalMetadata: \"subscribeTerminalMetadata\",\n  subscribePreviewEvents: \"subscribePreviewEvents\",\n  subscribeDiscoveredLocalServers: \"subscribeDiscoveredLocalServers\",\n  subscribeServerConfig: \"subscribeServerConfig\",\n  subscribeServerLifecycle: \"subscribeServerLifecycle\",\n  subscribeAuthAccess: \"subscribeAuthAccess\",\n  subscribeBackgroundPolicy: \"subscribeBackgroundPolicy\",\n  subscribeResourceTelemetry: \"subscribeResourceTelemetry\",\n} as const;\n\nexport const VoiceInputThread = Schema.Struct({ threadId: ThreadId });\nexport const VoiceInputAudio = Schema.Struct({\n  threadId: ThreadId,\n  data: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(32_000)),\n  sampleRate: Schema.Literal(24_000),\n  numChannels: Schema.Literal(1),\n  samplesPerChannel: Schema.optional(NonNegativeInt),\n});\nexport const VoiceInputTranscriptEvent = Schema.Struct({\n  eventId: Schema.String,\n  role: Schema.String,\n  text: Schema.String,\n  final: Schema.Boolean,\n});\n\nexport class VoiceInputUnavailableError extends Schema.TaggedErrorClass<VoiceInputUnavailableError>()(\n  \"VoiceInputUnavailableError\",\n  { message: Schema.String },\n) {}\n\nexport const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {\n  payload: ServerUpsertKeybindingInput,\n  success: ServerUpsertKeybindingResult,\n  error: Schema.Union([KeybindingsConfigError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerRemoveKeybindingRpc = Rpc.make(WS_METHODS.serverRemoveKeybinding, {\n  payload: ServerRemoveKeybindingInput,\n  success: ServerRemoveKeybindingResult,\n  error: Schema.Union([KeybindingsConfigError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerProbeRpc = Rpc.make(WS_METHODS.serverProbe, {\n  payload: Schema.Struct({}),\n  success: Schema.Struct({}),\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {\n  payload: Schema.Struct({}),\n  success: ServerConfig,\n  error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, {\n  payload: Schema.Struct({\n    /**\n     * When supplied, only refresh this specific provider instance. When\n     * omitted, refresh all configured instances — the legacy `refresh()`\n     * behaviour retained for transports that still dispatch untargeted\n     * refreshes.\n     */\n    instanceId: Schema.optional(ProviderInstanceId),\n  }),\n  success: ServerProviderUpdatedPayload,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerUpdateProviderRpc = Rpc.make(WS_METHODS.serverUpdateProvider, {\n  payload: ServerProviderUpdateInput,\n  success: ServerProviderUpdatedPayload,\n  error: Schema.Union([ServerProviderUpdateError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerUpdateServerRpc = Rpc.make(WS_METHODS.serverUpdateServer, {\n  payload: ServerSelfUpdateInput,\n  success: ServerSelfUpdateResult,\n  error: Schema.Union([ServerSelfUpdateError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerUpdateServerWithProgressRpc = Rpc.make(\n  WS_METHODS.serverUpdateServerWithProgress,\n  {\n    payload: ServerSelfUpdateInput,\n    success: ServerSelfUpdateProgressEvent,\n    error: Schema.Union([ServerSelfUpdateError, EnvironmentAuthorizationError]),\n    stream: true,\n  },\n);\n\nexport const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {\n  payload: Schema.Struct({}),\n  success: ServerSettings,\n  error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPortProxyListRpc = Rpc.make(WS_METHODS.portProxyList, {\n  payload: Schema.Struct({}),\n  success: PortProxyListResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsPortProxyAuthorizeRpc = Rpc.make(WS_METHODS.portProxyAuthorize, {\n  payload: PortProxyPortInput,\n  success: PortProxyListResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsPortProxyRevokeRpc = Rpc.make(WS_METHODS.portProxyRevoke, {\n  payload: PortProxyPortInput,\n  success: PortProxyListResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, {\n  payload: Schema.Struct({ patch: ServerSettingsPatch }),\n  success: ServerSettings,\n  error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerDiscoverSourceControlRpc = Rpc.make(WS_METHODS.serverDiscoverSourceControl, {\n  payload: Schema.Struct({}),\n  success: SourceControlDiscoveryResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetTraceDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetTraceDiagnostics, {\n  payload: Schema.Struct({}),\n  success: ServerTraceDiagnosticsResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetProcessDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetProcessDiagnostics, {\n  payload: Schema.Struct({}),\n  success: ServerProcessDiagnosticsResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetProcessResourceHistoryRpc = Rpc.make(\n  WS_METHODS.serverGetProcessResourceHistory,\n  {\n    payload: ServerProcessResourceHistoryInput,\n    success: ServerProcessResourceHistoryResult,\n    error: EnvironmentAuthorizationError,\n  },\n);\n\nexport const WsServerGetResourceTelemetryHistoryRpc = Rpc.make(\n  WS_METHODS.serverGetResourceTelemetryHistory,\n  {\n    payload: ResourceTelemetryHistoryInput,\n    success: ResourceTelemetryHistory,\n    error: EnvironmentAuthorizationError,\n  },\n);\n\nexport const WsServerRetryResourceTelemetryRpc = Rpc.make(WS_METHODS.serverRetryResourceTelemetry, {\n  payload: Schema.Struct({}),\n  success: ResourceTelemetryRetryResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, {\n  payload: ServerSignalProcessInput,\n  success: ServerSignalProcessResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsCloudGetRelayClientStatusRpc = Rpc.make(WS_METHODS.cloudGetRelayClientStatus, {\n  payload: Schema.Struct({}),\n  success: RelayClientStatusSchema,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsCloudInstallRelayClientRpc = Rpc.make(WS_METHODS.cloudInstallRelayClient, {\n  payload: Schema.Struct({}),\n  success: RelayClientInstallProgressEventSchema,\n  error: Schema.Union([RelayClientInstallFailedError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsServerReportClientActivityRpc = Rpc.make(WS_METHODS.serverReportClientActivity, {\n  payload: ClientActivityReportInput,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerReportHostPowerStateRpc = Rpc.make(WS_METHODS.serverReportHostPowerState, {\n  payload: HostPowerSnapshot,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetBackgroundPolicyRpc = Rpc.make(WS_METHODS.serverGetBackgroundPolicy, {\n  payload: Schema.Struct({}),\n  success: BackgroundPolicySnapshot,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsSourceControlLookupRepositoryRpc = Rpc.make(\n  WS_METHODS.sourceControlLookupRepository,\n  {\n    payload: SourceControlRepositoryLookupInput,\n    success: SourceControlRepositoryInfo,\n    error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlCloneRepository, {\n  payload: SourceControlCloneRepositoryInput,\n  success: SourceControlCloneRepositoryResult,\n  error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),\n});\n\nexport const WsSourceControlPublishRepositoryRpc = Rpc.make(\n  WS_METHODS.sourceControlPublishRepository,\n  {\n    payload: SourceControlPublishRepositoryInput,\n    success: SourceControlPublishRepositoryResult,\n    error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, {\n  payload: ProjectSearchEntriesInput,\n  success: ProjectSearchEntriesResult,\n  error: Schema.Union([ProjectSearchEntriesError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsSearchContentsRpc = Rpc.make(WS_METHODS.projectsSearchContents, {\n  payload: ProjectSearchContentsInput,\n  success: ProjectSearchContentsResult,\n  error: Schema.Union([ProjectSearchContentsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsListEntriesRpc = Rpc.make(WS_METHODS.projectsListEntries, {\n  payload: ProjectListEntriesInput,\n  success: ProjectListEntriesResult,\n  error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsReadFileRpc = Rpc.make(WS_METHODS.projectsReadFile, {\n  payload: ProjectReadFileInput,\n  success: ProjectReadFileResult,\n  error: Schema.Union([ProjectReadFileError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {\n  payload: ProjectWriteFileInput,\n  success: ProjectWriteFileResult,\n  error: Schema.Union([ProjectWriteFileError, EnvironmentAuthorizationError]),\n});\n\nexport const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {\n  payload: LaunchEditorInput,\n  error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),\n});\n\nexport const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {\n  payload: FilesystemBrowseInput,\n  success: FilesystemBrowseResult,\n  error: Schema.Union([FilesystemBrowseError, EnvironmentAuthorizationError]),\n});\n\nexport const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, {\n  payload: AssetCreateUrlInput,\n  success: AssetCreateUrlResult,\n  error: Schema.Union([AssetAccessError, EnvironmentAuthorizationError]),\n});\n\nexport const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {\n  payload: VcsStatusInput,\n  success: VcsStatusStreamEvent,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsVcsPullRpc = Rpc.make(WS_METHODS.vcsPull, {\n  payload: VcsPullInput,\n  success: VcsPullResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, {\n  payload: VcsStatusInput,\n  success: VcsStatusResult,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n});\n\nexport const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, {\n  payload: GitRunStackedActionInput,\n  success: GitActionProgressEvent,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsGitResolvePullRequestRpc = Rpc.make(WS_METHODS.gitResolvePullRequest, {\n  payload: GitPullRequestRefInput,\n  success: GitResolvePullRequestResult,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n});\n\nexport const WsGitPreparePullRequestThreadRpc = Rpc.make(WS_METHODS.gitPreparePullRequestThread, {\n  payload: GitPreparePullRequestThreadInput,\n  success: GitPreparePullRequestThreadResult,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsListRefsRpc = Rpc.make(WS_METHODS.vcsListRefs, {\n  payload: VcsListRefsInput,\n  success: VcsListRefsResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsCreateWorktreeRpc = Rpc.make(WS_METHODS.vcsCreateWorktree, {\n  payload: VcsCreateWorktreeInput,\n  success: VcsCreateWorktreeResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsRemoveWorktreeRpc = Rpc.make(WS_METHODS.vcsRemoveWorktree, {\n  payload: VcsRemoveWorktreeInput,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsCreateRefRpc = Rpc.make(WS_METHODS.vcsCreateRef, {\n  payload: VcsCreateRefInput,\n  success: VcsCreateRefResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, {\n  payload: VcsSwitchRefInput,\n  success: VcsSwitchRefResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {\n  payload: VcsInitInput,\n  error: Schema.Union([VcsError, EnvironmentAuthorizationError]),\n});\n\n/**\n * Ephemeral live diff preview for compact/mobile surfaces.\n * Not the persisted T3 Review model. Future review sessions should use\n * review.open* + review.getSnapshot.\n */\nexport const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, {\n  payload: ReviewDiffPreviewInput,\n  success: ReviewDiffPreviewResult,\n  error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsReviewGetDiffFileContentsRpc = Rpc.make(WS_METHODS.reviewGetDiffFileContents, {\n  payload: ReviewDiffFileContentsInput,\n  success: ReviewDiffFileContentsResult,\n  error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {\n  payload: TerminalOpenInput,\n  success: TerminalSessionSnapshot,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalAttachRpc = Rpc.make(WS_METHODS.terminalAttach, {\n  payload: TerminalAttachInput,\n  success: TerminalAttachStreamEvent,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, {\n  payload: TerminalWriteInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalResizeRpc = Rpc.make(WS_METHODS.terminalResize, {\n  payload: TerminalResizeInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalClearRpc = Rpc.make(WS_METHODS.terminalClear, {\n  payload: TerminalClearInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalRestartRpc = Rpc.make(WS_METHODS.terminalRestart, {\n  payload: TerminalRestartInput,\n  success: TerminalSessionSnapshot,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalCloseRpc = Rpc.make(WS_METHODS.terminalClose, {\n  payload: TerminalCloseInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewOpenRpc = Rpc.make(WS_METHODS.previewOpen, {\n  payload: PreviewOpenInput,\n  success: PreviewSessionSnapshot,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewNavigateRpc = Rpc.make(WS_METHODS.previewNavigate, {\n  payload: PreviewNavigateInput,\n  success: PreviewSessionSnapshot,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewResizeRpc = Rpc.make(WS_METHODS.previewResize, {\n  payload: PreviewResizeInput,\n  success: PreviewSessionSnapshot,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewRefreshRpc = Rpc.make(WS_METHODS.previewRefresh, {\n  payload: PreviewRefreshInput,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewCloseRpc = Rpc.make(WS_METHODS.previewClose, {\n  payload: PreviewCloseInput,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewListRpc = Rpc.make(WS_METHODS.previewList, {\n  payload: PreviewListInput,\n  success: PreviewListResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsPreviewReportStatusRpc = Rpc.make(WS_METHODS.previewReportStatus, {\n  payload: PreviewReportStatusInput,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewAutomationConnectRpc = Rpc.make(WS_METHODS.previewAutomationConnect, {\n  payload: PreviewAutomationHost,\n  success: PreviewAutomationStreamEvent,\n  error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsPreviewAutomationRespondRpc = Rpc.make(WS_METHODS.previewAutomationRespond, {\n  payload: PreviewAutomationResponse,\n  error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewAutomationFocusHostRpc = Rpc.make(WS_METHODS.previewAutomationFocusHost, {\n  payload: PreviewAutomationHostFocus,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, {\n  payload: Schema.Struct({}),\n  success: PreviewEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeDiscoveredLocalServersRpc = Rpc.make(\n  WS_METHODS.subscribeDiscoveredLocalServers,\n  {\n    payload: Schema.Struct({}),\n    success: DiscoveredLocalServerList,\n    error: EnvironmentAuthorizationError,\n    stream: true,\n  },\n);\n\nexport const WsOrchestrationDispatchCommandRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.dispatchCommand,\n  {\n    payload: ClientOrchestrationCommand,\n    success: OrchestrationRpcSchemas.dispatchCommand.output,\n    error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationGetWorkflowScriptRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.getWorkflowScript,\n  {\n    payload: OrchestrationRpcSchemas.getWorkflowScript.input,\n    success: OrchestrationRpcSchemas.getWorkflowScript.output,\n    error: Schema.Union([OrchestrationGetWorkflowScriptError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, {\n  payload: OrchestrationGetTurnDiffInput,\n  success: OrchestrationRpcSchemas.getTurnDiff.output,\n  error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),\n});\n\nexport const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.getFullThreadDiff,\n  {\n    payload: OrchestrationGetFullThreadDiffInput,\n    success: OrchestrationRpcSchemas.getFullThreadDiff.output,\n    error: Schema.Union([OrchestrationGetFullThreadDiffError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationSearchThreadsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.searchThreads, {\n  payload: OrchestrationSearchThreadsInput,\n  success: OrchestrationRpcSchemas.searchThreads.output,\n  error: Schema.Union([OrchestrationSearchThreadsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,\n  {\n    payload: OrchestrationRpcSchemas.getArchivedShellSnapshot.input,\n    success: OrchestrationRpcSchemas.getArchivedShellSnapshot.output,\n    error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {\n  payload: OrchestrationRpcSchemas.subscribeShell.input,\n  success: OrchestrationRpcSchemas.subscribeShell.output,\n  error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsOrchestrationSubscribeThreadRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.subscribeThread,\n  {\n    payload: OrchestrationRpcSchemas.subscribeThread.input,\n    success: OrchestrationRpcSchemas.subscribeThread.output,\n    error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n    stream: true,\n  },\n);\n\nexport const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTerminalEvents, {\n  payload: Schema.Struct({}),\n  success: TerminalEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTerminalMetadata, {\n  payload: Schema.Struct({}),\n  success: TerminalMetadataStreamEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConfig, {\n  payload: Schema.Struct({}),\n  success: ServerConfigStreamEvent,\n  error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecycle, {\n  payload: Schema.Struct({}),\n  success: ServerLifecycleStreamEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess, {\n  payload: Schema.Struct({}),\n  success: AuthAccessStreamEvent,\n  error: Schema.Union([AuthAccessStreamError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsSubscribeBackgroundPolicyRpc = Rpc.make(WS_METHODS.subscribeBackgroundPolicy, {\n  payload: Schema.Struct({}),\n  success: BackgroundPolicySnapshot,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeResourceTelemetryRpc = Rpc.make(WS_METHODS.subscribeResourceTelemetry, {\n  payload: Schema.Struct({}),\n  success: ResourceTelemetrySnapshot,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsVoiceInputStartRpc = Rpc.make(WS_METHODS.voiceInputStart, {\n  payload: VoiceInputThread,\n  success: Schema.Struct({}),\n  error: Schema.Union([VoiceInputUnavailableError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVoiceInputAppendAudioRpc = Rpc.make(WS_METHODS.voiceInputAppendAudio, {\n  payload: VoiceInputAudio,\n  success: Schema.Struct({}),\n  error: Schema.Union([VoiceInputUnavailableError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVoiceInputStopRpc = Rpc.make(WS_METHODS.voiceInputStop, {\n  payload: VoiceInputThread,\n  success: Schema.Struct({}),\n  error: Schema.Union([VoiceInputUnavailableError, EnvironmentAuthorizationError]),\n});\n\nexport const WsSubscribeVoiceInputTranscriptRpc = Rpc.make(\n  WS_METHODS.subscribeVoiceInputTranscript,\n  {\n    payload: VoiceInputThread,\n    success: VoiceInputTranscriptEvent,\n    error: Schema.Union([VoiceInputUnavailableError, EnvironmentAuthorizationError]),\n    stream: true,\n  },\n);\n\nexport const WsRpcGroup = RpcGroup.make(\n  WsServerProbeRpc,\n  WsServerGetConfigRpc,\n  WsServerRefreshProvidersRpc,\n  WsServerUpdateProviderRpc,\n  WsServerUpdateServerRpc,\n  WsServerUpdateServerWithProgressRpc,\n  WsServerUpsertKeybindingRpc,\n  WsServerRemoveKeybindingRpc,\n  WsServerGetSettingsRpc,\n  WsServerUpdateSettingsRpc,\n  WsServerDiscoverSourceControlRpc,\n  WsServerGetTraceDiagnosticsRpc,\n  WsServerGetProcessDiagnosticsRpc,\n  WsServerGetProcessResourceHistoryRpc,\n  WsServerGetResourceTelemetryHistoryRpc,\n  WsServerRetryResourceTelemetryRpc,\n  WsServerSignalProcessRpc,\n  WsServerReportClientActivityRpc,\n  WsServerReportHostPowerStateRpc,\n  WsServerGetBackgroundPolicyRpc,\n  WsPortProxyListRpc,\n  WsPortProxyAuthorizeRpc,\n  WsPortProxyRevokeRpc,\n  WsCloudGetRelayClientStatusRpc,\n  WsCloudInstallRelayClientRpc,\n  WsSourceControlLookupRepositoryRpc,\n  WsSourceControlCloneRepositoryRpc,\n  WsSourceControlPublishRepositoryRpc,\n  WsProjectsListEntriesRpc,\n  WsProjectsReadFileRpc,\n  WsProjectsSearchContentsRpc,\n  WsProjectsSearchEntriesRpc,\n  WsProjectsWriteFileRpc,\n  WsShellOpenInEditorRpc,\n  WsFilesystemBrowseRpc,\n  WsAssetsCreateUrlRpc,\n  WsSubscribeVcsStatusRpc,\n  WsVcsPullRpc,\n  WsVcsRefreshStatusRpc,\n  WsGitRunStackedActionRpc,\n  WsGitResolvePullRequestRpc,\n  WsGitPreparePullRequestThreadRpc,\n  WsVcsListRefsRpc,\n  WsVcsCreateWorktreeRpc,\n  WsVcsRemoveWorktreeRpc,\n  WsVcsCreateRefRpc,\n  WsVcsSwitchRefRpc,\n  WsVcsInitRpc,\n  WsReviewGetDiffPreviewRpc,\n  WsReviewGetDiffFileContentsRpc,\n  WsTerminalOpenRpc,\n  WsTerminalAttachRpc,\n  WsTerminalWriteRpc,\n  WsTerminalResizeRpc,\n  WsTerminalClearRpc,\n  WsTerminalRestartRpc,\n  WsTerminalCloseRpc,\n  WsSubscribeTerminalEventsRpc,\n  WsSubscribeTerminalMetadataRpc,\n  WsPreviewOpenRpc,\n  WsPreviewNavigateRpc,\n  WsPreviewResizeRpc,\n  WsPreviewRefreshRpc,\n  WsPreviewCloseRpc,\n  WsPreviewListRpc,\n  WsPreviewReportStatusRpc,\n  WsPreviewAutomationConnectRpc,\n  WsPreviewAutomationRespondRpc,\n  WsPreviewAutomationFocusHostRpc,\n  WsSubscribePreviewEventsRpc,\n  WsSubscribeDiscoveredLocalServersRpc,\n  WsSubscribeServerConfigRpc,\n  WsSubscribeServerLifecycleRpc,\n  WsSubscribeAuthAccessRpc,\n  WsSubscribeBackgroundPolicyRpc,\n  WsSubscribeResourceTelemetryRpc,\n  WsVoiceInputStartRpc,\n  WsVoiceInputAppendAudioRpc,\n  WsVoiceInputStopRpc,\n  WsSubscribeVoiceInputTranscriptRpc,\n  WsOrchestrationDispatchCommandRpc,\n  WsOrchestrationGetWorkflowScriptRpc,\n  WsOrchestrationGetTurnDiffRpc,\n  WsOrchestrationGetFullThreadDiffRpc,\n  WsOrchestrationSearchThreadsRpc,\n  WsOrchestrationGetArchivedShellSnapshotRpc,\n  WsOrchestrationSubscribeShellRpc,\n  WsOrchestrationSubscribeThreadRpc,\n);\n","import * as Schema from \"effect/Schema\";\n\nconst OAUTH_SCOPE_TOKEN = /^[\\u0021\\u0023-\\u005b\\u005d-\\u007e]+$/u;\n\nexport class OAuthScopeEncodingError extends Schema.TaggedErrorClass<OAuthScopeEncodingError>()(\n  \"OAuthScopeEncodingError\",\n  {\n    scopes: Schema.Array(Schema.String),\n    invalidScopes: Schema.Array(Schema.String),\n    duplicateScopes: Schema.Array(Schema.String),\n  },\n) {\n  override get message(): string {\n    return \"OAuth scopes must be non-empty, syntactically valid, and unique.\";\n  }\n}\n\n/**\n * Decodes an RFC 6749 `scope` value as a set while preserving its first-seen\n * order for canonical responses and logs.\n */\nexport function parseOAuthScope(value: string): ReadonlyArray<string> | null {\n  if (value.length === 0) {\n    return null;\n  }\n\n  const scopes = value.split(\" \");\n  if (scopes.some((scope) => !OAUTH_SCOPE_TOKEN.test(scope))) {\n    return null;\n  }\n\n  return [...new Set(scopes)];\n}\n\nexport function encodeOAuthScope(scopes: ReadonlyArray<string>): string {\n  const invalidScopes = scopes.filter((scope) => !OAUTH_SCOPE_TOKEN.test(scope));\n  const seen = new Set<string>();\n  const duplicateScopes = new Set<string>();\n  for (const scope of scopes) {\n    if (seen.has(scope)) duplicateScopes.add(scope);\n    seen.add(scope);\n  }\n\n  if (scopes.length === 0 || invalidScopes.length > 0 || duplicateScopes.size > 0) {\n    throw new OAuthScopeEncodingError({\n      scopes,\n      invalidScopes,\n      duplicateScopes: [...duplicateScopes],\n    });\n  }\n  return scopes.join(\" \");\n}\n\nexport function oauthScopeSetEquals(value: string, expectedScopes: ReadonlyArray<string>): boolean {\n  const scopes = parseOAuthScope(value);\n  return (\n    scopes !== null &&\n    scopes.length === new Set(expectedScopes).size &&\n    scopes.every((scope) => expectedScopes.includes(scope))\n  );\n}\n\nexport function parseAllowedOAuthScope<Scope extends string>(input: {\n  readonly value: string;\n  readonly allowedScopes: ReadonlySet<Scope>;\n}): ReadonlyArray<Scope> | null {\n  const scopes = parseOAuthScope(input.value);\n  if (\n    scopes === null ||\n    !scopes.every((scope): scope is Scope => input.allowedScopes.has(scope as Scope))\n  ) {\n    return null;\n  }\n  return scopes;\n}\n","/**\n * ServerConfig - Runtime configuration services.\n *\n * Defines process-level server configuration and networking helpers used by\n * startup and runtime layers.\n *\n * @module ServerConfig\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as LogLevel from \"effect/LogLevel\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nexport const DEFAULT_PORT = 3773;\n\nexport const RuntimeMode = Schema.Literals([\"web\", \"desktop\"]);\nexport type RuntimeMode = typeof RuntimeMode.Type;\n\nexport const StartupPresentation = Schema.Literals([\"browser\", \"headless\"]);\nexport type StartupPresentation = typeof StartupPresentation.Type;\n\n/**\n * ServerDerivedPaths - Derived paths from the base directory.\n */\nexport interface ServerDerivedPaths {\n  readonly stateDir: string;\n  readonly dbPath: string;\n  readonly keybindingsConfigPath: string;\n  readonly settingsPath: string;\n  readonly providerStatusCacheDir: string;\n  readonly worktreesDir: string;\n  readonly attachmentsDir: string;\n  readonly logsDir: string;\n  readonly serverLogPath: string;\n  readonly serverTracePath: string;\n  readonly providerLogsDir: string;\n  readonly providerEventLogPath: string;\n  readonly terminalLogsDir: string;\n  readonly anonymousIdPath: string;\n  readonly environmentIdPath: string;\n  readonly serverRuntimeStatePath: string;\n  readonly secretsDir: string;\n}\n\nexport interface DeriveServerPathsOptions {\n  readonly baseDirIsExplicit?: boolean;\n}\n\n/**\n * ServerConfig - Service tag for server runtime configuration.\n */\nexport class ServerConfig extends Context.Service<\n  ServerConfig,\n  ServerDerivedPaths & {\n    readonly logLevel: LogLevel.LogLevel;\n    readonly traceMinLevel: LogLevel.LogLevel;\n    readonly traceTimingEnabled: boolean;\n    readonly traceBatchWindowMs: number;\n    readonly traceMaxBytes: number;\n    readonly traceMaxFiles: number;\n    readonly otlpTracesUrl: string | undefined;\n    readonly otlpMetricsUrl: string | undefined;\n    readonly otlpExportIntervalMs: number;\n    readonly otlpServiceName: string;\n    readonly mode: RuntimeMode;\n    readonly port: number;\n    readonly host: string | undefined;\n    readonly cwd: string;\n    readonly baseDir: string;\n    readonly staticDir: string | undefined;\n    readonly devUrl: URL | undefined;\n    readonly devAllowedOrigins: ReadonlyArray<string>;\n    readonly noBrowser: boolean;\n    readonly startupPresentation: StartupPresentation;\n    readonly desktopBootstrapToken: string | undefined;\n    readonly desktopTelemetryFd?: number | undefined;\n    readonly desktopTelemetryControlFd?: number | undefined;\n    readonly resourceMonitorPath?: string | undefined;\n    readonly autoBootstrapProjectFromCwd: boolean;\n    readonly logWebSocketEvents: boolean;\n    readonly tailscaleServeEnabled: boolean;\n    readonly tailscaleServePort: number;\n    // agentlink fork (步骤 6): hub tunnel egress. All three set = the daemon\n    // dials out to <hubUrl>/daemon-tunnel and bridges E2EE RPC tunnels\n    // (tunnel/bridge.ts); unset = local-only, exactly as before.\n    readonly hubTunnel?: HubTunnelConfig | undefined;\n  }\n>()(\"t3/config/ServerConfig\") {\n  /** @deprecated Import and use `layerTest` from this module. */\n  static readonly layerTest = (\n    cwd: string,\n    baseDirOrPrefix: string | { readonly prefix: string },\n  ) => layerTest(cwd, baseDirOrPrefix);\n}\n\nexport interface HubTunnelConfig {\n  readonly hubUrl: string; // ws(s)://host[:port]\n  readonly machineToken: string; // al1 auth half, or the single-mode token\n  readonly enckey: string; // base64url 32-byte E2EE master key\n}\n\nexport const make = (config: ServerConfig[\"Service\"]) => ServerConfig.of(config);\n\nexport const layer = (config: ServerConfig[\"Service\"]) => Layer.succeed(ServerConfig, make(config));\n\nexport const deriveServerPaths = Effect.fn(function* (\n  baseDir: ServerConfig[\"Service\"][\"baseDir\"],\n  devUrl: ServerConfig[\"Service\"][\"devUrl\"],\n  options: DeriveServerPathsOptions = {},\n): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {\n  const { join } = yield* Path.Path;\n  const stateDir = join(\n    baseDir,\n    devUrl !== undefined && !options.baseDirIsExplicit ? \"dev\" : \"userdata\",\n  );\n  const dbPath = join(stateDir, \"state.sqlite\");\n  const attachmentsDir = join(stateDir, \"attachments\");\n  const logsDir = join(stateDir, \"logs\");\n  const providerLogsDir = join(logsDir, \"provider\");\n  const providerStatusCacheDir = join(baseDir, \"caches\");\n  return {\n    stateDir,\n    dbPath,\n    keybindingsConfigPath: join(stateDir, \"keybindings.json\"),\n    settingsPath: join(stateDir, \"settings.json\"),\n    providerStatusCacheDir,\n    worktreesDir: join(baseDir, \"worktrees\"),\n    attachmentsDir,\n    logsDir,\n    serverLogPath: join(logsDir, \"server.log\"),\n    serverTracePath: join(logsDir, \"server.trace.ndjson\"),\n    providerLogsDir,\n    providerEventLogPath: join(providerLogsDir, \"events.log\"),\n    terminalLogsDir: join(logsDir, \"terminals\"),\n    anonymousIdPath: join(stateDir, \"anonymous-id\"),\n    environmentIdPath: join(stateDir, \"environment-id\"),\n    serverRuntimeStatePath: join(stateDir, \"server-runtime.json\"),\n    secretsDir: join(stateDir, \"secrets\"),\n  };\n});\n\nexport const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  yield* Effect.all(\n    [\n      fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),\n      fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n});\n\nconst makeTest = Effect.fn(\"ServerConfig.makeTest\")(function* (\n  cwd: string,\n  baseDirOrPrefix: string | { readonly prefix: string },\n) {\n  const devUrl = undefined;\n  const fs = yield* FileSystem.FileSystem;\n  const baseDir =\n    typeof baseDirOrPrefix === \"string\"\n      ? baseDirOrPrefix\n      : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });\n  const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);\n  yield* ensureServerDirectories(derivedPaths);\n\n  return ServerConfig.of({\n    logLevel: \"Error\",\n    traceMinLevel: \"Info\",\n    traceTimingEnabled: true,\n    traceBatchWindowMs: 200,\n    traceMaxBytes: 10 * 1024 * 1024,\n    traceMaxFiles: 10,\n    otlpTracesUrl: undefined,\n    otlpMetricsUrl: undefined,\n    otlpExportIntervalMs: 10_000,\n    otlpServiceName: \"t3-server\",\n    cwd,\n    baseDir,\n    ...derivedPaths,\n    mode: \"web\",\n    autoBootstrapProjectFromCwd: false,\n    logWebSocketEvents: false,\n    tailscaleServeEnabled: false,\n    tailscaleServePort: 443,\n    port: 0,\n    host: undefined,\n    desktopBootstrapToken: undefined,\n    desktopTelemetryFd: undefined,\n    desktopTelemetryControlFd: undefined,\n    resourceMonitorPath: undefined,\n    staticDir: undefined,\n    devUrl,\n    devAllowedOrigins: [],\n    noBrowser: false,\n    startupPresentation: \"browser\",\n  });\n});\n\nexport const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>\n  Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));\n\nexport const resolveStaticDir = Effect.fn(function* () {\n  const { join, resolve } = yield* Path.Path;\n  const { exists } = yield* FileSystem.FileSystem;\n  const bundledClient = resolve(join(import.meta.dirname, \"client\"));\n  const bundledStat = yield* exists(join(bundledClient, \"index.html\")).pipe(\n    Effect.orElseSucceed(() => false),\n  );\n  if (bundledStat) {\n    return bundledClient;\n  }\n\n  const monorepoClient = resolve(join(import.meta.dirname, \"../../web/dist\"));\n  const monorepoStat = yield* exists(join(monorepoClient, \"index.html\")).pipe(\n    Effect.orElseSucceed(() => false),\n  );\n  if (monorepoStat) {\n    return monorepoClient;\n  }\n  return undefined;\n});\n","import type {\n  AuthClientMetadata,\n  AuthClientMetadataDeviceType,\n  AuthClientPresentationMetadata,\n} from \"@t3tools/contracts\";\nimport type * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\nimport * as NodeCrypto from \"node:crypto\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Result from \"effect/Result\";\n\nconst SESSION_COOKIE_NAME = \"t3_session\";\n\n/**\n * Cookies are scoped by host but *not* by port, so any two servers that can be\n * live on one hostname at once need separate names — otherwise the second\n * clobbers the first's session and both sides see \"Invalid session token\n * signature\" until someone clears cookies by hand.\n *\n * Two populations qualify, for the same reason but from different causes:\n *\n * - **Dev servers** (`devUrl` set), which run several at a time across worktrees.\n * - **Desktop**, which scans upward from 3773 for a free port and binds\n *   127.0.0.1, so a second instance lands on a different port and the same host.\n *\n * Hosted deployments keep the stable production name: their public port can\n * change between releases, and scoping it would log every user out.\n */\nexport function resolveSessionCookieName(input: {\n  readonly mode: \"web\" | \"desktop\";\n  readonly port: number;\n  readonly host: string | undefined;\n  readonly instanceKey: string;\n  readonly development: boolean;\n}): string {\n  if (input.mode === \"desktop\") {\n    return `${SESSION_COOKIE_NAME}_${input.port}`;\n  }\n\n  if (!input.development && isRemoteReachableHost(input.host)) {\n    return SESSION_COOKIE_NAME;\n  }\n\n  // Cookies are scoped by host, not port. Loopback development servers need an\n  // instance-specific name or parallel agents overwrite each other's session,\n  // and a server that later reuses the port receives a token signed elsewhere.\n  const instanceHash = NodeCrypto.createHash(\"sha256\")\n    .update(input.instanceKey)\n    .digest(\"hex\")\n    .slice(0, 12);\n  return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;\n}\n\nexport function isRemoteReachableHost(host: string | undefined): boolean {\n  if (host === \"0.0.0.0\" || host === \"::\" || host === \"[::]\") {\n    return true;\n  }\n  if (!host || host.length === 0) {\n    return false;\n  }\n  return !(\n    host === \"localhost\" ||\n    host === \"127.0.0.1\" ||\n    host === \"::1\" ||\n    host === \"[::1]\" ||\n    host.startsWith(\"127.\")\n  );\n}\n\nexport function base64UrlEncode(input: string | Uint8Array): string {\n  return typeof input === \"string\"\n    ? Encoding.encodeBase64Url(new TextEncoder().encode(input))\n    : Encoding.encodeBase64Url(input);\n}\n\nexport function base64UrlDecodeUtf8(input: string): string {\n  return Result.getOrThrow(Encoding.decodeBase64UrlString(input));\n}\n\nexport function signPayload(payload: string, secret: Uint8Array): string {\n  return NodeCrypto.createHmac(\"sha256\", Buffer.from(secret)).update(payload).digest(\"base64url\");\n}\n\nexport function timingSafeEqualBase64Url(left: string, right: string): boolean {\n  const leftBuffer = Buffer.from(left, \"base64url\");\n  const rightBuffer = Buffer.from(right, \"base64url\");\n  if (leftBuffer.length !== rightBuffer.length) {\n    return false;\n  }\n  return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);\n}\n\nfunction normalizeNonEmptyString(value: string | null | undefined): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeIpAddress(value: string | null | undefined): string | undefined {\n  const normalized = normalizeNonEmptyString(value);\n  if (!normalized) {\n    return undefined;\n  }\n  return normalized.startsWith(\"::ffff:\") ? normalized.slice(\"::ffff:\".length) : normalized;\n}\n\nfunction inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {\n  if (!userAgent) {\n    return \"unknown\";\n  }\n\n  const normalized = userAgent.toLowerCase();\n  if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {\n    return \"bot\";\n  }\n  if (/ipad|tablet/.test(normalized)) {\n    return \"tablet\";\n  }\n  if (/iphone|android.+mobile|mobile/.test(normalized)) {\n    return \"mobile\";\n  }\n  return \"desktop\";\n}\n\nfunction inferBrowser(userAgent: string | undefined): string | undefined {\n  if (!userAgent) {\n    return undefined;\n  }\n  const normalized = userAgent.toLowerCase();\n  if (/edg\\//.test(normalized)) return \"Edge\";\n  if (/opr\\//.test(normalized)) return \"Opera\";\n  if (/firefox\\//.test(normalized)) return \"Firefox\";\n  if (/electron\\//.test(normalized)) return \"Electron\";\n  if (/chrome\\//.test(normalized) || /crios\\//.test(normalized)) return \"Chrome\";\n  if (/safari\\//.test(normalized) && !/chrome\\//.test(normalized)) return \"Safari\";\n  return undefined;\n}\n\nfunction inferOs(userAgent: string | undefined): string | undefined {\n  if (!userAgent) {\n    return undefined;\n  }\n  const normalized = userAgent.toLowerCase();\n  if (/iphone|ipad|ipod/.test(normalized)) return \"iOS\";\n  if (/android/.test(normalized)) return \"Android\";\n  if (/mac os x|macintosh/.test(normalized)) return \"macOS\";\n  if (/windows nt/.test(normalized)) return \"Windows\";\n  if (/linux/.test(normalized)) return \"Linux\";\n  return undefined;\n}\n\nfunction readRemoteAddressFromSource(source: unknown): string | undefined {\n  if (!source || typeof source !== \"object\") {\n    return undefined;\n  }\n\n  const candidate = source as {\n    readonly remoteAddress?: string | null;\n    readonly socket?: {\n      readonly remoteAddress?: string | null;\n    };\n  };\n\n  return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);\n}\n\nexport function deriveAuthClientMetadata(input: {\n  readonly request: HttpServerRequest.HttpServerRequest;\n  readonly presented?: AuthClientPresentationMetadata;\n}): AuthClientMetadata {\n  const userAgent = normalizeNonEmptyString(input.request.headers[\"user-agent\"]);\n  const ipAddress = readRemoteAddressFromSource(input.request.source);\n  const os = input.presented?.os ?? inferOs(userAgent);\n  const browser = inferBrowser(userAgent);\n  return {\n    ...(input.presented?.label ? { label: input.presented.label } : {}),\n    ...(ipAddress ? { ipAddress } : {}),\n    ...(userAgent ? { userAgent } : {}),\n    deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),\n    ...(os ? { os } : {}),\n    ...(browser ? { browser } : {}),\n  };\n}\n","import type { ServerAuthDescriptor } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport { isRemoteReachableHost, resolveSessionCookieName } from \"./utils.ts\";\n\nexport class EnvironmentAuthPolicy extends Context.Service<\n  EnvironmentAuthPolicy,\n  {\n    readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;\n  }\n>()(\"t3/auth/EnvironmentAuthPolicy\") {}\n\nexport const make = Effect.gen(function* () {\n  const config = yield* ServerConfig.ServerConfig;\n  const isRemoteReachable = isRemoteReachableHost(config.host);\n\n  const policy =\n    config.mode === \"desktop\"\n      ? isRemoteReachable\n        ? \"remote-reachable\"\n        : \"desktop-managed-local\"\n      : isRemoteReachable\n        ? \"remote-reachable\"\n        : \"loopback-browser\";\n\n  const bootstrapMethods: ServerAuthDescriptor[\"bootstrapMethods\"] =\n    policy === \"desktop-managed-local\"\n      ? [\"desktop-bootstrap\"]\n      : config.mode === \"desktop\" && policy === \"remote-reachable\"\n        ? [\"desktop-bootstrap\", \"one-time-token\"]\n        : [\"one-time-token\"];\n\n  const descriptor: ServerAuthDescriptor = {\n    policy,\n    bootstrapMethods,\n    sessionMethods: [\"browser-session-cookie\", \"bearer-access-token\", \"dpop-access-token\"],\n    sessionCookieName: resolveSessionCookieName({\n      mode: config.mode,\n      port: config.port,\n      host: config.host,\n      instanceKey: config.stateDir,\n      development: config.devUrl !== undefined,\n    }),\n  };\n\n  return EnvironmentAuthPolicy.of({\n    getDescriptor: () =>\n      Effect.succeed(descriptor).pipe(Effect.withSpan(\"EnvironmentAuthPolicy.getDescriptor\")),\n  });\n});\n\nexport const layer = Layer.effect(EnvironmentAuthPolicy, make);\n","/**\n * Wraps SQL execution callbacks with request encoding and result decoding.\n *\n * `SqlSchema` is a small adapter between Effect Schema and SQL statements. Each\n * helper builds a function that accepts the decoded request type used by\n * application code, encodes it before calling `execute`, and decodes unknown\n * driver rows into the result schema. The helpers cover returning all rows, a\n * non-empty row list, the first row, an optional first row, or discarding the\n * SQL result for side-effect-only statements.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Cause from \"../../Cause.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Schema from \"../../Schema.js\";\n/**\n * Builds a query function that encodes the request and decodes all result rows,\n * allowing an empty result set.\n *\n * **When to use**\n *\n * Use when you need to run a query that may return zero or more rows and\n * represent an empty result as an empty array.\n *\n * @see {@link findNonEmpty} for queries where an empty result is a failure\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const findAll = options => {\n  const encodeRequest = Schema.encodeEffect(options.Request);\n  const decode = Schema.decodeUnknownEffect(Schema.mutable(Schema.Array(options.Result)));\n  return request => Effect.flatMap(Effect.flatMap(encodeRequest(request), options.execute), decode);\n};\n/**\n * Builds a query function that encodes the request, decodes all result rows,\n * and fails with `NoSuchElementError` when the result set is empty.\n *\n * **When to use**\n *\n * Use when you need to run a query that must return at least one row and treat\n * an empty result as a failure.\n *\n * @see {@link findAll} for queries where an empty result should return an empty array\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const findNonEmpty = options => {\n  const find = findAll(options);\n  return request => Effect.flatMap(find(request), results => Arr.isArrayNonEmpty(results) ? Effect.succeed(results) : Effect.fail(new Cause.NoSuchElementError()));\n};\nconst void_ = options => {\n  const encode = Schema.encodeEffect(options.Request);\n  return request => Effect.asVoid(Effect.flatMap(encode(request), options.execute));\n};\nexport {\n/**\n * Runs a sql query with a request schema and discard the result.\n *\n * @category constructors\n * @since 4.0.0\n */\nvoid_ as void };\n/**\n * Builds a query function that encodes the request, decodes the first result\n * row, and fails with `NoSuchElementError` when no rows are returned.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const findOne = options => {\n  const encodeRequest = Schema.encodeEffect(options.Request);\n  const decode = Schema.decodeUnknownEffect(options.Result);\n  return request => Effect.flatMap(Effect.flatMap(encodeRequest(request), options.execute), arr => Arr.isReadonlyArrayNonEmpty(arr) ? decode(arr[0]) : Effect.fail(new Cause.NoSuchElementError()));\n};\n/**\n * Builds a query function that encodes the request, decodes the first result row\n * as `Option.some`, and returns `Option.none` when no rows are returned.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const findOneOption = options => {\n  const encodeRequest = Schema.encodeEffect(options.Request);\n  const decode = Schema.decodeUnknownEffect(options.Result);\n  return request => Effect.flatMap(Effect.flatMap(encodeRequest(request), options.execute), arr => Arr.isReadonlyArrayNonEmpty(arr) ? Effect.asSome(decode(arr[0])) : Effect.succeedNone);\n};\n//# sourceMappingURL=SqlSchema.js.map","import * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\n\nfunction summarizeSchemaIssue(issue: SchemaIssue.Issue): string {\n  switch (issue._tag) {\n    case \"Filter\":\n    case \"Encoding\":\n    case \"Pointer\":\n      return `${issue._tag}(${summarizeSchemaIssue(issue.issue)})`;\n    case \"Composite\":\n    case \"AnyOf\":\n      return `${issue._tag}(${issue.issues.map(summarizeSchemaIssue).join(\",\")})`;\n    default:\n      return issue._tag;\n  }\n}\n\n// ===============================\n// Core Persistence Errors\n// ===============================\n\nexport const PersistenceErrorCorrelation = Schema.Union([\n  Schema.Struct({ sessionId: Schema.String }),\n  Schema.Struct({ currentSessionId: Schema.String }),\n  Schema.Struct({ pairingLinkId: Schema.String }),\n  Schema.Struct({ threadId: Schema.String }),\n]);\nexport type PersistenceErrorCorrelation = typeof PersistenceErrorCorrelation.Type;\n\nexport class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlError>()(\n  \"PersistenceSqlError\",\n  {\n    operation: Schema.String,\n    detail: Schema.optional(Schema.String),\n    correlation: Schema.optional(PersistenceErrorCorrelation),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return this.detail === undefined\n      ? `SQL error in ${this.operation}`\n      : `SQL error in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceDecodeError>()(\n  \"PersistenceDecodeError\",\n  {\n    operation: Schema.String,\n    issue: Schema.String,\n    correlation: Schema.optional(PersistenceErrorCorrelation),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  static fromSchemaError(\n    operation: string,\n    cause: Schema.SchemaError,\n    correlation?: PersistenceErrorCorrelation,\n  ): PersistenceDecodeError {\n    return new PersistenceDecodeError({\n      operation,\n      issue: summarizeSchemaIssue(cause.issue),\n      ...(correlation === undefined ? {} : { correlation }),\n      cause,\n    });\n  }\n\n  override get message(): string {\n    return `Decode error in ${this.operation}: ${this.issue}`;\n  }\n}\nconst isPersistenceSqlError = Schema.is(PersistenceSqlError);\nconst isPersistenceDecodeError = Schema.is(PersistenceDecodeError);\n\n// Kept for orchestration/projection call sites, which are being revamped separately.\nexport function toPersistenceSqlError(operation: string) {\n  return (cause: unknown): PersistenceSqlError =>\n    new PersistenceSqlError({\n      operation,\n      detail: `Failed to execute ${operation}`,\n      cause,\n    });\n}\n\n// Kept for orchestration/projection call sites, which are being revamped separately.\nexport function toPersistenceDecodeError(operation: string) {\n  return (cause: Schema.SchemaError): PersistenceDecodeError =>\n    PersistenceDecodeError.fromSchemaError(operation, cause);\n}\n\nexport const isPersistenceError = (u: unknown) =>\n  isPersistenceSqlError(u) || isPersistenceDecodeError(u);\n\n// ===============================\n// Provider Session Repository Errors\n// ===============================\n\nexport class ProviderSessionRepositoryValidationError extends Schema.TaggedErrorClass<ProviderSessionRepositoryValidationError>()(\n  \"ProviderSessionRepositoryValidationError\",\n  {\n    operation: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider session repository validation failed in ${this.operation}: ${this.issue}`;\n  }\n}\n\nexport class ProviderSessionRepositoryPersistenceError extends Schema.TaggedErrorClass<ProviderSessionRepositoryPersistenceError>()(\n  \"ProviderSessionRepositoryPersistenceError\",\n  {\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider session repository persistence error in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport type OrchestrationEventStoreError = PersistenceSqlError | PersistenceDecodeError;\n\nexport type ProviderSessionRepositoryError =\n  | ProviderSessionRepositoryValidationError\n  | ProviderSessionRepositoryPersistenceError;\n\nexport type OrchestrationCommandReceiptRepositoryError =\n  | PersistenceSqlError\n  | PersistenceDecodeError;\n\nexport type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;\nexport type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;\nexport type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;\n\nexport type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport { AuthEnvironmentScopes } from \"@t3tools/contracts\";\n\nimport {\n  type AuthPairingLinkRepositoryError,\n  PersistenceDecodeError,\n  type PersistenceErrorCorrelation,\n  PersistenceSqlError,\n} from \"./Errors.ts\";\n\nexport const AuthPairingLinkRecord = Schema.Struct({\n  id: Schema.String,\n  credential: Schema.String,\n  method: Schema.Literals([\"desktop-bootstrap\", \"one-time-token\"]),\n  scopes: Schema.fromJsonString(AuthEnvironmentScopes),\n  subject: Schema.String,\n  label: Schema.NullOr(Schema.String),\n  proofKeyThumbprint: Schema.NullOr(Schema.String),\n  createdAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n  consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n  revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\nexport type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;\n\nexport const CreateAuthPairingLinkInput = Schema.Struct({\n  id: Schema.String,\n  credential: Schema.String,\n  method: Schema.Literals([\"desktop-bootstrap\", \"one-time-token\"]),\n  scopes: AuthEnvironmentScopes,\n  subject: Schema.String,\n  label: Schema.NullOr(Schema.String),\n  proofKeyThumbprint: Schema.NullOr(Schema.String),\n  createdAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n});\nexport type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;\n\nexport const ConsumeAuthPairingLinkInput = Schema.Struct({\n  credential: Schema.String,\n  proofKeyThumbprint: Schema.NullOr(Schema.String),\n  consumedAt: Schema.DateTimeUtcFromString,\n  now: Schema.DateTimeUtcFromString,\n});\nexport type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;\n\nexport const ListActiveAuthPairingLinksInput = Schema.Struct({\n  now: Schema.DateTimeUtcFromString,\n});\nexport type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;\n\nexport const RevokeAuthPairingLinkInput = Schema.Struct({\n  id: Schema.String,\n  revokedAt: Schema.DateTimeUtcFromString,\n});\nexport type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;\n\nexport const GetAuthPairingLinkByCredentialInput = Schema.Struct({\n  credential: Schema.String,\n});\nexport type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;\n\nconst AuthPairingLinkRawDbRow = Schema.Struct({\n  id: Schema.String,\n  credential: Schema.Unknown,\n  method: Schema.Unknown,\n  scopes: Schema.Unknown,\n  subject: Schema.Unknown,\n  label: Schema.Unknown,\n  proofKeyThumbprint: Schema.Unknown,\n  createdAt: Schema.Unknown,\n  expiresAt: Schema.Unknown,\n  consumedAt: Schema.Unknown,\n  revokedAt: Schema.Unknown,\n});\n\nconst decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);\n\nexport class AuthPairingLinkRepository extends Context.Service<\n  AuthPairingLinkRepository,\n  {\n    readonly create: (\n      input: CreateAuthPairingLinkInput,\n    ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;\n    readonly consumeAvailable: (\n      input: ConsumeAuthPairingLinkInput,\n    ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;\n    readonly listActive: (\n      input: ListActiveAuthPairingLinksInput,\n    ) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;\n    readonly revoke: (\n      input: RevokeAuthPairingLinkInput,\n    ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;\n    readonly getByCredential: (\n      input: GetAuthPairingLinkByCredentialInput,\n    ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;\n  }\n>()(\"t3/persistence/AuthPairingLinks/AuthPairingLinkRepository\") {}\n\nfunction toPersistenceSqlOrDecodeError(\n  sqlOperation: string,\n  decodeOperation: string,\n  correlation?: PersistenceErrorCorrelation,\n) {\n  return (cause: unknown): AuthPairingLinkRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)\n      : new PersistenceSqlError({\n          operation: sqlOperation,\n          ...(correlation === undefined ? {} : { correlation }),\n          cause,\n        });\n}\n\nexport const make = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const createPairingLinkRow = SqlSchema.void({\n    Request: CreateAuthPairingLinkInput,\n    execute: (input) =>\n      sql`\n        INSERT INTO auth_pairing_links (\n          id,\n          credential,\n          method,\n          scopes,\n          subject,\n          label,\n          proof_key_thumbprint,\n          created_at,\n          expires_at,\n          consumed_at,\n          revoked_at\n        )\n        VALUES (\n          ${input.id},\n          ${input.credential},\n          ${input.method},\n          ${JSON.stringify(input.scopes)},\n          ${input.subject},\n          ${input.label},\n          ${input.proofKeyThumbprint},\n          ${input.createdAt},\n          ${input.expiresAt},\n          NULL,\n          NULL\n        )\n      `,\n  });\n\n  const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({\n    Request: ConsumeAuthPairingLinkInput,\n    Result: AuthPairingLinkRawDbRow,\n    execute: ({ credential, proofKeyThumbprint, consumedAt, now }) =>\n      sql`\n        UPDATE auth_pairing_links\n        SET consumed_at = ${consumedAt}\n        WHERE credential = ${credential}\n          AND revoked_at IS NULL\n          AND consumed_at IS NULL\n          AND expires_at > ${now}\n          AND (\n            proof_key_thumbprint IS NULL\n            OR proof_key_thumbprint = ${proofKeyThumbprint}\n          )\n        RETURNING\n          id AS \"id\",\n          credential AS \"credential\",\n          method AS \"method\",\n          scopes AS \"scopes\",\n          subject AS \"subject\",\n          label AS \"label\",\n          proof_key_thumbprint AS \"proofKeyThumbprint\",\n          created_at AS \"createdAt\",\n          expires_at AS \"expiresAt\",\n          consumed_at AS \"consumedAt\",\n          revoked_at AS \"revokedAt\"\n      `,\n  });\n\n  const listActivePairingLinkRows = SqlSchema.findAll({\n    Request: ListActiveAuthPairingLinksInput,\n    Result: AuthPairingLinkRawDbRow,\n    execute: ({ now }) =>\n      sql`\n        SELECT\n          id AS \"id\",\n          credential AS \"credential\",\n          method AS \"method\",\n          scopes AS \"scopes\",\n          subject AS \"subject\",\n          label AS \"label\",\n          proof_key_thumbprint AS \"proofKeyThumbprint\",\n          created_at AS \"createdAt\",\n          expires_at AS \"expiresAt\",\n          consumed_at AS \"consumedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_pairing_links\n        WHERE revoked_at IS NULL\n          AND consumed_at IS NULL\n          AND expires_at > ${now}\n        ORDER BY created_at DESC, id DESC\n      `,\n  });\n\n  const revokePairingLinkRow = SqlSchema.findAll({\n    Request: RevokeAuthPairingLinkInput,\n    Result: Schema.Struct({ id: Schema.String }),\n    execute: ({ id, revokedAt }) =>\n      sql`\n        UPDATE auth_pairing_links\n        SET revoked_at = ${revokedAt}\n        WHERE id = ${id}\n          AND revoked_at IS NULL\n          AND consumed_at IS NULL\n        RETURNING id AS \"id\"\n      `,\n  });\n\n  const getPairingLinkRowByCredential = SqlSchema.findOneOption({\n    Request: GetAuthPairingLinkByCredentialInput,\n    Result: AuthPairingLinkRawDbRow,\n    execute: ({ credential }) =>\n      sql`\n        SELECT\n          id AS \"id\",\n          credential AS \"credential\",\n          method AS \"method\",\n          scopes AS \"scopes\",\n          subject AS \"subject\",\n          label AS \"label\",\n          proof_key_thumbprint AS \"proofKeyThumbprint\",\n          created_at AS \"createdAt\",\n          expires_at AS \"expiresAt\",\n          consumed_at AS \"consumedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_pairing_links\n        WHERE credential = ${credential}\n      `,\n  });\n\n  const create: AuthPairingLinkRepository[\"Service\"][\"create\"] = (input) =>\n    createPairingLinkRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.create:query\",\n          \"AuthPairingLinkRepository.create:encodeRequest\",\n          { pairingLinkId: input.id },\n        ),\n      ),\n    );\n\n  const consumeAvailable: AuthPairingLinkRepository[\"Service\"][\"consumeAvailable\"] = (input) =>\n    consumeAvailablePairingLinkRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.consumeAvailable:query\",\n          \"AuthPairingLinkRepository.consumeAvailable:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeAuthPairingLinkDbRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"AuthPairingLinkRepository.consumeAvailable:decodeRow\",\n                  cause,\n                  { pairingLinkId: row.id },\n                ),\n              ),\n              Effect.map(Option.some),\n            ),\n        }),\n      ),\n    );\n\n  const listActive: AuthPairingLinkRepository[\"Service\"][\"listActive\"] = (input) =>\n    listActivePairingLinkRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.listActive:query\",\n          \"AuthPairingLinkRepository.listActive:decodeRows\",\n        ),\n      ),\n      Effect.flatMap((rows) =>\n        Effect.forEach(rows, (row) =>\n          decodeAuthPairingLinkDbRow(row).pipe(\n            Effect.mapError((cause) =>\n              PersistenceDecodeError.fromSchemaError(\n                \"AuthPairingLinkRepository.listActive:decodeRows\",\n                cause,\n                { pairingLinkId: row.id },\n              ),\n            ),\n          ),\n        ),\n      ),\n    );\n\n  const revoke: AuthPairingLinkRepository[\"Service\"][\"revoke\"] = (input) =>\n    revokePairingLinkRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.revoke:query\",\n          \"AuthPairingLinkRepository.revoke:decodeRows\",\n          { pairingLinkId: input.id },\n        ),\n      ),\n      Effect.map((rows) => rows.length > 0),\n    );\n\n  const getByCredential: AuthPairingLinkRepository[\"Service\"][\"getByCredential\"] = (input) =>\n    getPairingLinkRowByCredential(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.getByCredential:query\",\n          \"AuthPairingLinkRepository.getByCredential:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeAuthPairingLinkDbRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"AuthPairingLinkRepository.getByCredential:decodeRow\",\n                  cause,\n                  { pairingLinkId: row.id },\n                ),\n              ),\n              Effect.map(Option.some),\n            ),\n        }),\n      ),\n    );\n\n  return {\n    create,\n    consumeAvailable,\n    listActive,\n    revoke,\n    getByCredential,\n  } satisfies AuthPairingLinkRepository[\"Service\"];\n});\n\nexport const layer = Layer.effect(AuthPairingLinkRepository, make);\n","import {\n  AuthAdministrativeScopes,\n  AuthStandardClientScopes,\n  type AuthEnvironmentScope,\n  type AuthPairingLink,\n  type ServerAuthBootstrapMethod,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as AuthPairingLinks from \"../persistence/AuthPairingLinks.ts\";\n\nexport interface BootstrapGrant {\n  readonly method: ServerAuthBootstrapMethod;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly subject: string;\n  readonly label?: string;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt: DateTime.DateTime;\n}\n\nexport class UnknownBootstrapCredentialError extends Schema.TaggedErrorClass<UnknownBootstrapCredentialError>()(\n  \"UnknownBootstrapCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Unknown bootstrap credential.\";\n  }\n}\n\nexport class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<ExpiredBootstrapCredentialError>()(\n  \"ExpiredBootstrapCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Bootstrap credential expired.\";\n  }\n}\n\nexport class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedErrorClass<BootstrapCredentialProofKeyMismatchError>()(\n  \"BootstrapCredentialProofKeyMismatchError\",\n  {},\n) {\n  override get message(): string {\n    return \"Bootstrap credential proof key mismatch.\";\n  }\n}\n\nexport class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClass<UnavailableBootstrapCredentialError>()(\n  \"UnavailableBootstrapCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Bootstrap credential is no longer available.\";\n  }\n}\n\nexport const BootstrapCredentialInvalidError = Schema.Union([\n  UnknownBootstrapCredentialError,\n  ExpiredBootstrapCredentialError,\n  BootstrapCredentialProofKeyMismatchError,\n  UnavailableBootstrapCredentialError,\n]);\nexport type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;\nexport const isBootstrapCredentialInvalidError = Schema.is(BootstrapCredentialInvalidError);\n\nexport class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActivePairingLinksLoadError>()(\n  \"ActivePairingLinksLoadError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to load active pairing links.\";\n  }\n}\n\nexport class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(\n  \"PairingLinkRevokeError\",\n  {\n    pairingLinkId: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to revoke pairing link '${this.pairingLinkId}'.`;\n  }\n}\n\nexport class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(\n  \"PairingCredentialIssueError\",\n  {\n    pairingLinkId: Schema.String,\n    subject: Schema.String,\n    label: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;\n  }\n}\n\nexport class PairingCredentialRandomGenerationError extends Schema.TaggedErrorClass<PairingCredentialRandomGenerationError>()(\n  \"PairingCredentialRandomGenerationError\",\n  {\n    operation: Schema.Literals([\"generate-id\", \"generate-token\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to generate pairing credential data during '${this.operation}'.`;\n  }\n}\n\nexport class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeError>()(\n  \"BootstrapCredentialConsumeError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to consume bootstrap credential.\";\n  }\n}\n\nexport class BootstrapCredentialConsumeAvailableError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeAvailableError>()(\n  \"BootstrapCredentialConsumeAvailableError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to atomically consume an available bootstrap credential.\";\n  }\n}\n\nexport class BootstrapCredentialLookupError extends Schema.TaggedErrorClass<BootstrapCredentialLookupError>()(\n  \"BootstrapCredentialLookupError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to look up bootstrap credential state.\";\n  }\n}\n\nexport const BootstrapCredentialInternalError = Schema.Union([\n  ActivePairingLinksLoadError,\n  PairingLinkRevokeError,\n  PairingCredentialIssueError,\n  PairingCredentialRandomGenerationError,\n  BootstrapCredentialConsumeError,\n  BootstrapCredentialConsumeAvailableError,\n  BootstrapCredentialLookupError,\n]);\nexport type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;\nexport const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);\n\nexport const BootstrapCredentialError = Schema.Union([\n  BootstrapCredentialInvalidError,\n  BootstrapCredentialInternalError,\n]);\nexport type BootstrapCredentialError = typeof BootstrapCredentialError.Type;\nexport const isBootstrapCredentialError = Schema.is(BootstrapCredentialError);\n\nexport interface IssuedBootstrapCredential {\n  readonly id: string;\n  readonly credential: string;\n  readonly label?: string;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt: DateTime.Utc;\n}\n\nexport type BootstrapCredentialChange =\n  | {\n      readonly type: \"pairingLinkUpserted\";\n      readonly pairingLink: AuthPairingLink;\n    }\n  | {\n      readonly type: \"pairingLinkRemoved\";\n      readonly id: string;\n    };\n\nexport class PairingGrantStore extends Context.Service<\n  PairingGrantStore,\n  {\n    readonly issueOneTimeToken: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly subject?: string;\n      readonly label?: string;\n      readonly proofKeyThumbprint?: string;\n      /**\n       * \"startup\" marks the credential the server mints for itself at boot,\n       * which gets the long dev TTL when a dev URL is configured.\n       */\n      readonly purpose?: \"startup\";\n    }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;\n    readonly listActive: () => Effect.Effect<\n      ReadonlyArray<AuthPairingLink>,\n      BootstrapCredentialInternalError\n    >;\n    readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;\n    readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;\n    readonly consume: (\n      credential: string,\n      input?: {\n        readonly proofKeyThumbprint?: string;\n      },\n    ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;\n  }\n>()(\"t3/auth/PairingGrantStore\") {}\n\ninterface StoredBootstrapGrant extends BootstrapGrant {\n  readonly remainingUses: number | \"unbounded\";\n}\n\ntype ConsumeResult =\n  | {\n      readonly _tag: \"error\";\n      readonly reason: \"not-found\" | \"expired\";\n      readonly error: BootstrapCredentialError;\n    }\n  | {\n      readonly _tag: \"success\";\n      readonly grant: BootstrapGrant;\n    };\n\nconst DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);\n// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or\n// stdin) at backend launch, so it doesn't have to be short-lived the\n// way a user-facing pairing link does. Letting it live for the\n// lifetime of the backend process (24h is more than long enough for\n// practical desktop use, and well under \"forever\" in case the seed\n// gets logged anywhere by accident) means a page reload past the 5-min\n// window can still recover by re-bootstrapping rather than locking\n// the user out of the backend.\nconst DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);\n// A dev server's startup token is read off a log by whoever (or whatever) is\n// driving the session, often minutes later — after a `node --watch` restart, a\n// detour into another task, or a hand-off to the person actually doing the\n// testing. Five minutes turns that into a restart-the-server loop for no\n// security benefit: the token only unlocks a local dev backend, and its holder\n// could read the log anyway. Same reasoning (and duration) as the desktop\n// bootstrap grant above. Only applies when a dev URL is configured; user-issued\n// pairing links and real servers keep the 5-minute default.\nconst DEV_STARTUP_TTL_HOURS = Duration.hours(24);\nconst PAIRING_TOKEN_ALPHABET = \"23456789ABCDEFGHJKLMNPQRSTUVWXYZ\";\nconst PAIRING_TOKEN_LENGTH = 12;\nconst PAIRING_TOKEN_REJECTION_LIMIT =\n  Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;\n\nexport const make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const config = yield* ServerConfig.ServerConfig;\n  const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;\n  const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());\n  const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();\n  const generatePairingToken = Effect.gen(function* () {\n    let credential = \"\";\n    while (credential.length < PAIRING_TOKEN_LENGTH) {\n      const bytes = yield* crypto\n        .randomBytes(PAIRING_TOKEN_LENGTH)\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new PairingCredentialRandomGenerationError({ operation: \"generate-token\", cause }),\n          ),\n        );\n      for (const byte of bytes) {\n        if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {\n          continue;\n        }\n        credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;\n        if (credential.length === PAIRING_TOKEN_LENGTH) {\n          return credential;\n        }\n      }\n    }\n    return credential;\n  });\n\n  const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>\n    Ref.update(seededGrantsRef, (current) => {\n      const next = new Map(current);\n      next.set(credential, grant);\n      return next;\n    });\n\n  const emitUpsert = (pairingLink: AuthPairingLink) =>\n    PubSub.publish(changesPubSub, {\n      type: \"pairingLinkUpserted\",\n      pairingLink,\n    }).pipe(Effect.asVoid);\n\n  const emitRemoved = (id: string) =>\n    PubSub.publish(changesPubSub, {\n      type: \"pairingLinkRemoved\",\n      id,\n    }).pipe(Effect.asVoid);\n\n  if (config.desktopBootstrapToken) {\n    const now = yield* DateTime.now;\n    yield* seedGrant(config.desktopBootstrapToken, {\n      method: \"desktop-bootstrap\",\n      scopes: AuthAdministrativeScopes,\n      subject: \"desktop-bootstrap\",\n      expiresAt: DateTime.add(now, {\n        milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),\n      }),\n      // Unbounded uses so the renderer can re-exchange the seed for a\n      // fresh bearer session after a page reload (or after the prior\n      // bearer expires). The seed itself stays inside the desktop\n      // process and the rendered page, both of which the user already\n      // implicitly trusts.\n      remainingUses: \"unbounded\",\n    });\n  }\n\n  const listActive: PairingGrantStore[\"Service\"][\"listActive\"] = Effect.fn(\n    \"PairingGrantStore.listActive\",\n  )(\n    function* () {\n      const now = yield* DateTime.now;\n      const rows = yield* pairingLinks.listActive({ now });\n\n      return rows.map((row) =>\n        row.label\n          ? ({\n              id: row.id,\n              credential: row.credential,\n              scopes: row.scopes,\n              subject: row.subject,\n              label: row.label,\n              createdAt: row.createdAt,\n              expiresAt: row.expiresAt,\n            } satisfies AuthPairingLink)\n          : ({\n              id: row.id,\n              credential: row.credential,\n              scopes: row.scopes,\n              subject: row.subject,\n              createdAt: row.createdAt,\n              expiresAt: row.expiresAt,\n            } satisfies AuthPairingLink),\n      );\n    },\n    Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),\n  );\n\n  const revoke: PairingGrantStore[\"Service\"][\"revoke\"] = Effect.fn(\"PairingGrantStore.revoke\")(\n    function* (id) {\n      const revokedAt = yield* DateTime.now;\n      const revoked = yield* pairingLinks\n        .revoke({\n          id,\n          revokedAt,\n        })\n        .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));\n      if (revoked) {\n        yield* emitRemoved(id);\n      }\n      return revoked;\n    },\n  );\n\n  const issueOneTimeToken: PairingGrantStore[\"Service\"][\"issueOneTimeToken\"] = Effect.fn(\n    \"PairingGrantStore.issueOneTimeToken\",\n  )(function* (input) {\n    const id = yield* crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) => new PairingCredentialRandomGenerationError({ operation: \"generate-id\", cause }),\n      ),\n    );\n    const credential = yield* generatePairingToken;\n    const isDevStartupToken = config.devUrl !== undefined && input?.purpose === \"startup\";\n    const ttl =\n      input?.ttl ??\n      (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);\n    const now = yield* DateTime.now;\n    const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });\n    const issued: IssuedBootstrapCredential = {\n      id,\n      credential,\n      ...(input?.label ? { label: input.label } : {}),\n      ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),\n      expiresAt,\n    };\n    const subject = input?.subject ?? \"one-time-token\";\n    yield* pairingLinks\n      .create({\n        id,\n        credential,\n        method: \"one-time-token\",\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        subject,\n        label: input?.label ?? null,\n        proofKeyThumbprint: input?.proofKeyThumbprint ?? null,\n        createdAt: now,\n        expiresAt: expiresAt,\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new PairingCredentialIssueError({\n              pairingLinkId: id,\n              subject,\n              ...(input?.label ? { label: input.label } : {}),\n              cause,\n            }),\n        ),\n      );\n    yield* emitUpsert({\n      id,\n      credential,\n      scopes: input?.scopes ?? AuthStandardClientScopes,\n      subject: input?.subject ?? \"one-time-token\",\n      ...(input?.label ? { label: input.label } : {}),\n      createdAt: now,\n      expiresAt,\n    });\n    return issued;\n  });\n\n  const consume: PairingGrantStore[\"Service\"][\"consume\"] = Effect.fn(\"PairingGrantStore.consume\")(\n    function* (credential, input) {\n      const now = yield* DateTime.now;\n      const seededResult: ConsumeResult = yield* Ref.modify(\n        seededGrantsRef,\n        (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {\n          const grant = current.get(credential);\n          if (!grant) {\n            return [\n              {\n                _tag: \"error\",\n                reason: \"not-found\",\n                error: new UnknownBootstrapCredentialError({}),\n              },\n              current,\n            ];\n          }\n\n          const next = new Map(current);\n          if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {\n            next.delete(credential);\n            return [\n              {\n                _tag: \"error\",\n                reason: \"expired\",\n                error: new ExpiredBootstrapCredentialError({}),\n              },\n              next,\n            ];\n          }\n\n          if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {\n            return [\n              {\n                _tag: \"error\",\n                reason: \"not-found\",\n                error: new BootstrapCredentialProofKeyMismatchError({}),\n              },\n              next,\n            ];\n          }\n\n          const remainingUses = grant.remainingUses;\n          if (typeof remainingUses === \"number\") {\n            if (remainingUses <= 1) {\n              next.delete(credential);\n            } else {\n              next.set(credential, {\n                ...grant,\n                remainingUses: remainingUses - 1,\n              });\n            }\n          }\n\n          return [\n            {\n              _tag: \"success\",\n              grant: {\n                method: grant.method,\n                scopes: grant.scopes,\n                subject: grant.subject,\n                ...(grant.label ? { label: grant.label } : {}),\n                ...(grant.proofKeyThumbprint\n                  ? { proofKeyThumbprint: grant.proofKeyThumbprint }\n                  : {}),\n                expiresAt: grant.expiresAt,\n              } satisfies BootstrapGrant,\n            },\n            next,\n          ];\n        },\n      );\n\n      if (seededResult._tag === \"success\") {\n        return seededResult.grant;\n      }\n      if (seededResult.reason !== \"not-found\") {\n        return yield* seededResult.error;\n      }\n\n      const consumed = yield* pairingLinks\n        .consumeAvailable({\n          credential,\n          proofKeyThumbprint: input?.proofKeyThumbprint ?? null,\n          consumedAt: now,\n          now,\n        })\n        .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));\n\n      if (Option.isSome(consumed)) {\n        yield* emitRemoved(consumed.value.id);\n        return {\n          method: consumed.value.method,\n          scopes: consumed.value.scopes,\n          subject: consumed.value.subject,\n          ...(consumed.value.label ? { label: consumed.value.label } : {}),\n          ...(consumed.value.proofKeyThumbprint\n            ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }\n            : {}),\n          expiresAt: consumed.value.expiresAt,\n        } satisfies BootstrapGrant;\n      }\n\n      const matching = yield* pairingLinks\n        .getByCredential({ credential })\n        .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));\n      if (Option.isNone(matching)) {\n        return yield* new UnknownBootstrapCredentialError({});\n      }\n\n      if (matching.value.revokedAt !== null) {\n        return yield* new UnavailableBootstrapCredentialError({});\n      }\n\n      if (matching.value.consumedAt !== null) {\n        return yield* new UnknownBootstrapCredentialError({});\n      }\n\n      if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {\n        return yield* new ExpiredBootstrapCredentialError({});\n      }\n\n      if (\n        matching.value.proofKeyThumbprint !== null &&\n        matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint\n      ) {\n        return yield* new BootstrapCredentialProofKeyMismatchError({});\n      }\n\n      return yield* new UnavailableBootstrapCredentialError({});\n    },\n  );\n\n  return PairingGrantStore.of({\n    issueOneTimeToken,\n    listActive,\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n    revoke,\n    consume,\n  });\n});\n\nexport const layer = Layer.effect(PairingGrantStore, make).pipe(\n  Layer.provideMerge(AuthPairingLinks.layer),\n);\n","import * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ServerConfig from \"../config.ts\";\n\nconst secretStoreErrorContext = {\n  resource: Schema.String,\n  cause: Schema.Defect(),\n};\n\nexport class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(\n  \"SecretStoreSecureError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to secure ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(\n  \"SecretStoreReadError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(\n  \"SecretStoreTemporaryPathError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to create temporary path for ${this.resource}.`;\n  }\n}\n\nexport class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(\n  \"SecretStorePersistError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to persist ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(\n  \"SecretStoreRandomGenerationError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to generate random bytes for ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(\n  \"SecretStoreConcurrentReadError\",\n  {\n    resource: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.resource} after concurrent creation.`;\n  }\n}\n\nexport class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(\n  \"SecretStoreRemoveError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to remove ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(\n  \"SecretStoreDecodeError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to decode ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(\n  \"SecretStoreEncodeError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to encode ${this.resource}.`;\n  }\n}\n\nexport const SecretStoreError = Schema.Union([\n  SecretStoreSecureError,\n  SecretStoreReadError,\n  SecretStoreTemporaryPathError,\n  SecretStorePersistError,\n  SecretStoreRandomGenerationError,\n  SecretStoreConcurrentReadError,\n  SecretStoreRemoveError,\n  SecretStoreDecodeError,\n  SecretStoreEncodeError,\n]);\nexport type SecretStoreError = typeof SecretStoreError.Type;\nexport const isSecretStoreError = Schema.is(SecretStoreError);\n\nconst isPlatformError = (value: unknown): value is PlatformError.PlatformError =>\n  Predicate.isTagged(value, \"PlatformError\");\n\nexport const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>\n  \"cause\" in error && isPlatformError(error.cause) && error.cause.reason._tag === \"AlreadyExists\";\n\nexport class ServerSecretStore extends Context.Service<\n  ServerSecretStore,\n  {\n    readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;\n    readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;\n    readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;\n    readonly getOrCreateRandom: (\n      name: string,\n      bytes: number,\n    ) => Effect.Effect<Uint8Array, SecretStoreError>;\n    readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;\n  }\n>()(\"t3/auth/ServerSecretStore\") {}\n\nexport const make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n\n  yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });\n  yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(\n    Effect.mapError(\n      (cause) =>\n        new SecretStoreSecureError({\n          resource: `secrets directory ${serverConfig.secretsDir}`,\n          cause,\n        }),\n    ),\n  );\n\n  const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);\n\n  const get: ServerSecretStore[\"Service\"][\"get\"] = (name) =>\n    fileSystem.readFile(resolveSecretPath(name)).pipe(\n      Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),\n      Effect.catch((cause) =>\n        cause.reason._tag === \"NotFound\"\n          ? Effect.succeed(Option.none())\n          : Effect.fail(\n              new SecretStoreReadError({\n                resource: `secret ${name}`,\n                cause,\n              }),\n            ),\n      ),\n      Effect.withSpan(\"ServerSecretStore.get\"),\n    );\n\n  const set: ServerSecretStore[\"Service\"][\"set\"] = (name, value) => {\n    const secretPath = resolveSecretPath(name);\n    return crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new SecretStoreTemporaryPathError({\n            resource: `secret ${name}`,\n            cause,\n          }),\n      ),\n      Effect.flatMap((uuid) => {\n        const tempPath = `${secretPath}.${uuid}.tmp`;\n        return Effect.gen(function* () {\n          yield* fileSystem.writeFile(tempPath, value);\n          yield* fileSystem.chmod(tempPath, 0o600);\n          yield* fileSystem.rename(tempPath, secretPath);\n          yield* fileSystem.chmod(secretPath, 0o600);\n        }).pipe(\n          Effect.catch((cause) =>\n            fileSystem.remove(tempPath).pipe(\n              Effect.ignore,\n              Effect.flatMap(() =>\n                Effect.fail(\n                  new SecretStorePersistError({\n                    resource: `secret ${name}`,\n                    cause,\n                  }),\n                ),\n              ),\n            ),\n          ),\n        );\n      }),\n      Effect.withSpan(\"ServerSecretStore.set\"),\n    );\n  };\n\n  const create: ServerSecretStore[\"Service\"][\"create\"] = (name, value) => {\n    const secretPath = resolveSecretPath(name);\n    return Effect.scoped(\n      Effect.gen(function* () {\n        const file = yield* fileSystem.open(secretPath, {\n          flag: \"wx\",\n          mode: 0o600,\n        });\n        yield* file.writeAll(value);\n        yield* file.sync;\n        yield* fileSystem.chmod(secretPath, 0o600);\n      }),\n    ).pipe(\n      Effect.mapError(\n        (cause) =>\n          new SecretStorePersistError({\n            resource: `secret ${name}`,\n            cause,\n          }),\n      ),\n    );\n  };\n\n  const getOrCreateRandom: ServerSecretStore[\"Service\"][\"getOrCreateRandom\"] = (name, bytes) =>\n    get(name).pipe(\n      Effect.flatMap(\n        Option.match({\n          onSome: Effect.succeed,\n          onNone: () =>\n            crypto.randomBytes(bytes).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new SecretStoreRandomGenerationError({\n                    resource: `secret ${name}`,\n                    cause,\n                  }),\n              ),\n              Effect.flatMap((generated) =>\n                create(name, generated).pipe(\n                  Effect.as(Uint8Array.from(generated)),\n                  Effect.catchIf(isSecretStoreError, (error) =>\n                    isSecretAlreadyExistsError(error)\n                      ? get(name).pipe(\n                          Effect.flatMap(\n                            Option.match({\n                              onSome: Effect.succeed,\n                              onNone: () =>\n                                Effect.fail(\n                                  new SecretStoreConcurrentReadError({\n                                    resource: `secret ${name}`,\n                                  }),\n                                ),\n                            }),\n                          ),\n                        )\n                      : Effect.fail(error),\n                  ),\n                ),\n              ),\n            ),\n        }),\n      ),\n      Effect.withSpan(\"ServerSecretStore.getOrCreateRandom\"),\n    );\n\n  const remove: ServerSecretStore[\"Service\"][\"remove\"] = (name) =>\n    fileSystem.remove(resolveSecretPath(name)).pipe(\n      Effect.catch((cause) =>\n        cause.reason._tag === \"NotFound\"\n          ? Effect.void\n          : Effect.fail(\n              new SecretStoreRemoveError({\n                resource: `secret ${name}`,\n                cause,\n              }),\n            ),\n      ),\n      Effect.withSpan(\"ServerSecretStore.remove\"),\n    );\n\n  return ServerSecretStore.of({\n    get,\n    set,\n    create,\n    getOrCreateRandom,\n    remove,\n  });\n});\n\nexport const layer = Layer.effect(ServerSecretStore, make);\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport {\n  AuthClientMetadataDeviceType,\n  AuthEnvironmentScopes,\n  AuthSessionId,\n  ServerAuthSessionMethod,\n} from \"@t3tools/contracts\";\n\nimport {\n  type AuthSessionRepositoryError,\n  PersistenceDecodeError,\n  type PersistenceErrorCorrelation,\n  PersistenceSqlError,\n} from \"./Errors.ts\";\n\nexport const AuthSessionClientMetadataRecord = Schema.Struct({\n  label: Schema.NullOr(Schema.String),\n  ipAddress: Schema.NullOr(Schema.String),\n  userAgent: Schema.NullOr(Schema.String),\n  deviceType: AuthClientMetadataDeviceType,\n  os: Schema.NullOr(Schema.String),\n  browser: Schema.NullOr(Schema.String),\n});\nexport type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;\n\nexport const AuthSessionRecord = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: Schema.String,\n  scopes: AuthEnvironmentScopes,\n  method: ServerAuthSessionMethod,\n  client: AuthSessionClientMetadataRecord,\n  issuedAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n  lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n  revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\nexport type AuthSessionRecord = typeof AuthSessionRecord.Type;\n\nexport const CreateAuthSessionInput = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: Schema.String,\n  scopes: AuthEnvironmentScopes,\n  method: ServerAuthSessionMethod,\n  client: AuthSessionClientMetadataRecord,\n  issuedAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n});\nexport type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;\n\nexport const GetAuthSessionByIdInput = Schema.Struct({\n  sessionId: AuthSessionId,\n});\nexport type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;\n\nexport const ListActiveAuthSessionsInput = Schema.Struct({\n  now: Schema.DateTimeUtcFromString,\n});\nexport type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;\n\nexport const RevokeAuthSessionInput = Schema.Struct({\n  sessionId: AuthSessionId,\n  revokedAt: Schema.DateTimeUtcFromString,\n});\nexport type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;\n\nexport const RevokeOtherAuthSessionsInput = Schema.Struct({\n  currentSessionId: AuthSessionId,\n  revokedAt: Schema.DateTimeUtcFromString,\n});\nexport type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;\n\nexport const SetAuthSessionLastConnectedAtInput = Schema.Struct({\n  sessionId: AuthSessionId,\n  lastConnectedAt: Schema.DateTimeUtcFromString,\n});\nexport type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;\n\nexport class AuthSessionRepository extends Context.Service<\n  AuthSessionRepository,\n  {\n    readonly create: (\n      input: CreateAuthSessionInput,\n    ) => Effect.Effect<void, AuthSessionRepositoryError>;\n    readonly getById: (\n      input: GetAuthSessionByIdInput,\n    ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;\n    readonly listActive: (\n      input: ListActiveAuthSessionsInput,\n    ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;\n    readonly revoke: (\n      input: RevokeAuthSessionInput,\n    ) => Effect.Effect<boolean, AuthSessionRepositoryError>;\n    readonly revokeAllExcept: (\n      input: RevokeOtherAuthSessionsInput,\n    ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;\n    readonly setLastConnectedAt: (\n      input: SetAuthSessionLastConnectedAtInput,\n    ) => Effect.Effect<void, AuthSessionRepositoryError>;\n  }\n>()(\"t3/persistence/AuthSessions/AuthSessionRepository\") {}\n\nconst AuthSessionDbRow = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: Schema.String,\n  scopes: Schema.fromJsonString(AuthEnvironmentScopes),\n  method: ServerAuthSessionMethod,\n  clientLabel: Schema.NullOr(Schema.String),\n  clientIpAddress: Schema.NullOr(Schema.String),\n  clientUserAgent: Schema.NullOr(Schema.String),\n  clientDeviceType: Schema.Literals([\"desktop\", \"mobile\", \"tablet\", \"bot\", \"unknown\"]),\n  clientOs: Schema.NullOr(Schema.String),\n  clientBrowser: Schema.NullOr(Schema.String),\n  issuedAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n  lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n  revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\n\nconst AuthSessionRawDbRow = Schema.Struct({\n  sessionId: Schema.String,\n  subject: Schema.Unknown,\n  scopes: Schema.Unknown,\n  method: Schema.Unknown,\n  clientLabel: Schema.Unknown,\n  clientIpAddress: Schema.Unknown,\n  clientUserAgent: Schema.Unknown,\n  clientDeviceType: Schema.Unknown,\n  clientOs: Schema.Unknown,\n  clientBrowser: Schema.Unknown,\n  issuedAt: Schema.Unknown,\n  expiresAt: Schema.Unknown,\n  lastConnectedAt: Schema.Unknown,\n  revokedAt: Schema.Unknown,\n});\n\nconst decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);\n\nfunction toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {\n  return {\n    sessionId: row.sessionId,\n    subject: row.subject,\n    scopes: row.scopes,\n    method: row.method,\n    client: {\n      label: row.clientLabel,\n      ipAddress: row.clientIpAddress,\n      userAgent: row.clientUserAgent,\n      deviceType: row.clientDeviceType,\n      os: row.clientOs,\n      browser: row.clientBrowser,\n    },\n    issuedAt: row.issuedAt,\n    expiresAt: row.expiresAt,\n    lastConnectedAt: row.lastConnectedAt,\n    revokedAt: row.revokedAt,\n  };\n}\n\nfunction toPersistenceSqlOrDecodeError(\n  sqlOperation: string,\n  decodeOperation: string,\n  correlation?: PersistenceErrorCorrelation,\n) {\n  return (cause: unknown): AuthSessionRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)\n      : new PersistenceSqlError({\n          operation: sqlOperation,\n          ...(correlation === undefined ? {} : { correlation }),\n          cause,\n        });\n}\n\nexport const make = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const createSessionRow = SqlSchema.void({\n    Request: CreateAuthSessionInput,\n    execute: (input) =>\n      sql`\n        INSERT INTO auth_sessions (\n          session_id,\n          subject,\n          scopes,\n          method,\n          client_label,\n          client_ip_address,\n          client_user_agent,\n          client_device_type,\n          client_os,\n          client_browser,\n          issued_at,\n          expires_at,\n          revoked_at\n        )\n        VALUES (\n          ${input.sessionId},\n          ${input.subject},\n          ${JSON.stringify(input.scopes)},\n          ${input.method},\n          ${input.client.label},\n          ${input.client.ipAddress},\n          ${input.client.userAgent},\n          ${input.client.deviceType},\n          ${input.client.os},\n          ${input.client.browser},\n          ${input.issuedAt},\n          ${input.expiresAt},\n          NULL\n        )\n      `,\n  });\n\n  const getSessionRowById = SqlSchema.findOneOption({\n    Request: GetAuthSessionByIdInput,\n    Result: AuthSessionRawDbRow,\n    execute: ({ sessionId }) =>\n      sql`\n        SELECT\n          session_id AS \"sessionId\",\n          subject AS \"subject\",\n          scopes AS \"scopes\",\n          method AS \"method\",\n          client_label AS \"clientLabel\",\n          client_ip_address AS \"clientIpAddress\",\n          client_user_agent AS \"clientUserAgent\",\n          client_device_type AS \"clientDeviceType\",\n          client_os AS \"clientOs\",\n          client_browser AS \"clientBrowser\",\n          issued_at AS \"issuedAt\",\n          expires_at AS \"expiresAt\",\n          last_connected_at AS \"lastConnectedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_sessions\n        WHERE session_id = ${sessionId}\n      `,\n  });\n\n  const listActiveSessionRows = SqlSchema.findAll({\n    Request: ListActiveAuthSessionsInput,\n    Result: AuthSessionRawDbRow,\n    execute: ({ now }) =>\n      sql`\n        SELECT\n          session_id AS \"sessionId\",\n          subject AS \"subject\",\n          scopes AS \"scopes\",\n          method AS \"method\",\n          client_label AS \"clientLabel\",\n          client_ip_address AS \"clientIpAddress\",\n          client_user_agent AS \"clientUserAgent\",\n          client_device_type AS \"clientDeviceType\",\n          client_os AS \"clientOs\",\n          client_browser AS \"clientBrowser\",\n          issued_at AS \"issuedAt\",\n          expires_at AS \"expiresAt\",\n          last_connected_at AS \"lastConnectedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_sessions\n        WHERE revoked_at IS NULL\n          AND expires_at > ${now}\n        ORDER BY issued_at DESC, session_id DESC\n      `,\n  });\n\n  const setLastConnectedAtRow = SqlSchema.void({\n    Request: SetAuthSessionLastConnectedAtInput,\n    execute: ({ sessionId, lastConnectedAt }) =>\n      sql`\n        UPDATE auth_sessions\n        SET last_connected_at = ${lastConnectedAt}\n        WHERE session_id = ${sessionId}\n          AND revoked_at IS NULL\n      `,\n  });\n\n  const revokeSessionRows = SqlSchema.findAll({\n    Request: RevokeAuthSessionInput,\n    Result: Schema.Struct({ sessionId: AuthSessionId }),\n    execute: ({ sessionId, revokedAt }) =>\n      sql`\n        UPDATE auth_sessions\n        SET revoked_at = ${revokedAt}\n        WHERE session_id = ${sessionId}\n          AND revoked_at IS NULL\n        RETURNING session_id AS \"sessionId\"\n      `,\n  });\n\n  const revokeOtherSessionRows = SqlSchema.findAll({\n    Request: RevokeOtherAuthSessionsInput,\n    Result: Schema.Struct({ sessionId: AuthSessionId }),\n    execute: ({ currentSessionId, revokedAt }) =>\n      sql`\n        UPDATE auth_sessions\n        SET revoked_at = ${revokedAt}\n        WHERE session_id <> ${currentSessionId}\n          AND revoked_at IS NULL\n        RETURNING session_id AS \"sessionId\"\n      `,\n  });\n\n  const create: AuthSessionRepository[\"Service\"][\"create\"] = (input) =>\n    createSessionRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.create:query\",\n          \"AuthSessionRepository.create:encodeRequest\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n    );\n\n  const getById: AuthSessionRepository[\"Service\"][\"getById\"] = (input) =>\n    getSessionRowById(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.getById:query\",\n          \"AuthSessionRepository.getById:decodeRow\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeAuthSessionDbRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"AuthSessionRepository.getById:decodeRow\",\n                  cause,\n                  { sessionId: input.sessionId },\n                ),\n              ),\n              Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),\n            ),\n        }),\n      ),\n    );\n\n  const listActive: AuthSessionRepository[\"Service\"][\"listActive\"] = (input) =>\n    listActiveSessionRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.listActive:query\",\n          \"AuthSessionRepository.listActive:decodeRows\",\n        ),\n      ),\n      Effect.flatMap((rows) =>\n        Effect.forEach(rows, (row) =>\n          decodeAuthSessionDbRow(row).pipe(\n            Effect.mapError((cause) =>\n              PersistenceDecodeError.fromSchemaError(\n                \"AuthSessionRepository.listActive:decodeRows\",\n                cause,\n                { sessionId: row.sessionId },\n              ),\n            ),\n            Effect.map(toAuthSessionRecord),\n          ),\n        ),\n      ),\n    );\n\n  const revoke: AuthSessionRepository[\"Service\"][\"revoke\"] = (input) =>\n    revokeSessionRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.revoke:query\",\n          \"AuthSessionRepository.revoke:decodeRows\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n      Effect.map((rows) => rows.length > 0),\n    );\n\n  const revokeAllExcept: AuthSessionRepository[\"Service\"][\"revokeAllExcept\"] = (input) =>\n    revokeOtherSessionRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.revokeAllExcept:query\",\n          \"AuthSessionRepository.revokeAllExcept:decodeRows\",\n          { currentSessionId: input.currentSessionId },\n        ),\n      ),\n      Effect.map((rows) => rows.map((row) => row.sessionId)),\n    );\n\n  const setLastConnectedAt: AuthSessionRepository[\"Service\"][\"setLastConnectedAt\"] = (input) =>\n    setLastConnectedAtRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.setLastConnectedAt:query\",\n          \"AuthSessionRepository.setLastConnectedAt:encodeRequest\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n    );\n\n  return {\n    create,\n    getById,\n    listActive,\n    revoke,\n    revokeAllExcept,\n    setLastConnectedAt,\n  } satisfies AuthSessionRepository[\"Service\"];\n});\n\nexport const layer = Layer.effect(AuthSessionRepository, make);\n","import {\n  AuthSessionId,\n  AuthStandardClientScopes,\n  AuthEnvironmentScopes,\n  type AuthClientMetadata,\n  type AuthClientSession,\n  type AuthEnvironmentScope,\n  type ServerAuthSessionMethod,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Option from \"effect/Option\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as AuthSessions from \"../persistence/AuthSessions.ts\";\nimport * as ServerSecretStore from \"./ServerSecretStore.ts\";\nimport {\n  base64UrlDecodeUtf8,\n  base64UrlEncode,\n  resolveSessionCookieName,\n  signPayload,\n  timingSafeEqualBase64Url,\n} from \"./utils.ts\";\n\nexport interface IssuedSession {\n  readonly sessionId: AuthSessionId;\n  readonly token: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly client: AuthClientMetadata;\n  readonly expiresAt: DateTime.DateTime;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n}\n\nexport interface VerifiedSession {\n  readonly sessionId: AuthSessionId;\n  readonly token: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly client: AuthClientMetadata;\n  readonly expiresAt?: DateTime.DateTime;\n  readonly subject: string;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n}\n\nexport type SessionCredentialChange =\n  | {\n      readonly type: \"clientUpserted\";\n      readonly clientSession: AuthClientSession;\n    }\n  | {\n      readonly type: \"clientRemoved\";\n      readonly sessionId: AuthSessionId;\n    };\n\nexport class MalformedSessionTokenError extends Schema.TaggedErrorClass<MalformedSessionTokenError>()(\n  \"MalformedSessionTokenError\",\n  {},\n) {\n  override get message(): string {\n    return \"Malformed session token.\";\n  }\n}\n\nexport class InvalidSessionTokenSignatureError extends Schema.TaggedErrorClass<InvalidSessionTokenSignatureError>()(\n  \"InvalidSessionTokenSignatureError\",\n  {},\n) {\n  override get message(): string {\n    return \"Invalid session token signature.\";\n  }\n}\n\nexport class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<InvalidSessionTokenPayloadError>()(\n  \"InvalidSessionTokenPayloadError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Invalid session token payload.\";\n  }\n}\n\nexport class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(\n  \"SessionTokenExpiredError\",\n  {\n    sessionId: AuthSessionId,\n    expiresAt: Schema.DateTimeUtc,\n    observedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Session token expired.\";\n  }\n}\n\nexport class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(\n  \"UnknownSessionTokenError\",\n  {\n    sessionId: AuthSessionId,\n  },\n) {\n  override get message(): string {\n    return \"Unknown session token.\";\n  }\n}\n\nexport class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(\n  \"SessionTokenRevokedError\",\n  {\n    sessionId: AuthSessionId,\n    revokedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Session token revoked.\";\n  }\n}\n\nexport class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(\n  \"InvalidSessionExpirationClaimError\",\n  {\n    sessionId: AuthSessionId,\n    expirationClaim: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return \"Invalid `exp` claim\";\n  }\n}\n\nexport class MalformedWebSocketTokenError extends Schema.TaggedErrorClass<MalformedWebSocketTokenError>()(\n  \"MalformedWebSocketTokenError\",\n  {},\n) {\n  override get message(): string {\n    return \"Malformed websocket token.\";\n  }\n}\n\nexport class InvalidWebSocketTokenSignatureError extends Schema.TaggedErrorClass<InvalidWebSocketTokenSignatureError>()(\n  \"InvalidWebSocketTokenSignatureError\",\n  {},\n) {\n  override get message(): string {\n    return \"Invalid websocket token signature.\";\n  }\n}\n\nexport class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<InvalidWebSocketTokenPayloadError>()(\n  \"InvalidWebSocketTokenPayloadError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Invalid websocket token payload.\";\n  }\n}\n\nexport class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(\n  \"WebSocketTokenExpiredError\",\n  {\n    sessionId: AuthSessionId,\n    expiresAt: Schema.DateTimeUtc,\n    observedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Websocket token expired.\";\n  }\n}\n\nexport class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(\n  \"UnknownWebSocketSessionError\",\n  {\n    sessionId: AuthSessionId,\n  },\n) {\n  override get message(): string {\n    return \"Unknown websocket session.\";\n  }\n}\n\nexport class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(\n  \"WebSocketSessionExpiredError\",\n  {\n    sessionId: AuthSessionId,\n    expiresAt: Schema.DateTimeUtc,\n    observedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Websocket session expired.\";\n  }\n}\n\nexport class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(\n  \"WebSocketSessionRevokedError\",\n  {\n    sessionId: AuthSessionId,\n    revokedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Websocket session revoked.\";\n  }\n}\n\nexport const SessionCredentialInvalidError = Schema.Union([\n  MalformedSessionTokenError,\n  InvalidSessionTokenSignatureError,\n  InvalidSessionTokenPayloadError,\n  SessionTokenExpiredError,\n  UnknownSessionTokenError,\n  SessionTokenRevokedError,\n  InvalidSessionExpirationClaimError,\n  MalformedWebSocketTokenError,\n  InvalidWebSocketTokenSignatureError,\n  InvalidWebSocketTokenPayloadError,\n  WebSocketTokenExpiredError,\n  UnknownWebSocketSessionError,\n  WebSocketSessionExpiredError,\n  WebSocketSessionRevokedError,\n]);\nexport type SessionCredentialInvalidError = typeof SessionCredentialInvalidError.Type;\nexport const isSessionCredentialInvalidError = Schema.is(SessionCredentialInvalidError);\n\nconst sessionCredentialInternalErrorContext = {\n  cause: Schema.Defect(),\n};\n\nexport class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(\n  \"SessionClaimsEncodingError\",\n  {\n    sessionId: AuthSessionId,\n    operation: Schema.Literals([\"encode_session_claims\", \"encode_websocket_claims\"]),\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to encode claims\";\n  }\n}\n\nexport class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(\n  \"SessionCredentialIssueError\",\n  {\n    sessionId: Schema.optional(AuthSessionId),\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue session credential.\";\n  }\n}\n\nexport class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(\n  \"SessionCredentialVerificationError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to verify session credential.\";\n  }\n}\n\nexport class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(\n  \"WebSocketTokenIssueError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue websocket token.\";\n  }\n}\n\nexport class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(\n  \"WebSocketTokenVerificationError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to verify websocket token.\";\n  }\n}\n\nexport class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessionsListError>()(\n  \"ActiveSessionsListError\",\n  {\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to list active sessions.\";\n  }\n}\n\nexport class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(\n  \"SessionRevocationError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke session.\";\n  }\n}\n\nexport class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(\n  \"OtherSessionsRevocationError\",\n  {\n    currentSessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke other sessions.\";\n  }\n}\n\nexport const SessionCredentialInternalError = Schema.Union([\n  SessionClaimsEncodingError,\n  SessionCredentialIssueError,\n  SessionCredentialVerificationError,\n  WebSocketTokenIssueError,\n  WebSocketTokenVerificationError,\n  ActiveSessionsListError,\n  SessionRevocationError,\n  OtherSessionsRevocationError,\n]);\nexport type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type;\nexport const isSessionCredentialInternalError = Schema.is(SessionCredentialInternalError);\n\nexport const SessionCredentialError = Schema.Union([\n  SessionCredentialInvalidError,\n  SessionCredentialInternalError,\n]);\nexport type SessionCredentialError = typeof SessionCredentialError.Type;\nexport const isSessionCredentialError = Schema.is(SessionCredentialError);\n\nexport class SessionStore extends Context.Service<\n  SessionStore,\n  {\n    readonly cookieName: string;\n    readonly issue: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly subject?: string;\n      readonly method?: ServerAuthSessionMethod;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly client?: AuthClientMetadata;\n      readonly proofKeyThumbprint?: string;\n    }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;\n    readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;\n    readonly issueWebSocketToken: (\n      sessionId: AuthSessionId,\n      input?: {\n        readonly ttl?: Duration.Duration;\n      },\n    ) => Effect.Effect<\n      {\n        readonly token: string;\n        readonly expiresAt: DateTime.DateTime;\n      },\n      SessionCredentialInternalError\n    >;\n    readonly verifyWebSocketToken: (\n      token: string,\n    ) => Effect.Effect<VerifiedSession, SessionCredentialError>;\n    readonly listActive: () => Effect.Effect<\n      ReadonlyArray<AuthClientSession>,\n      SessionCredentialInternalError\n    >;\n    readonly streamChanges: Stream.Stream<SessionCredentialChange>;\n    readonly revoke: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<boolean, SessionCredentialInternalError>;\n    readonly revokeAllExcept: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<number, SessionCredentialInternalError>;\n    readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;\n    readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;\n  }\n>()(\"t3/auth/SessionStore\") {}\n\nconst SIGNING_SECRET_NAME = \"server-signing-key\";\nconst DEFAULT_SESSION_TTL = Duration.days(30);\nconst DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);\n\nconst SessionClaims = Schema.Struct({\n  v: Schema.Literal(1),\n  kind: Schema.Literal(\"session\"),\n  sid: AuthSessionId,\n  sub: Schema.String,\n  scopes: AuthEnvironmentScopes,\n  method: Schema.Literals([\"browser-session-cookie\", \"bearer-access-token\", \"dpop-access-token\"]),\n  jkt: Schema.optionalKey(Schema.String),\n  iat: Schema.Number,\n  exp: Schema.Number,\n});\ntype SessionClaims = typeof SessionClaims.Type;\n\nconst WebSocketClaims = Schema.Struct({\n  v: Schema.Literal(1),\n  kind: Schema.Literal(\"websocket\"),\n  sid: AuthSessionId,\n  iat: Schema.Number,\n  exp: Schema.Number,\n});\ntype WebSocketClaims = typeof WebSocketClaims.Type;\n\nconst decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));\nconst decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));\n\nfunction createDefaultClientMetadata(): AuthClientMetadata {\n  return {\n    deviceType: \"unknown\",\n  };\n}\n\nfunction toClientMetadata(record: {\n  readonly label: string | null;\n  readonly ipAddress: string | null;\n  readonly userAgent: string | null;\n  readonly deviceType: AuthClientMetadata[\"deviceType\"];\n  readonly os: string | null;\n  readonly browser: string | null;\n}): AuthClientMetadata {\n  return {\n    ...(record.label ? { label: record.label } : {}),\n    ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),\n    ...(record.userAgent ? { userAgent: record.userAgent } : {}),\n    deviceType: record.deviceType,\n    ...(record.os ? { os: record.os } : {}),\n    ...(record.browser ? { browser: record.browser } : {}),\n  };\n}\n\nfunction toAuthClientSession(input: Omit<AuthClientSession, \"current\">): AuthClientSession {\n  return {\n    ...input,\n    current: false,\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const authSessions = yield* AuthSessions.AuthSessionRepository;\n  const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);\n  const connectedSessionsRef = yield* Ref.make(new Map<string, number>());\n  const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();\n  const cookieName = resolveSessionCookieName({\n    mode: serverConfig.mode,\n    port: serverConfig.port,\n    host: serverConfig.host,\n    instanceKey: serverConfig.stateDir,\n    development: serverConfig.devUrl !== undefined,\n  });\n\n  const emitUpsert = (clientSession: AuthClientSession) =>\n    PubSub.publish(changesPubSub, {\n      type: \"clientUpserted\",\n      clientSession,\n    }).pipe(Effect.asVoid);\n\n  const emitRemoved = (sessionId: AuthSessionId) =>\n    PubSub.publish(changesPubSub, {\n      type: \"clientRemoved\",\n      sessionId,\n    }).pipe(Effect.asVoid);\n\n  const loadActiveSession = (sessionId: AuthSessionId) =>\n    Effect.gen(function* () {\n      const row = yield* authSessions.getById({ sessionId });\n      if (Option.isNone(row) || row.value.revokedAt !== null) {\n        return Option.none<AuthClientSession>();\n      }\n\n      const connectedSessions = yield* Ref.get(connectedSessionsRef);\n      return Option.some(\n        toAuthClientSession({\n          sessionId: row.value.sessionId,\n          subject: row.value.subject,\n          scopes: row.value.scopes,\n          method: row.value.method,\n          client: toClientMetadata(row.value.client),\n          issuedAt: row.value.issuedAt,\n          expiresAt: row.value.expiresAt,\n          lastConnectedAt: row.value.lastConnectedAt,\n          connected: connectedSessions.has(row.value.sessionId),\n        }),\n      );\n    });\n\n  const markConnected: SessionStore[\"Service\"][\"markConnected\"] = (sessionId) =>\n    Ref.modify(connectedSessionsRef, (current) => {\n      const next = new Map(current);\n      const wasDisconnected = !next.has(sessionId);\n      next.set(sessionId, (next.get(sessionId) ?? 0) + 1);\n      return [wasDisconnected, next] as const;\n    }).pipe(\n      Effect.flatMap((wasDisconnected) =>\n        wasDisconnected\n          ? DateTime.now.pipe(\n              Effect.flatMap((lastConnectedAt) =>\n                authSessions.setLastConnectedAt({\n                  sessionId,\n                  lastConnectedAt,\n                }),\n              ),\n            )\n          : Effect.void,\n      ),\n      Effect.flatMap(() => loadActiveSession(sessionId)),\n      Effect.flatMap((session) =>\n        Option.isSome(session) ? emitUpsert(session.value) : Effect.void,\n      ),\n      Effect.catchCause((cause) =>\n        Effect.logError(\"Failed to publish connected-session auth update.\").pipe(\n          Effect.annotateLogs({\n            sessionId,\n            cause,\n          }),\n        ),\n      ),\n      Effect.withSpan(\"SessionStore.markConnected\"),\n    );\n\n  const markDisconnected: SessionStore[\"Service\"][\"markDisconnected\"] = (sessionId) =>\n    Ref.update(connectedSessionsRef, (current) => {\n      const next = new Map(current);\n      const remaining = (next.get(sessionId) ?? 0) - 1;\n      if (remaining > 0) {\n        next.set(sessionId, remaining);\n      } else {\n        next.delete(sessionId);\n      }\n      return next;\n    }).pipe(\n      Effect.flatMap(() => loadActiveSession(sessionId)),\n      Effect.flatMap((session) =>\n        Option.isSome(session) ? emitUpsert(session.value) : Effect.void,\n      ),\n      Effect.catchCause((cause) =>\n        Effect.logError(\"Failed to publish disconnected-session auth update.\").pipe(\n          Effect.annotateLogs({\n            sessionId,\n            cause,\n          }),\n        ),\n      ),\n      Effect.withSpan(\"SessionStore.markDisconnected\"),\n    );\n\n  const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));\n  const issue: SessionStore[\"Service\"][\"issue\"] = Effect.fn(\"SessionStore.issue\")(\n    function* (input) {\n      const sessionId = AuthSessionId.make(\n        yield* crypto.randomUUIDv4.pipe(\n          Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),\n        ),\n      );\n      const issuedAt = yield* DateTime.now;\n      const expiresAt = DateTime.add(issuedAt, {\n        milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),\n      });\n      const claims: SessionClaims = {\n        v: 1,\n        kind: \"session\",\n        sid: sessionId,\n        sub: input?.subject ?? \"browser\",\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        method: input?.method ?? \"browser-session-cookie\",\n        ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),\n        iat: issuedAt.epochMilliseconds,\n        exp: expiresAt.epochMilliseconds,\n      };\n\n      const encodedPayload = yield* encodeClaims(claims).pipe(\n        Effect.map(base64UrlEncode),\n        Effect.mapError(\n          (cause) =>\n            new SessionCredentialIssueError({\n              sessionId,\n              cause: new SessionClaimsEncodingError({\n                sessionId,\n                operation: \"encode_session_claims\",\n                cause,\n              }),\n            }),\n        ),\n      );\n      const signature = signPayload(encodedPayload, signingSecret);\n      const client = input?.client ?? createDefaultClientMetadata();\n      yield* authSessions\n        .create({\n          sessionId,\n          subject: claims.sub,\n          scopes: claims.scopes,\n          method: claims.method,\n          client: {\n            label: client.label ?? null,\n            ipAddress: client.ipAddress ?? null,\n            userAgent: client.userAgent ?? null,\n            deviceType: client.deviceType,\n            os: client.os ?? null,\n            browser: client.browser ?? null,\n          },\n          issuedAt,\n          expiresAt,\n        })\n        .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));\n      yield* emitUpsert(\n        toAuthClientSession({\n          sessionId,\n          subject: claims.sub,\n          scopes: claims.scopes,\n          method: claims.method,\n          client,\n          issuedAt,\n          expiresAt,\n          lastConnectedAt: null,\n          connected: false,\n        }),\n      );\n\n      return {\n        sessionId,\n        token: `${encodedPayload}.${signature}`,\n        method: claims.method,\n        client,\n        expiresAt: expiresAt,\n        scopes: claims.scopes,\n        ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),\n      } satisfies IssuedSession;\n    },\n  );\n\n  const verify: SessionStore[\"Service\"][\"verify\"] = Effect.fn(\"SessionStore.verify\")(\n    function* (token) {\n      const [encodedPayload, signature] = token.split(\".\");\n      if (!encodedPayload || !signature) {\n        return yield* new MalformedSessionTokenError({});\n      }\n\n      const expectedSignature = signPayload(encodedPayload, signingSecret);\n      if (!timingSafeEqualBase64Url(signature, expectedSignature)) {\n        return yield* new InvalidSessionTokenSignatureError({});\n      }\n\n      const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(\n        Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),\n      );\n\n      const observedAt = yield* DateTime.now;\n      const expiresAt = DateTime.make(claims.exp);\n      if (Option.isNone(expiresAt)) {\n        return yield* new InvalidSessionExpirationClaimError({\n          sessionId: claims.sid,\n          expirationClaim: claims.exp,\n        });\n      }\n      if (claims.exp <= observedAt.epochMilliseconds) {\n        return yield* new SessionTokenExpiredError({\n          sessionId: claims.sid,\n          expiresAt: expiresAt.value,\n          observedAt,\n        });\n      }\n\n      const row = yield* authSessions\n        .getById({ sessionId: claims.sid })\n        .pipe(\n          Effect.mapError(\n            (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),\n          ),\n        );\n      if (Option.isNone(row)) {\n        return yield* new UnknownSessionTokenError({ sessionId: claims.sid });\n      }\n      if (row.value.revokedAt !== null) {\n        return yield* new SessionTokenRevokedError({\n          sessionId: claims.sid,\n          revokedAt: row.value.revokedAt,\n        });\n      }\n\n      return {\n        sessionId: claims.sid,\n        token,\n        method: claims.method,\n        client: toClientMetadata(row.value.client),\n        expiresAt: expiresAt.value,\n        subject: claims.sub,\n        scopes: claims.scopes,\n        ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),\n      } satisfies VerifiedSession;\n    },\n  );\n\n  const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));\n  const issueWebSocketToken: SessionStore[\"Service\"][\"issueWebSocketToken\"] = Effect.fn(\n    \"SessionStore.issueWebSocketToken\",\n  )(function* (sessionId, input) {\n    const issuedAt = yield* DateTime.now;\n    const expiresAt = DateTime.add(issuedAt, {\n      milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),\n    });\n    const claims: WebSocketClaims = {\n      v: 1,\n      kind: \"websocket\",\n      sid: sessionId,\n      iat: issuedAt.epochMilliseconds,\n      exp: expiresAt.epochMilliseconds,\n    };\n    const encodedPayload = yield* encodeWsClaims(claims).pipe(\n      Effect.map(base64UrlEncode),\n      Effect.mapError(\n        (cause) =>\n          new WebSocketTokenIssueError({\n            sessionId,\n            cause: new SessionClaimsEncodingError({\n              sessionId,\n              operation: \"encode_websocket_claims\",\n              cause,\n            }),\n          }),\n      ),\n    );\n    const signature = signPayload(encodedPayload, signingSecret);\n    return {\n      token: `${encodedPayload}.${signature}`,\n      expiresAt,\n    };\n  });\n\n  const verifyWebSocketToken: SessionStore[\"Service\"][\"verifyWebSocketToken\"] = Effect.fn(\n    \"SessionStore.verifyWebSocketToken\",\n  )(function* (token) {\n    const [encodedPayload, signature] = token.split(\".\");\n    if (!encodedPayload || !signature) {\n      return yield* new MalformedWebSocketTokenError({});\n    }\n\n    const expectedSignature = signPayload(encodedPayload, signingSecret);\n    if (!timingSafeEqualBase64Url(signature, expectedSignature)) {\n      return yield* new InvalidWebSocketTokenSignatureError({});\n    }\n\n    const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(\n      Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),\n    );\n\n    const observedAt = yield* DateTime.now;\n    const expiresAt = DateTime.make(claims.exp);\n    if (Option.isNone(expiresAt)) {\n      return yield* new InvalidSessionExpirationClaimError({\n        sessionId: claims.sid,\n        expirationClaim: claims.exp,\n      });\n    }\n    if (claims.exp <= observedAt.epochMilliseconds) {\n      return yield* new WebSocketTokenExpiredError({\n        sessionId: claims.sid,\n        expiresAt: expiresAt.value,\n        observedAt,\n      });\n    }\n\n    const row = yield* authSessions\n      .getById({ sessionId: claims.sid })\n      .pipe(\n        Effect.mapError(\n          (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),\n        ),\n      );\n    if (Option.isNone(row)) {\n      return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });\n    }\n    if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {\n      return yield* new WebSocketSessionExpiredError({\n        sessionId: claims.sid,\n        expiresAt: row.value.expiresAt,\n        observedAt,\n      });\n    }\n    if (row.value.revokedAt !== null) {\n      return yield* new WebSocketSessionRevokedError({\n        sessionId: claims.sid,\n        revokedAt: row.value.revokedAt,\n      });\n    }\n\n    return {\n      sessionId: row.value.sessionId,\n      token,\n      method: row.value.method,\n      client: toClientMetadata(row.value.client),\n      expiresAt: row.value.expiresAt,\n      subject: row.value.subject,\n      scopes: row.value.scopes,\n    } satisfies VerifiedSession;\n  });\n\n  const listActive: SessionStore[\"Service\"][\"listActive\"] = Effect.fn(\"SessionStore.listActive\")(\n    function* () {\n      const now = yield* DateTime.now;\n      const connectedSessions = yield* Ref.get(connectedSessionsRef);\n      const rows = yield* authSessions.listActive({ now });\n\n      return rows.map((row) =>\n        toAuthClientSession({\n          sessionId: row.sessionId,\n          subject: row.subject,\n          scopes: row.scopes,\n          method: row.method,\n          client: toClientMetadata(row.client),\n          issuedAt: row.issuedAt,\n          expiresAt: row.expiresAt,\n          lastConnectedAt: row.lastConnectedAt,\n          connected: connectedSessions.has(row.sessionId),\n        }),\n      );\n    },\n    Effect.mapError((cause) => new ActiveSessionsListError({ cause })),\n  );\n\n  const revoke: SessionStore[\"Service\"][\"revoke\"] = Effect.fn(\"SessionStore.revoke\")(\n    function* (sessionId) {\n      const revokedAt = yield* DateTime.now;\n      const revoked = yield* authSessions\n        .revoke({\n          sessionId,\n          revokedAt,\n        })\n        .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));\n      if (revoked) {\n        yield* Ref.update(connectedSessionsRef, (current) => {\n          const next = new Map(current);\n          next.delete(sessionId);\n          return next;\n        });\n        yield* emitRemoved(sessionId);\n      }\n      return revoked;\n    },\n  );\n\n  const revokeAllExcept: SessionStore[\"Service\"][\"revokeAllExcept\"] = Effect.fn(\n    \"SessionStore.revokeAllExcept\",\n  )(function* (sessionId) {\n    const revokedAt = yield* DateTime.now;\n    const revokedSessionIds = yield* authSessions\n      .revokeAllExcept({\n        currentSessionId: sessionId,\n        revokedAt,\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),\n        ),\n      );\n    if (revokedSessionIds.length > 0) {\n      yield* Ref.update(connectedSessionsRef, (current) => {\n        const next = new Map(current);\n        for (const revokedSessionId of revokedSessionIds) {\n          next.delete(revokedSessionId);\n        }\n        return next;\n      });\n      yield* Effect.forEach(\n        revokedSessionIds,\n        (revokedSessionId) => emitRemoved(revokedSessionId),\n        {\n          concurrency: \"unbounded\",\n          discard: true,\n        },\n      );\n    }\n    return revokedSessionIds.length;\n  });\n\n  return SessionStore.of({\n    cookieName,\n    issue,\n    verify,\n    issueWebSocketToken,\n    verifyWebSocketToken,\n    listActive,\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n    revoke,\n    revokeAllExcept,\n    markConnected,\n    markDisconnected,\n  });\n});\n\nexport const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));\n","/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc\n    ? nc.webcrypto\n    : nc && typeof nc === 'object' && 'randomBytes' in nc\n        ? nc\n        : undefined;\n//# sourceMappingURL=cryptoNode.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n    if (!Number.isSafeInteger(n) || n < 0)\n        throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n    if (!isBytes(b))\n        throw new Error('Uint8Array expected');\n    if (lengths.length > 0 && !lengths.includes(b.length))\n        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n    if (typeof h !== 'function' || typeof h.create !== 'function')\n        throw new Error('Hash should be wrapped by utils.createHasher');\n    anumber(h.outputLen);\n    anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n    if (instance.destroyed)\n        throw new Error('Hash instance has been destroyed');\n    if (checkFinished && instance.finished)\n        throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n    abytes(out);\n    const min = instance.outputLen;\n    if (out.length < min) {\n        throw new Error('digestInto() expects output buffer of length at least ' + min);\n    }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n    for (let i = 0; i < arrays.length; i++) {\n        arrays[i].fill(0);\n    }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n    return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n    return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n    return (((word << 24) & 0xff000000) |\n        ((word << 8) & 0xff0000) |\n        ((word >>> 8) & 0xff00) |\n        ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n    ? (n) => n\n    : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = byteSwap(arr[i]);\n    }\n    return arr;\n}\nexport const swap32IfBE = isLE\n    ? (u) => u\n    : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n    if (ch >= asciis._0 && ch <= asciis._9)\n        return ch - asciis._0; // '2' => 50-48\n    if (ch >= asciis.A && ch <= asciis.F)\n        return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n    if (ch >= asciis.a && ch <= asciis.f)\n        return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n    return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new Error('hex string expected, got ' + typeof hex);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return Uint8Array.fromHex(hex);\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new Error('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi));\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n    }\n    return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n    let ts = Date.now();\n    for (let i = 0; i < iters; i++) {\n        cb(i);\n        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n        const diff = Date.now() - ts;\n        if (diff >= 0 && diff < tick)\n            continue;\n        await nextTick();\n        ts += diff;\n    }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new Error('string expected');\n    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n    return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n    if (typeof data === 'string')\n        data = utf8ToBytes(data);\n    abytes(data);\n    return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n    if (typeof data === 'string')\n        data = utf8ToBytes(data);\n    abytes(data);\n    return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\nexport function checkOpts(defaults, opts) {\n    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n        throw new Error('options should be object or undefined');\n    const merged = Object.assign(defaults, opts);\n    return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n    const tmp = hashCons();\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = () => hashCons();\n    return hashC;\n}\nexport function createOptHasher(hashCons) {\n    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n    const tmp = hashCons({});\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = (opts) => hashCons(opts);\n    return hashC;\n}\nexport function createXOFer(hashCons) {\n    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n    const tmp = hashCons({});\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = (opts) => hashCons(opts);\n    return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n    if (crypto && typeof crypto.getRandomValues === 'function') {\n        return crypto.getRandomValues(new Uint8Array(bytesLength));\n    }\n    // Legacy Node.js compatibility\n    if (crypto && typeof crypto.randomBytes === 'function') {\n        return Uint8Array.from(crypto.randomBytes(bytesLength));\n    }\n    throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n    if (typeof view.setBigUint64 === 'function')\n        return view.setBigUint64(byteOffset, value, isLE);\n    const _32n = BigInt(32);\n    const _u32_max = BigInt(0xffffffff);\n    const wh = Number((value >> _32n) & _u32_max);\n    const wl = Number(value & _u32_max);\n    const h = isLE ? 4 : 0;\n    const l = isLE ? 0 : 4;\n    view.setUint32(byteOffset + h, wh, isLE);\n    view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n    return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n    return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n    constructor(blockLen, outputLen, padOffset, isLE) {\n        super();\n        this.finished = false;\n        this.length = 0;\n        this.pos = 0;\n        this.destroyed = false;\n        this.blockLen = blockLen;\n        this.outputLen = outputLen;\n        this.padOffset = padOffset;\n        this.isLE = isLE;\n        this.buffer = new Uint8Array(blockLen);\n        this.view = createView(this.buffer);\n    }\n    update(data) {\n        aexists(this);\n        data = toBytes(data);\n        abytes(data);\n        const { view, buffer, blockLen } = this;\n        const len = data.length;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            // Fast path: we have at least one block in input, cast it to view and process\n            if (take === blockLen) {\n                const dataView = createView(data);\n                for (; blockLen <= len - pos; pos += blockLen)\n                    this.process(dataView, pos);\n                continue;\n            }\n            buffer.set(data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            pos += take;\n            if (this.pos === blockLen) {\n                this.process(view, 0);\n                this.pos = 0;\n            }\n        }\n        this.length += data.length;\n        this.roundClean();\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        // Padding\n        // We can avoid allocation of buffer for padding completely if it\n        // was previously not allocated here. But it won't change performance.\n        const { buffer, view, blockLen, isLE } = this;\n        let { pos } = this;\n        // append the bit '1' to the message\n        buffer[pos++] = 0b10000000;\n        clean(this.buffer.subarray(pos));\n        // we have less than padOffset left in buffer, so we cannot put length in\n        // current block, need process it and pad again\n        if (this.padOffset > blockLen - pos) {\n            this.process(view, 0);\n            pos = 0;\n        }\n        // Pad until full block byte with zeros\n        for (let i = pos; i < blockLen; i++)\n            buffer[i] = 0;\n        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n        // So we just write lowest 64 bits of that value.\n        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n        this.process(view, 0);\n        const oview = createView(out);\n        const len = this.outputLen;\n        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n        if (len % 4)\n            throw new Error('_sha2: outputLen should be aligned to 32bit');\n        const outLen = len / 4;\n        const state = this.get();\n        if (outLen > state.length)\n            throw new Error('_sha2: outputLen bigger than state');\n        for (let i = 0; i < outLen; i++)\n            oview.setUint32(4 * i, state[i], isLE);\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n    _cloneInto(to) {\n        to || (to = new this.constructor());\n        to.set(...this.get());\n        const { blockLen, buffer, length, finished, destroyed, pos } = this;\n        to.destroyed = destroyed;\n        to.finished = finished;\n        to.length = length;\n        to.pos = pos;\n        if (length % blockLen)\n            to.buffer.set(buffer);\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n    if (le)\n        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n    const len = lst.length;\n    let Ah = new Uint32Array(len);\n    let Al = new Uint32Array(len);\n    for (let i = 0; i < len; i++) {\n        const { h, l } = fromBig(lst[i], le);\n        [Ah[i], Al[i]] = [h, l];\n    }\n    return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n    const l = (Al >>> 0) + (Bl >>> 0);\n    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n    fromBig, split, toBig,\n    shrSH, shrSL,\n    rotrSH, rotrSL, rotrBH, rotrBL,\n    rotr32H, rotr32L,\n    rotlSH, rotlSL, rotlBH, rotlBL,\n    add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n    constructor(outputLen = 32) {\n        super(64, outputLen, 8, false);\n        // We cannot use array here since array allows indexing by variable\n        // which means optimizer/compiler cannot use registers.\n        this.A = SHA256_IV[0] | 0;\n        this.B = SHA256_IV[1] | 0;\n        this.C = SHA256_IV[2] | 0;\n        this.D = SHA256_IV[3] | 0;\n        this.E = SHA256_IV[4] | 0;\n        this.F = SHA256_IV[5] | 0;\n        this.G = SHA256_IV[6] | 0;\n        this.H = SHA256_IV[7] | 0;\n    }\n    get() {\n        const { A, B, C, D, E, F, G, H } = this;\n        return [A, B, C, D, E, F, G, H];\n    }\n    // prettier-ignore\n    set(A, B, C, D, E, F, G, H) {\n        this.A = A | 0;\n        this.B = B | 0;\n        this.C = C | 0;\n        this.D = D | 0;\n        this.E = E | 0;\n        this.F = F | 0;\n        this.G = G | 0;\n        this.H = H | 0;\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4)\n            SHA256_W[i] = view.getUint32(offset, false);\n        for (let i = 16; i < 64; i++) {\n            const W15 = SHA256_W[i - 15];\n            const W2 = SHA256_W[i - 2];\n            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n        }\n        // Compression function main loop, 64 rounds\n        let { A, B, C, D, E, F, G, H } = this;\n        for (let i = 0; i < 64; i++) {\n            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n            const T2 = (sigma0 + Maj(A, B, C)) | 0;\n            H = G;\n            G = F;\n            F = E;\n            E = (D + T1) | 0;\n            D = C;\n            C = B;\n            B = A;\n            A = (T1 + T2) | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        A = (A + this.A) | 0;\n        B = (B + this.B) | 0;\n        C = (C + this.C) | 0;\n        D = (D + this.D) | 0;\n        E = (E + this.E) | 0;\n        F = (F + this.F) | 0;\n        G = (G + this.G) | 0;\n        H = (H + this.H) | 0;\n        this.set(A, B, C, D, E, F, G, H);\n    }\n    roundClean() {\n        clean(SHA256_W);\n    }\n    destroy() {\n        this.set(0, 0, 0, 0, 0, 0, 0, 0);\n        clean(this.buffer);\n    }\n}\nexport class SHA224 extends SHA256 {\n    constructor() {\n        super(28);\n        this.A = SHA224_IV[0] | 0;\n        this.B = SHA224_IV[1] | 0;\n        this.C = SHA224_IV[2] | 0;\n        this.D = SHA224_IV[3] | 0;\n        this.E = SHA224_IV[4] | 0;\n        this.F = SHA224_IV[5] | 0;\n        this.G = SHA224_IV[6] | 0;\n        this.H = SHA224_IV[7] | 0;\n    }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n    constructor(outputLen = 64) {\n        super(128, outputLen, 16, false);\n        // We cannot use array here since array allows indexing by variable\n        // which means optimizer/compiler cannot use registers.\n        // h -- high 32 bits, l -- low 32 bits\n        this.Ah = SHA512_IV[0] | 0;\n        this.Al = SHA512_IV[1] | 0;\n        this.Bh = SHA512_IV[2] | 0;\n        this.Bl = SHA512_IV[3] | 0;\n        this.Ch = SHA512_IV[4] | 0;\n        this.Cl = SHA512_IV[5] | 0;\n        this.Dh = SHA512_IV[6] | 0;\n        this.Dl = SHA512_IV[7] | 0;\n        this.Eh = SHA512_IV[8] | 0;\n        this.El = SHA512_IV[9] | 0;\n        this.Fh = SHA512_IV[10] | 0;\n        this.Fl = SHA512_IV[11] | 0;\n        this.Gh = SHA512_IV[12] | 0;\n        this.Gl = SHA512_IV[13] | 0;\n        this.Hh = SHA512_IV[14] | 0;\n        this.Hl = SHA512_IV[15] | 0;\n    }\n    // prettier-ignore\n    get() {\n        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n    }\n    // prettier-ignore\n    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n        this.Ah = Ah | 0;\n        this.Al = Al | 0;\n        this.Bh = Bh | 0;\n        this.Bl = Bl | 0;\n        this.Ch = Ch | 0;\n        this.Cl = Cl | 0;\n        this.Dh = Dh | 0;\n        this.Dl = Dl | 0;\n        this.Eh = Eh | 0;\n        this.El = El | 0;\n        this.Fh = Fh | 0;\n        this.Fl = Fl | 0;\n        this.Gh = Gh | 0;\n        this.Gl = Gl | 0;\n        this.Hh = Hh | 0;\n        this.Hl = Hl | 0;\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4) {\n            SHA512_W_H[i] = view.getUint32(offset);\n            SHA512_W_L[i] = view.getUint32((offset += 4));\n        }\n        for (let i = 16; i < 80; i++) {\n            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n            const W15h = SHA512_W_H[i - 15] | 0;\n            const W15l = SHA512_W_L[i - 15] | 0;\n            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n            const W2h = SHA512_W_H[i - 2] | 0;\n            const W2l = SHA512_W_L[i - 2] | 0;\n            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n            SHA512_W_H[i] = SUMh | 0;\n            SHA512_W_L[i] = SUMl | 0;\n        }\n        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        // Compression function main loop, 80 rounds\n        for (let i = 0; i < 80; i++) {\n            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n            const CHIl = (El & Fl) ^ (~El & Gl);\n            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n            // prettier-ignore\n            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n            const T1l = T1ll | 0;\n            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n            Hh = Gh | 0;\n            Hl = Gl | 0;\n            Gh = Fh | 0;\n            Gl = Fl | 0;\n            Fh = Eh | 0;\n            Fl = El | 0;\n            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n            Dh = Ch | 0;\n            Dl = Cl | 0;\n            Ch = Bh | 0;\n            Cl = Bl | 0;\n            Bh = Ah | 0;\n            Bl = Al | 0;\n            const All = u64.add3L(T1l, sigma0l, MAJl);\n            Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n            Al = All | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n    }\n    roundClean() {\n        clean(SHA512_W_H, SHA512_W_L);\n    }\n    destroy() {\n        clean(this.buffer);\n        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n    }\n}\nexport class SHA384 extends SHA512 {\n    constructor() {\n        super(48);\n        this.Ah = SHA384_IV[0] | 0;\n        this.Al = SHA384_IV[1] | 0;\n        this.Bh = SHA384_IV[2] | 0;\n        this.Bl = SHA384_IV[3] | 0;\n        this.Ch = SHA384_IV[4] | 0;\n        this.Cl = SHA384_IV[5] | 0;\n        this.Dh = SHA384_IV[6] | 0;\n        this.Dl = SHA384_IV[7] | 0;\n        this.Eh = SHA384_IV[8] | 0;\n        this.El = SHA384_IV[9] | 0;\n        this.Fh = SHA384_IV[10] | 0;\n        this.Fl = SHA384_IV[11] | 0;\n        this.Gh = SHA384_IV[12] | 0;\n        this.Gl = SHA384_IV[13] | 0;\n        this.Hh = SHA384_IV[14] | 0;\n        this.Hl = SHA384_IV[15] | 0;\n    }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n    constructor() {\n        super(28);\n        this.Ah = T224_IV[0] | 0;\n        this.Al = T224_IV[1] | 0;\n        this.Bh = T224_IV[2] | 0;\n        this.Bl = T224_IV[3] | 0;\n        this.Ch = T224_IV[4] | 0;\n        this.Cl = T224_IV[5] | 0;\n        this.Dh = T224_IV[6] | 0;\n        this.Dl = T224_IV[7] | 0;\n        this.Eh = T224_IV[8] | 0;\n        this.El = T224_IV[9] | 0;\n        this.Fh = T224_IV[10] | 0;\n        this.Fl = T224_IV[11] | 0;\n        this.Gh = T224_IV[12] | 0;\n        this.Gl = T224_IV[13] | 0;\n        this.Hh = T224_IV[14] | 0;\n        this.Hl = T224_IV[15] | 0;\n    }\n}\nexport class SHA512_256 extends SHA512 {\n    constructor() {\n        super(32);\n        this.Ah = T256_IV[0] | 0;\n        this.Al = T256_IV[1] | 0;\n        this.Bh = T256_IV[2] | 0;\n        this.Bl = T256_IV[3] | 0;\n        this.Ch = T256_IV[4] | 0;\n        this.Cl = T256_IV[5] | 0;\n        this.Dh = T256_IV[6] | 0;\n        this.Dl = T256_IV[7] | 0;\n        this.Eh = T256_IV[8] | 0;\n        this.El = T256_IV[9] | 0;\n        this.Fh = T256_IV[10] | 0;\n        this.Fl = T256_IV[11] | 0;\n        this.Gh = T256_IV[12] | 0;\n        this.Gl = T256_IV[13] | 0;\n        this.Hh = T256_IV[14] | 0;\n        this.Hl = T256_IV[15] | 0;\n    }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n    constructor(hash, _key) {\n        super();\n        this.finished = false;\n        this.destroyed = false;\n        ahash(hash);\n        const key = toBytes(_key);\n        this.iHash = hash.create();\n        if (typeof this.iHash.update !== 'function')\n            throw new Error('Expected instance of class which extends utils.Hash');\n        this.blockLen = this.iHash.blockLen;\n        this.outputLen = this.iHash.outputLen;\n        const blockLen = this.blockLen;\n        const pad = new Uint8Array(blockLen);\n        // blockLen can be bigger than outputLen\n        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36;\n        this.iHash.update(pad);\n        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n        this.oHash = hash.create();\n        // Undo internal XOR && apply outer XOR\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36 ^ 0x5c;\n        this.oHash.update(pad);\n        clean(pad);\n    }\n    update(buf) {\n        aexists(this);\n        this.iHash.update(buf);\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        abytes(out, this.outputLen);\n        this.finished = true;\n        this.iHash.digestInto(out);\n        this.oHash.update(out);\n        this.oHash.digestInto(out);\n        this.destroy();\n    }\n    digest() {\n        const out = new Uint8Array(this.oHash.outputLen);\n        this.digestInto(out);\n        return out;\n    }\n    _cloneInto(to) {\n        // Create new instance without calling constructor since key already in state and we don't know it.\n        to || (to = Object.create(Object.getPrototypeOf(this), {}));\n        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n        to = to;\n        to.finished = finished;\n        to.destroyed = destroyed;\n        to.blockLen = blockLen;\n        to.outputLen = outputLen;\n        to.oHash = oHash._cloneInto(to.oHash);\n        to.iHash = iHash._cloneInto(to.iHash);\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n    destroy() {\n        this.destroyed = true;\n        this.oHash.destroy();\n        this.iHash.destroy();\n    }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function isBytes(a) {\n    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nexport function abytes(item) {\n    if (!isBytes(item))\n        throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n    if (typeof value !== 'boolean')\n        throw new Error(title + ' boolean expected, got ' + value);\n}\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num) {\n    const hex = num.toString(16);\n    return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n    if (typeof hex !== 'string')\n        throw new Error('hex string expected, got ' + typeof hex);\n    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n    if (ch >= asciis._0 && ch <= asciis._9)\n        return ch - asciis._0; // '2' => 50-48\n    if (ch >= asciis.A && ch <= asciis.F)\n        return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n    if (ch >= asciis.a && ch <= asciis.f)\n        return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n    return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new Error('hex string expected, got ' + typeof hex);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return Uint8Array.fromHex(hex);\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new Error('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi));\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n    }\n    return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n    return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n    abytes(bytes);\n    return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n    return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n    return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n    return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n    let res;\n    if (typeof hex === 'string') {\n        try {\n            res = hexToBytes(hex);\n        }\n        catch (e) {\n            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n        }\n    }\n    else if (isBytes(hex)) {\n        // Uint8Array.from() instead of hash.slice() because node.js Buffer\n        // is instance of Uint8Array, and its slice() creates **mutable** copy\n        res = Uint8Array.from(hex);\n    }\n    else {\n        throw new Error(title + ' must be hex string or Uint8Array');\n    }\n    const len = res.length;\n    if (typeof expectedLength === 'number' && len !== expectedLength)\n        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n    return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n    if (a.length !== b.length)\n        return false;\n    let diff = 0;\n    for (let i = 0; i < a.length; i++)\n        diff |= a[i] ^ b[i];\n    return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new Error('string expected');\n    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n    // consider P=256n, min=0n, max=P\n    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`\n    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`\n    // - our way is the cleanest:               `inRange('x', x, 0n, P)\n    if (!inRange(n, min, max))\n        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n    let len;\n    for (len = 0; n > _0n; n >>= _1n, len += 1)\n        ;\n    return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n    return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n    return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n// DRBG\nconst u8n = (len) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n *   const drbg = createHmacDRBG<Key>(32, 32, hmac);\n *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n    if (typeof hashLen !== 'number' || hashLen < 2)\n        throw new Error('hashLen must be a number');\n    if (typeof qByteLen !== 'number' || qByteLen < 2)\n        throw new Error('qByteLen must be a number');\n    if (typeof hmacFn !== 'function')\n        throw new Error('hmacFn must be a function');\n    // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n    let i = 0; // Iterations counter, will throw when over 1000\n    const reset = () => {\n        v.fill(1);\n        k.fill(0);\n        i = 0;\n    };\n    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n    const reseed = (seed = u8n(0)) => {\n        // HMAC-DRBG reseed() function. Steps D-G\n        k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n        v = h(); // v = hmac(k || v)\n        if (seed.length === 0)\n            return;\n        k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n        v = h(); // v = hmac(k || v)\n    };\n    const gen = () => {\n        // HMAC-DRBG generate() function\n        if (i++ >= 1000)\n            throw new Error('drbg: tried 1000 values');\n        let len = 0;\n        const out = [];\n        while (len < qByteLen) {\n            v = h();\n            const sl = v.slice();\n            out.push(sl);\n            len += v.length;\n        }\n        return concatBytes(...out);\n    };\n    const genUntil = (seed, pred) => {\n        reset();\n        reseed(seed); // Steps D-G\n        let res = undefined; // Step H: grind until k is in [1..n-1]\n        while (!(res = pred(gen())))\n            reseed();\n        reset();\n        return res;\n    };\n    return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n    bigint: (val) => typeof val === 'bigint',\n    function: (val) => typeof val === 'function',\n    boolean: (val) => typeof val === 'boolean',\n    string: (val) => typeof val === 'string',\n    stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n    isSafeInteger: (val) => Number.isSafeInteger(val),\n    array: (val) => Array.isArray(val),\n    field: (val, object) => object.Fp.isValid(val),\n    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n    const checkField = (fieldName, type, isOptional) => {\n        const checkVal = validatorFns[type];\n        if (typeof checkVal !== 'function')\n            throw new Error('invalid validator function');\n        const val = object[fieldName];\n        if (isOptional && val === undefined)\n            return;\n        if (!checkVal(val, object)) {\n            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n        }\n    };\n    for (const [fieldName, type] of Object.entries(validators))\n        checkField(fieldName, type, false);\n    for (const [fieldName, type] of Object.entries(optValidators))\n        checkField(fieldName, type, true);\n    return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n    throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n    const map = new WeakMap();\n    return (arg, ...args) => {\n        const val = map.get(arg);\n        if (val !== undefined)\n            return val;\n        const computed = fn(arg, ...args);\n        map.set(arg, computed);\n        return computed;\n    };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from \"./utils.js\";\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// Calculates a modulo b\nexport function mod(a, b) {\n    const result = a % b;\n    return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n    return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n    let res = x;\n    while (power-- > _0n) {\n        res *= res;\n        res %= modulo;\n    }\n    return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n    if (number === _0n)\n        throw new Error('invert: expected non-zero number');\n    if (modulo <= _0n)\n        throw new Error('invert: expected positive modulus, got ' + modulo);\n    // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n    let a = mod(number, modulo);\n    let b = modulo;\n    // prettier-ignore\n    let x = _0n, y = _1n, u = _1n, v = _0n;\n    while (a !== _0n) {\n        // JIT applies optimization if those two lines follow each other\n        const q = b / a;\n        const r = b % a;\n        const m = x - u * q;\n        const n = y - v * q;\n        // prettier-ignore\n        b = a, a = r, x = u, y = v, u = m, v = n;\n    }\n    const gcd = b;\n    if (gcd !== _1n)\n        throw new Error('invert: does not exist');\n    return mod(x, modulo);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n    const p1div4 = (Fp.ORDER + _1n) / _4n;\n    const root = Fp.pow(n, p1div4);\n    // Throw if root^2 != n\n    if (!Fp.eql(Fp.sqr(root), n))\n        throw new Error('Cannot find square root');\n    return root;\n}\nfunction sqrt5mod8(Fp, n) {\n    const p5div8 = (Fp.ORDER - _5n) / _8n;\n    const n2 = Fp.mul(n, _2n);\n    const v = Fp.pow(n2, p5div8);\n    const nv = Fp.mul(n, v);\n    const i = Fp.mul(Fp.mul(nv, _2n), v);\n    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n    if (!Fp.eql(Fp.sqr(root), n))\n        throw new Error('Cannot find square root');\n    return root;\n}\n// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16<T>(Fp: IField<T>, n: T, p7div16?: bigint) {\n//   if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n//   const c1 = Fp.sqrt(Fp.neg(Fp.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n//   const c2 = Fp.sqrt(c1);             //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n//   const c3 = Fp.sqrt(Fp.neg(c1));     //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n//   const c4 = p7div16;                 //  4. c4 = (q + 7) / 16        # Integer arithmetic\n//   let tv1 = Fp.pow(n, c4);            //  1. tv1 = x^c4\n//   let tv2 = Fp.mul(c1, tv1);          //  2. tv2 = c1 * tv1\n//   const tv3 = Fp.mul(c2, tv1);        //  3. tv3 = c2 * tv1\n//   let tv4 = Fp.mul(c3, tv1);          //  4. tv4 = c3 * tv1\n//   const e1 = Fp.eql(Fp.sqr(tv2), n);  //  5.  e1 = (tv2^2) == x\n//   const e2 = Fp.eql(Fp.sqr(tv3), n);  //  6.  e2 = (tv3^2) == x\n//   tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x\n//   tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x\n//   const e3 = Fp.eql(Fp.sqr(tv2), n);  //  9.  e3 = (tv2^2) == x\n//   return Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n// }\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n    // Initialization (precomputation).\n    if (P < BigInt(3))\n        throw new Error('sqrt is not defined for small field');\n    // Factor P - 1 = Q * 2^S, where Q is odd\n    let Q = P - _1n;\n    let S = 0;\n    while (Q % _2n === _0n) {\n        Q /= _2n;\n        S++;\n    }\n    // Find the first quadratic non-residue Z >= 2\n    let Z = _2n;\n    const _Fp = Field(P);\n    while (FpLegendre(_Fp, Z) === 1) {\n        // Basic primality test for P. After x iterations, chance of\n        // not finding quadratic non-residue is 2^x, so 2^1000.\n        if (Z++ > 1000)\n            throw new Error('Cannot find square root: probably non-prime P');\n    }\n    // Fast-path; usually done before Z, but we do \"primality test\".\n    if (S === 1)\n        return sqrt3mod4;\n    // Slow-path\n    // TODO: test on Fp2 and others\n    let cc = _Fp.pow(Z, Q); // c = z^Q\n    const Q1div2 = (Q + _1n) / _2n;\n    return function tonelliSlow(Fp, n) {\n        if (Fp.is0(n))\n            return n;\n        // Check if n is a quadratic residue using Legendre symbol\n        if (FpLegendre(Fp, n) !== 1)\n            throw new Error('Cannot find square root');\n        // Initialize variables for the main loop\n        let M = S;\n        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n        // Main loop\n        // while t != 1\n        while (!Fp.eql(t, Fp.ONE)) {\n            if (Fp.is0(t))\n                return Fp.ZERO; // if t=0 return R=0\n            let i = 1;\n            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n            let t_tmp = Fp.sqr(t); // t^(2^1)\n            while (!Fp.eql(t_tmp, Fp.ONE)) {\n                i++;\n                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n                if (i === M)\n                    throw new Error('Cannot find square root');\n            }\n            // Calculate the exponent for b: 2^(M - i - 1)\n            const exponent = _1n << BigInt(M - i - 1); // bigint is important\n            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n            // Update variables\n            M = i;\n            c = Fp.sqr(b); // c = b^2\n            t = Fp.mul(t, c); // t = (t * b^2)\n            R = Fp.mul(R, b); // R = R*b\n        }\n        return R;\n    };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n    if (P % _4n === _3n)\n        return sqrt3mod4;\n    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n    if (P % _8n === _5n)\n        return sqrt5mod8;\n    // P ≡ 9 (mod 16) not implemented, see above\n    // Tonelli-Shanks algorithm\n    return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n    'eql', 'add', 'sub', 'mul', 'pow', 'div',\n    'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n    const initial = {\n        ORDER: 'bigint',\n        MASK: 'bigint',\n        BYTES: 'isSafeInteger',\n        BITS: 'isSafeInteger',\n    };\n    const opts = FIELD_FIELDS.reduce((map, val) => {\n        map[val] = 'function';\n        return map;\n    }, initial);\n    return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n    if (power < _0n)\n        throw new Error('invalid exponent, negatives unsupported');\n    if (power === _0n)\n        return Fp.ONE;\n    if (power === _1n)\n        return num;\n    let p = Fp.ONE;\n    let d = num;\n    while (power > _0n) {\n        if (power & _1n)\n            p = Fp.mul(p, d);\n        d = Fp.sqr(d);\n        power >>= _1n;\n    }\n    return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n    // Walk from first to last, multiply them by each other MOD p\n    const multipliedAcc = nums.reduce((acc, num, i) => {\n        if (Fp.is0(num))\n            return acc;\n        inverted[i] = acc;\n        return Fp.mul(acc, num);\n    }, Fp.ONE);\n    // Invert last element\n    const invertedAcc = Fp.inv(multipliedAcc);\n    // Walk from last to first, multiply them by inverted each other MOD p\n    nums.reduceRight((acc, num, i) => {\n        if (Fp.is0(num))\n            return acc;\n        inverted[i] = Fp.mul(acc, inverted[i]);\n        return Fp.mul(acc, num);\n    }, invertedAcc);\n    return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0    if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n    // We can use 3rd argument as optional cache of this value\n    // but seems unneeded for now. The operation is very fast.\n    const p1mod2 = (Fp.ORDER - _1n) / _2n;\n    const powered = Fp.pow(n, p1mod2);\n    const yes = Fp.eql(powered, Fp.ONE);\n    const zero = Fp.eql(powered, Fp.ZERO);\n    const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n    if (!yes && !zero && !no)\n        throw new Error('invalid Legendre symbol result');\n    return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n    const l = FpLegendre(Fp, n);\n    return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n    // Bit size, byte size of CURVE.n\n    if (nBitLength !== undefined)\n        anumber(nBitLength);\n    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n    const nByteLength = Math.ceil(_nBitLength / 8);\n    return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n    if (ORDER <= _0n)\n        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n    if (BYTES > 2048)\n        throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n    let sqrtP; // cached sqrtP\n    const f = Object.freeze({\n        ORDER,\n        isLE,\n        BITS,\n        BYTES,\n        MASK: bitMask(BITS),\n        ZERO: _0n,\n        ONE: _1n,\n        create: (num) => mod(num, ORDER),\n        isValid: (num) => {\n            if (typeof num !== 'bigint')\n                throw new Error('invalid field element: expected bigint, got ' + typeof num);\n            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n        },\n        is0: (num) => num === _0n,\n        isOdd: (num) => (num & _1n) === _1n,\n        neg: (num) => mod(-num, ORDER),\n        eql: (lhs, rhs) => lhs === rhs,\n        sqr: (num) => mod(num * num, ORDER),\n        add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n        pow: (num, power) => FpPow(f, num, power),\n        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n        // Same as above, but doesn't normalize\n        sqrN: (num) => num * num,\n        addN: (lhs, rhs) => lhs + rhs,\n        subN: (lhs, rhs) => lhs - rhs,\n        mulN: (lhs, rhs) => lhs * rhs,\n        inv: (num) => invert(num, ORDER),\n        sqrt: redef.sqrt ||\n            ((n) => {\n                if (!sqrtP)\n                    sqrtP = FpSqrt(ORDER);\n                return sqrtP(f, n);\n            }),\n        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n        fromBytes: (bytes) => {\n            if (bytes.length !== BYTES)\n                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n            return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n        },\n        // TODO: we don't need it here, move out to separate fn\n        invertBatch: (lst) => FpInvertBatch(f, lst),\n        // We can't move this out because Fp6, Fp12 implement it\n        // and it's unclear what to return in there.\n        cmov: (a, b, c) => (c ? b : a),\n    });\n    return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n    if (!Fp.isOdd)\n        throw new Error(\"Field doesn't have isOdd\");\n    const root = Fp.sqrt(elm);\n    return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n    if (!Fp.isOdd)\n        throw new Error(\"Field doesn't have isOdd\");\n    const root = Fp.sqrt(elm);\n    return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n    hash = ensureBytes('privateHash', hash);\n    const hashLen = hash.length;\n    const minLen = nLength(groupOrder).nByteLength + 8;\n    if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n    return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n    if (typeof fieldOrder !== 'bigint')\n        throw new Error('field order must be bigint');\n    const bitLength = fieldOrder.toString(2).length;\n    return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n    const length = getFieldBytesLength(fieldOrder);\n    return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n    const len = key.length;\n    const fieldLen = getFieldBytesLength(fieldOrder);\n    const minLen = getMinHashLength(fieldOrder);\n    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n    if (len < 16 || len < minLen || len > 1024)\n        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n    const reduced = mod(num, fieldOrder - _1n) + _1n;\n    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { nLength, validateField } from \"./modular.js\";\nimport { bitLen, bitMask, validateObject } from \"./utils.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction constTimeNegate(condition, item) {\n    const neg = item.negate();\n    return condition ? neg : item;\n}\nfunction validateW(W, bits) {\n    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n    validateW(W, scalarBits);\n    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n    const maxNumber = 2 ** W; // W=8 256\n    const mask = bitMask(W); // W=8 255 == mask 0b11111111\n    const shiftBy = BigInt(W); // W=8 8\n    return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n    const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n    let wbits = Number(n & mask); // extract W bits.\n    let nextN = n >> shiftBy; // shift number by W bits.\n    // What actually happens here:\n    // const highestBit = Number(mask ^ (mask >> 1n));\n    // let wbits2 = wbits - 1; // skip zero\n    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n    // split if bits > max: +224 => 256-32\n    if (wbits > windowSize) {\n        // we skip zero, which means instead of `>= size-1`, we do `> size`\n        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n        nextN += _1n; // +256 (carry)\n    }\n    const offsetStart = window * windowSize;\n    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n    const isZero = wbits === 0; // is current window slice a 0?\n    const isNeg = wbits < 0; // is current window slice negative?\n    const isNegF = window % 2 !== 0; // fake random statement for noise\n    const offsetF = offsetStart; // fake offset for noise\n    return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n    if (!Array.isArray(points))\n        throw new Error('array expected');\n    points.forEach((p, i) => {\n        if (!(p instanceof c))\n            throw new Error('invalid point at index ' + i);\n    });\n}\nfunction validateMSMScalars(scalars, field) {\n    if (!Array.isArray(scalars))\n        throw new Error('array of scalars expected');\n    scalars.forEach((s, i) => {\n        if (!field.isValid(s))\n            throw new Error('invalid scalar at index ' + i);\n    });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n    return pointWindowSizes.get(P) || 1;\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF(c, bits) {\n    return {\n        constTimeNegate,\n        hasPrecomputes(elm) {\n            return getW(elm) !== 1;\n        },\n        // non-const time multiplication ladder\n        unsafeLadder(elm, n, p = c.ZERO) {\n            let d = elm;\n            while (n > _0n) {\n                if (n & _1n)\n                    p = p.add(d);\n                d = d.double();\n                n >>= _1n;\n            }\n            return p;\n        },\n        /**\n         * Creates a wNAF precomputation window. Used for caching.\n         * Default window size is set by `utils.precompute()` and is equal to 8.\n         * Number of precomputed points depends on the curve size:\n         * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n         * - 𝑊 is the window size\n         * - 𝑛 is the bitlength of the curve order.\n         * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n         * @param elm Point instance\n         * @param W window size\n         * @returns precomputed point tables flattened to a single array\n         */\n        precomputeWindow(elm, W) {\n            const { windows, windowSize } = calcWOpts(W, bits);\n            const points = [];\n            let p = elm;\n            let base = p;\n            for (let window = 0; window < windows; window++) {\n                base = p;\n                points.push(base);\n                // i=1, bc we skip 0\n                for (let i = 1; i < windowSize; i++) {\n                    base = base.add(p);\n                    points.push(base);\n                }\n                p = base.double();\n            }\n            return points;\n        },\n        /**\n         * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n         * @param W window size\n         * @param precomputes precomputed tables\n         * @param n scalar (we don't check here, but should be less than curve order)\n         * @returns real and fake (for const-time) points\n         */\n        wNAF(W, precomputes, n) {\n            // Smaller version:\n            // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n            // TODO: check the scalar is less than group order?\n            // wNAF behavior is undefined otherwise. But have to carefully remove\n            // other checks before wNAF. ORDER == bits here.\n            // Accumulators\n            let p = c.ZERO;\n            let f = c.BASE;\n            // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n            // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n            // there is negate now: it is possible that negated element from low value\n            // would be the same as high element, which will create carry into next window.\n            // It's not obvious how this can fail, but still worth investigating later.\n            const wo = calcWOpts(W, bits);\n            for (let window = 0; window < wo.windows; window++) {\n                // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n                const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n                n = nextN;\n                if (isZero) {\n                    // bits are 0: add garbage to fake point\n                    // Important part for const-time getPublicKey: add random \"noise\" point to f.\n                    f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n                }\n                else {\n                    // bits are 1: add to result point\n                    p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n                }\n            }\n            // Return both real and fake points: JIT won't eliminate f.\n            // At this point there is a way to F be infinity-point even if p is not,\n            // which makes it less const-time: around 1 bigint multiply.\n            return { p, f };\n        },\n        /**\n         * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n         * @param W window size\n         * @param precomputes precomputed tables\n         * @param n scalar (we don't check here, but should be less than curve order)\n         * @param acc accumulator point to add result of multiplication\n         * @returns point\n         */\n        wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {\n            const wo = calcWOpts(W, bits);\n            for (let window = 0; window < wo.windows; window++) {\n                if (n === _0n)\n                    break; // Early-exit, skip 0 value\n                const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n                n = nextN;\n                if (isZero) {\n                    // Window bits are 0: skip processing.\n                    // Move to next window.\n                    continue;\n                }\n                else {\n                    const item = precomputes[offset];\n                    acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n                }\n            }\n            return acc;\n        },\n        getPrecomputes(W, P, transform) {\n            // Calculate precomputes on a first run, reuse them after\n            let comp = pointPrecomputes.get(P);\n            if (!comp) {\n                comp = this.precomputeWindow(P, W);\n                if (W !== 1)\n                    pointPrecomputes.set(P, transform(comp));\n            }\n            return comp;\n        },\n        wNAFCached(P, n, transform) {\n            const W = getW(P);\n            return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n        },\n        wNAFCachedUnsafe(P, n, transform, prev) {\n            const W = getW(P);\n            if (W === 1)\n                return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n            return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n        },\n        // We calculate precomputes for elliptic curve point multiplication\n        // using windowed method. This specifies window size and\n        // stores precomputed values. Usually only base point would be precomputed.\n        setWindowSize(P, W) {\n            validateW(W, bits);\n            pointWindowSizes.set(P, W);\n            pointPrecomputes.delete(P);\n        },\n    };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n    // If we split scalars by some window (let's say 8 bits), every chunk will only\n    // take 256 buckets even if there are 4096 scalars, also re-uses double.\n    // TODO:\n    // - https://eprint.iacr.org/2024/750.pdf\n    // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n    // 0 is accepted in scalars\n    validateMSMPoints(points, c);\n    validateMSMScalars(scalars, fieldN);\n    const plength = points.length;\n    const slength = scalars.length;\n    if (plength !== slength)\n        throw new Error('arrays of points and scalars must have equal length');\n    // if (plength === 0) throw new Error('array must be of length >= 2');\n    const zero = c.ZERO;\n    const wbits = bitLen(BigInt(plength));\n    let windowSize = 1; // bits\n    if (wbits > 12)\n        windowSize = wbits - 3;\n    else if (wbits > 4)\n        windowSize = wbits - 2;\n    else if (wbits > 0)\n        windowSize = 2;\n    const MASK = bitMask(windowSize);\n    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n    let sum = zero;\n    for (let i = lastBits; i >= 0; i -= windowSize) {\n        buckets.fill(zero);\n        for (let j = 0; j < slength; j++) {\n            const scalar = scalars[j];\n            const wbits = Number((scalar >> BigInt(i)) & MASK);\n            buckets[wbits] = buckets[wbits].add(points[j]);\n        }\n        let resI = zero; // not using this will do small speed-up, but will lose ct\n        // Skip first bucket, because it is zero\n        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n            sumI = sumI.add(buckets[j]);\n            resI = resI.add(sumI);\n        }\n        sum = sum.add(resI);\n        if (i !== 0)\n            for (let j = 0; j < windowSize; j++)\n                sum = sum.double();\n    }\n    return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n    /**\n     * Performance Analysis of Window-based Precomputation\n     *\n     * Base Case (256-bit scalar, 8-bit window):\n     * - Standard precomputation requires:\n     *   - 31 additions per scalar × 256 scalars = 7,936 ops\n     *   - Plus 255 summary additions = 8,191 total ops\n     *   Note: Summary additions can be optimized via accumulator\n     *\n     * Chunked Precomputation Analysis:\n     * - Using 32 chunks requires:\n     *   - 255 additions per chunk\n     *   - 256 doublings\n     *   - Total: (255 × 32) + 256 = 8,416 ops\n     *\n     * Memory Usage Comparison:\n     * Window Size | Standard Points | Chunked Points\n     * ------------|-----------------|---------------\n     *     4-bit   |     520         |      15\n     *     8-bit   |    4,224        |     255\n     *    10-bit   |   13,824        |   1,023\n     *    16-bit   |  557,056        |  65,535\n     *\n     * Key Advantages:\n     * 1. Enables larger window sizes due to reduced memory overhead\n     * 2. More efficient for smaller scalar counts:\n     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops\n     *    - ~2x faster than standard 8,191 ops\n     *\n     * Limitations:\n     * - Not suitable for plain precomputes (requires 256 constant doublings)\n     * - Performance degrades with larger scalar counts:\n     *   - Optimal for ~256 scalars\n     *   - Less efficient for 4096+ scalars (Pippenger preferred)\n     */\n    validateW(windowSize, fieldN.BITS);\n    validateMSMPoints(points, c);\n    const zero = c.ZERO;\n    const tableSize = 2 ** windowSize - 1; // table size (without zero)\n    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n    const MASK = bitMask(windowSize);\n    const tables = points.map((p) => {\n        const res = [];\n        for (let i = 0, acc = p; i < tableSize; i++) {\n            res.push(acc);\n            acc = acc.add(p);\n        }\n        return res;\n    });\n    return (scalars) => {\n        validateMSMScalars(scalars, fieldN);\n        if (scalars.length > points.length)\n            throw new Error('array of scalars must be smaller than array of points');\n        let res = zero;\n        for (let i = 0; i < chunks; i++) {\n            // No need to double if accumulator is still zero.\n            if (res !== zero)\n                for (let j = 0; j < windowSize; j++)\n                    res = res.double();\n            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n            for (let j = 0; j < scalars.length; j++) {\n                const n = scalars[j];\n                const curr = Number((n >> shiftBy) & MASK);\n                if (!curr)\n                    continue; // skip zero scalars chunks\n                res = res.add(tables[j][curr - 1]);\n            }\n        }\n        return res;\n    };\n}\nexport function validateBasic(curve) {\n    validateField(curve.Fp);\n    validateObject(curve, {\n        n: 'bigint',\n        h: 'bigint',\n        Gx: 'field',\n        Gy: 'field',\n    }, {\n        nBitLength: 'isSafeInteger',\n        nByteLength: 'isSafeInteger',\n    });\n    // Set defaults\n    return Object.freeze({\n        ...nLength(curve.n, curve.nBitLength),\n        ...curve,\n        ...{ p: curve.Fp.ORDER },\n    });\n}\n//# sourceMappingURL=curve.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n *   `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n *   it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n *     which is hard to debug.\n *     2. Params can be generic and we can't enforce them to be constant value:\n *     if somebody creates curve from non-constant params,\n *     it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport { pippenger, validateBasic, wNAF } from \"./curve.js\";\n// prettier-ignore\nimport { Field, FpInvertBatch, getMinHashLength, invert, mapHashToField, mod, validateField } from \"./modular.js\";\n// prettier-ignore\nimport { aInRange, abool, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject } from \"./utils.js\";\nfunction validateSigVerOpts(opts) {\n    if (opts.lowS !== undefined)\n        abool('lowS', opts.lowS);\n    if (opts.prehash !== undefined)\n        abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n    const opts = validateBasic(curve);\n    validateObject(opts, {\n        a: 'field',\n        b: 'field',\n    }, {\n        allowInfinityPoint: 'boolean',\n        allowedPrivateKeyLengths: 'array',\n        clearCofactor: 'function',\n        fromBytes: 'function',\n        isTorsionFree: 'function',\n        toBytes: 'function',\n        wrapPrivateKey: 'boolean',\n    });\n    const { endo, Fp, a } = opts;\n    if (endo) {\n        if (!Fp.eql(a, Fp.ZERO)) {\n            throw new Error('invalid endo: CURVE.a must be 0');\n        }\n        if (typeof endo !== 'object' ||\n            typeof endo.beta !== 'bigint' ||\n            typeof endo.splitScalar !== 'function') {\n            throw new Error('invalid endo: expected \"beta\": bigint and \"splitScalar\": function');\n        }\n    }\n    return Object.freeze({ ...opts });\n}\nexport class DERErr extends Error {\n    constructor(m = '') {\n        super(m);\n    }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n    // asn.1 DER encoding utils\n    Err: DERErr,\n    // Basic building block is TLV (Tag-Length-Value)\n    _tlv: {\n        encode: (tag, data) => {\n            const { Err: E } = DER;\n            if (tag < 0 || tag > 256)\n                throw new E('tlv.encode: wrong tag');\n            if (data.length & 1)\n                throw new E('tlv.encode: unpadded data');\n            const dataLen = data.length / 2;\n            const len = numberToHexUnpadded(dataLen);\n            if ((len.length / 2) & 128)\n                throw new E('tlv.encode: long form length too big');\n            // length of length with long form flag\n            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';\n            const t = numberToHexUnpadded(tag);\n            return t + lenLen + len + data;\n        },\n        // v - value, l - left bytes (unparsed)\n        decode(tag, data) {\n            const { Err: E } = DER;\n            let pos = 0;\n            if (tag < 0 || tag > 256)\n                throw new E('tlv.encode: wrong tag');\n            if (data.length < 2 || data[pos++] !== tag)\n                throw new E('tlv.decode: wrong tlv');\n            const first = data[pos++];\n            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n            let length = 0;\n            if (!isLong)\n                length = first;\n            else {\n                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n                const lenLen = first & 127;\n                if (!lenLen)\n                    throw new E('tlv.decode(long): indefinite length not supported');\n                if (lenLen > 4)\n                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n                const lengthBytes = data.subarray(pos, pos + lenLen);\n                if (lengthBytes.length !== lenLen)\n                    throw new E('tlv.decode: length bytes not complete');\n                if (lengthBytes[0] === 0)\n                    throw new E('tlv.decode(long): zero leftmost byte');\n                for (const b of lengthBytes)\n                    length = (length << 8) | b;\n                pos += lenLen;\n                if (length < 128)\n                    throw new E('tlv.decode(long): not minimal encoding');\n            }\n            const v = data.subarray(pos, pos + length);\n            if (v.length !== length)\n                throw new E('tlv.decode: wrong value length');\n            return { v, l: data.subarray(pos + length) };\n        },\n    },\n    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n    // since we always use positive integers here. It must always be empty:\n    // - add zero byte if exists\n    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n    _int: {\n        encode(num) {\n            const { Err: E } = DER;\n            if (num < _0n)\n                throw new E('integer: negative integers are not allowed');\n            let hex = numberToHexUnpadded(num);\n            // Pad with zero byte if negative flag is present\n            if (Number.parseInt(hex[0], 16) & 0b1000)\n                hex = '00' + hex;\n            if (hex.length & 1)\n                throw new E('unexpected DER parsing assertion: unpadded hex');\n            return hex;\n        },\n        decode(data) {\n            const { Err: E } = DER;\n            if (data[0] & 128)\n                throw new E('invalid signature integer: negative');\n            if (data[0] === 0x00 && !(data[1] & 128))\n                throw new E('invalid signature integer: unnecessary leading zero');\n            return bytesToNumberBE(data);\n        },\n    },\n    toSig(hex) {\n        // parse DER signature\n        const { Err: E, _int: int, _tlv: tlv } = DER;\n        const data = ensureBytes('signature', hex);\n        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n        if (seqLeftBytes.length)\n            throw new E('invalid signature: left bytes after parsing');\n        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n        if (sLeftBytes.length)\n            throw new E('invalid signature: left bytes after parsing');\n        return { r: int.decode(rBytes), s: int.decode(sBytes) };\n    },\n    hexFromSig(sig) {\n        const { _tlv: tlv, _int: int } = DER;\n        const rs = tlv.encode(0x02, int.encode(sig.r));\n        const ss = tlv.encode(0x02, int.encode(sig.s));\n        const seq = rs + ss;\n        return tlv.encode(0x30, seq);\n    },\n};\nfunction numToSizedHex(num, size) {\n    return bytesToHex(numberToBytesBE(num, size));\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n    const CURVE = validatePointOpts(opts);\n    const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n    const Fn = Field(CURVE.n, CURVE.nBitLength);\n    const toBytes = CURVE.toBytes ||\n        ((_c, point, _isCompressed) => {\n            const a = point.toAffine();\n            return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n        });\n    const fromBytes = CURVE.fromBytes ||\n        ((bytes) => {\n            // const head = bytes[0];\n            const tail = bytes.subarray(1);\n            // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n            const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n            const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n            return { x, y };\n        });\n    /**\n     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n     * @returns y²\n     */\n    function weierstrassEquation(x) {\n        const { a, b } = CURVE;\n        const x2 = Fp.sqr(x); // x * x\n        const x3 = Fp.mul(x2, x); // x² * x\n        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n    }\n    function isValidXY(x, y) {\n        const left = Fp.sqr(y); // y²\n        const right = weierstrassEquation(x); // x³ + ax + b\n        return Fp.eql(left, right);\n    }\n    // Validate whether the passed curve params are valid.\n    // Test 1: equation y² = x³ + ax + b should work for generator point.\n    if (!isValidXY(CURVE.Gx, CURVE.Gy))\n        throw new Error('bad curve params: generator point');\n    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n    // Guarantees curve is genus-1, smooth (non-singular).\n    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n    if (Fp.is0(Fp.add(_4a3, _27b2)))\n        throw new Error('bad curve params: a or b');\n    // Valid group elements reside in range 1..n-1\n    function isWithinCurveOrder(num) {\n        return inRange(num, _1n, CURVE.n);\n    }\n    // Validates if priv key is valid and converts it to bigint.\n    // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n    function normPrivateKeyToScalar(key) {\n        const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n        if (lengths && typeof key !== 'bigint') {\n            if (isBytes(key))\n                key = bytesToHex(key);\n            // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n            if (typeof key !== 'string' || !lengths.includes(key.length))\n                throw new Error('invalid private key');\n            key = key.padStart(nByteLength * 2, '0');\n        }\n        let num;\n        try {\n            num =\n                typeof key === 'bigint'\n                    ? key\n                    : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n        }\n        catch (error) {\n            throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);\n        }\n        if (wrapPrivateKey)\n            num = mod(num, N); // disabled by default, enabled for BLS\n        aInRange('private key', num, _1n, N); // num in range [1..N-1]\n        return num;\n    }\n    function aprjpoint(other) {\n        if (!(other instanceof Point))\n            throw new Error('ProjectivePoint expected');\n    }\n    // Memoized toAffine / validity check. They are heavy. Points are immutable.\n    // Converts Projective point to affine (x, y) coordinates.\n    // Can accept precomputed Z^-1 - for example, from invertBatch.\n    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n    const toAffineMemo = memoized((p, iz) => {\n        const { px: x, py: y, pz: z } = p;\n        // Fast-path for normalized points\n        if (Fp.eql(z, Fp.ONE))\n            return { x, y };\n        const is0 = p.is0();\n        // If invZ was 0, we return zero point. However we still want to execute\n        // all operations, so we replace invZ with a random number, 1.\n        if (iz == null)\n            iz = is0 ? Fp.ONE : Fp.inv(z);\n        const ax = Fp.mul(x, iz);\n        const ay = Fp.mul(y, iz);\n        const zz = Fp.mul(z, iz);\n        if (is0)\n            return { x: Fp.ZERO, y: Fp.ZERO };\n        if (!Fp.eql(zz, Fp.ONE))\n            throw new Error('invZ was invalid');\n        return { x: ax, y: ay };\n    });\n    // NOTE: on exception this will crash 'cached' and no value will be set.\n    // Otherwise true will be return\n    const assertValidMemo = memoized((p) => {\n        if (p.is0()) {\n            // (0, 1, 0) aka ZERO is invalid in most contexts.\n            // In BLS, ZERO can be serialized, so we allow it.\n            // (0, 0, 0) is invalid representation of ZERO.\n            if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n                return;\n            throw new Error('bad point: ZERO');\n        }\n        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n        const { x, y } = p.toAffine();\n        // Check if x, y are valid field elements\n        if (!Fp.isValid(x) || !Fp.isValid(y))\n            throw new Error('bad point: x or y not FE');\n        if (!isValidXY(x, y))\n            throw new Error('bad point: equation left != right');\n        if (!p.isTorsionFree())\n            throw new Error('bad point: not in prime-order subgroup');\n        return true;\n    });\n    /**\n     * Projective Point works in 3d / projective (homogeneous) coordinates: (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n     * Default Point works in 2d / affine coordinates: (x, y)\n     * We're doing calculations in projective, because its operations don't require costly inversion.\n     */\n    class Point {\n        constructor(px, py, pz) {\n            if (px == null || !Fp.isValid(px))\n                throw new Error('x required');\n            if (py == null || !Fp.isValid(py) || Fp.is0(py))\n                throw new Error('y required');\n            if (pz == null || !Fp.isValid(pz))\n                throw new Error('z required');\n            this.px = px;\n            this.py = py;\n            this.pz = pz;\n            Object.freeze(this);\n        }\n        // Does not validate if the point is on-curve.\n        // Use fromHex instead, or call assertValidity() later.\n        static fromAffine(p) {\n            const { x, y } = p || {};\n            if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n                throw new Error('invalid affine point');\n            if (p instanceof Point)\n                throw new Error('projective point not allowed');\n            const is0 = (i) => Fp.eql(i, Fp.ZERO);\n            // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n            if (is0(x) && is0(y))\n                return Point.ZERO;\n            return new Point(x, y, Fp.ONE);\n        }\n        get x() {\n            return this.toAffine().x;\n        }\n        get y() {\n            return this.toAffine().y;\n        }\n        /**\n         * Takes a bunch of Projective Points but executes only one\n         * inversion on all of them. Inversion is very slow operation,\n         * so this improves performance massively.\n         * Optimization: converts a list of projective points to a list of identical points with Z=1.\n         */\n        static normalizeZ(points) {\n            const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));\n            return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n        }\n        /**\n         * Converts hash string or Uint8Array to Point.\n         * @param hex short/long ECDSA hex\n         */\n        static fromHex(hex) {\n            const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n            P.assertValidity();\n            return P;\n        }\n        // Multiplies generator point by privateKey.\n        static fromPrivateKey(privateKey) {\n            return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n        }\n        // Multiscalar Multiplication\n        static msm(points, scalars) {\n            return pippenger(Point, Fn, points, scalars);\n        }\n        // \"Private method\", don't use it directly\n        _setWindowSize(windowSize) {\n            wnaf.setWindowSize(this, windowSize);\n        }\n        // A point on curve is valid if it conforms to equation.\n        assertValidity() {\n            assertValidMemo(this);\n        }\n        hasEvenY() {\n            const { y } = this.toAffine();\n            if (Fp.isOdd)\n                return !Fp.isOdd(y);\n            throw new Error(\"Field doesn't support isOdd\");\n        }\n        /**\n         * Compare one point to another.\n         */\n        equals(other) {\n            aprjpoint(other);\n            const { px: X1, py: Y1, pz: Z1 } = this;\n            const { px: X2, py: Y2, pz: Z2 } = other;\n            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n            return U1 && U2;\n        }\n        /**\n         * Flips point to one corresponding to (x, -y) in Affine coordinates.\n         */\n        negate() {\n            return new Point(this.px, Fp.neg(this.py), this.pz);\n        }\n        // Renes-Costello-Batina exception-free doubling formula.\n        // There is 30% faster Jacobian formula, but it is not complete.\n        // https://eprint.iacr.org/2015/1060, algorithm 3\n        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n        double() {\n            const { a, b } = CURVE;\n            const b3 = Fp.mul(b, _3n);\n            const { px: X1, py: Y1, pz: Z1 } = this;\n            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n            let t0 = Fp.mul(X1, X1); // step 1\n            let t1 = Fp.mul(Y1, Y1);\n            let t2 = Fp.mul(Z1, Z1);\n            let t3 = Fp.mul(X1, Y1);\n            t3 = Fp.add(t3, t3); // step 5\n            Z3 = Fp.mul(X1, Z1);\n            Z3 = Fp.add(Z3, Z3);\n            X3 = Fp.mul(a, Z3);\n            Y3 = Fp.mul(b3, t2);\n            Y3 = Fp.add(X3, Y3); // step 10\n            X3 = Fp.sub(t1, Y3);\n            Y3 = Fp.add(t1, Y3);\n            Y3 = Fp.mul(X3, Y3);\n            X3 = Fp.mul(t3, X3);\n            Z3 = Fp.mul(b3, Z3); // step 15\n            t2 = Fp.mul(a, t2);\n            t3 = Fp.sub(t0, t2);\n            t3 = Fp.mul(a, t3);\n            t3 = Fp.add(t3, Z3);\n            Z3 = Fp.add(t0, t0); // step 20\n            t0 = Fp.add(Z3, t0);\n            t0 = Fp.add(t0, t2);\n            t0 = Fp.mul(t0, t3);\n            Y3 = Fp.add(Y3, t0);\n            t2 = Fp.mul(Y1, Z1); // step 25\n            t2 = Fp.add(t2, t2);\n            t0 = Fp.mul(t2, t3);\n            X3 = Fp.sub(X3, t0);\n            Z3 = Fp.mul(t2, t1);\n            Z3 = Fp.add(Z3, Z3); // step 30\n            Z3 = Fp.add(Z3, Z3);\n            return new Point(X3, Y3, Z3);\n        }\n        // Renes-Costello-Batina exception-free addition formula.\n        // There is 30% faster Jacobian formula, but it is not complete.\n        // https://eprint.iacr.org/2015/1060, algorithm 1\n        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n        add(other) {\n            aprjpoint(other);\n            const { px: X1, py: Y1, pz: Z1 } = this;\n            const { px: X2, py: Y2, pz: Z2 } = other;\n            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n            const a = CURVE.a;\n            const b3 = Fp.mul(CURVE.b, _3n);\n            let t0 = Fp.mul(X1, X2); // step 1\n            let t1 = Fp.mul(Y1, Y2);\n            let t2 = Fp.mul(Z1, Z2);\n            let t3 = Fp.add(X1, Y1);\n            let t4 = Fp.add(X2, Y2); // step 5\n            t3 = Fp.mul(t3, t4);\n            t4 = Fp.add(t0, t1);\n            t3 = Fp.sub(t3, t4);\n            t4 = Fp.add(X1, Z1);\n            let t5 = Fp.add(X2, Z2); // step 10\n            t4 = Fp.mul(t4, t5);\n            t5 = Fp.add(t0, t2);\n            t4 = Fp.sub(t4, t5);\n            t5 = Fp.add(Y1, Z1);\n            X3 = Fp.add(Y2, Z2); // step 15\n            t5 = Fp.mul(t5, X3);\n            X3 = Fp.add(t1, t2);\n            t5 = Fp.sub(t5, X3);\n            Z3 = Fp.mul(a, t4);\n            X3 = Fp.mul(b3, t2); // step 20\n            Z3 = Fp.add(X3, Z3);\n            X3 = Fp.sub(t1, Z3);\n            Z3 = Fp.add(t1, Z3);\n            Y3 = Fp.mul(X3, Z3);\n            t1 = Fp.add(t0, t0); // step 25\n            t1 = Fp.add(t1, t0);\n            t2 = Fp.mul(a, t2);\n            t4 = Fp.mul(b3, t4);\n            t1 = Fp.add(t1, t2);\n            t2 = Fp.sub(t0, t2); // step 30\n            t2 = Fp.mul(a, t2);\n            t4 = Fp.add(t4, t2);\n            t0 = Fp.mul(t1, t4);\n            Y3 = Fp.add(Y3, t0);\n            t0 = Fp.mul(t5, t4); // step 35\n            X3 = Fp.mul(t3, X3);\n            X3 = Fp.sub(X3, t0);\n            t0 = Fp.mul(t3, t1);\n            Z3 = Fp.mul(t5, Z3);\n            Z3 = Fp.add(Z3, t0); // step 40\n            return new Point(X3, Y3, Z3);\n        }\n        subtract(other) {\n            return this.add(other.negate());\n        }\n        is0() {\n            return this.equals(Point.ZERO);\n        }\n        wNAF(n) {\n            return wnaf.wNAFCached(this, n, Point.normalizeZ);\n        }\n        /**\n         * Non-constant-time multiplication. Uses double-and-add algorithm.\n         * It's faster, but should only be used when you don't care about\n         * an exposed private key e.g. sig verification, which works over *public* keys.\n         */\n        multiplyUnsafe(sc) {\n            const { endo, n: N } = CURVE;\n            aInRange('scalar', sc, _0n, N);\n            const I = Point.ZERO;\n            if (sc === _0n)\n                return I;\n            if (this.is0() || sc === _1n)\n                return this;\n            // Case a: no endomorphism. Case b: has precomputes.\n            if (!endo || wnaf.hasPrecomputes(this))\n                return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n            // Case c: endomorphism\n            /** See docs for {@link EndomorphismOpts} */\n            let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n            let k1p = I;\n            let k2p = I;\n            let d = this;\n            while (k1 > _0n || k2 > _0n) {\n                if (k1 & _1n)\n                    k1p = k1p.add(d);\n                if (k2 & _1n)\n                    k2p = k2p.add(d);\n                d = d.double();\n                k1 >>= _1n;\n                k2 >>= _1n;\n            }\n            if (k1neg)\n                k1p = k1p.negate();\n            if (k2neg)\n                k2p = k2p.negate();\n            k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n            return k1p.add(k2p);\n        }\n        /**\n         * Constant time multiplication.\n         * Uses wNAF method. Windowed method may be 10% faster,\n         * but takes 2x longer to generate and consumes 2x memory.\n         * Uses precomputes when available.\n         * Uses endomorphism for Koblitz curves.\n         * @param scalar by which the point would be multiplied\n         * @returns New point\n         */\n        multiply(scalar) {\n            const { endo, n: N } = CURVE;\n            aInRange('scalar', scalar, _1n, N);\n            let point, fake; // Fake point is used to const-time mult\n            /** See docs for {@link EndomorphismOpts} */\n            if (endo) {\n                const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n                let { p: k1p, f: f1p } = this.wNAF(k1);\n                let { p: k2p, f: f2p } = this.wNAF(k2);\n                k1p = wnaf.constTimeNegate(k1neg, k1p);\n                k2p = wnaf.constTimeNegate(k2neg, k2p);\n                k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n                point = k1p.add(k2p);\n                fake = f1p.add(f2p);\n            }\n            else {\n                const { p, f } = this.wNAF(scalar);\n                point = p;\n                fake = f;\n            }\n            // Normalize `z` for both points, but return only real one\n            return Point.normalizeZ([point, fake])[0];\n        }\n        /**\n         * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n         * Not using Strauss-Shamir trick: precomputation tables are faster.\n         * The trick could be useful if both P and Q are not G (not in our case).\n         * @returns non-zero affine point\n         */\n        multiplyAndAddUnsafe(Q, a, b) {\n            const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n            const mul = (P, a // Select faster multiply() method\n            ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n            const sum = mul(this, a).add(mul(Q, b));\n            return sum.is0() ? undefined : sum;\n        }\n        // Converts Projective point to affine (x, y) coordinates.\n        // Can accept precomputed Z^-1 - for example, from invertBatch.\n        // (x, y, z) ∋ (x=x/z, y=y/z)\n        toAffine(iz) {\n            return toAffineMemo(this, iz);\n        }\n        isTorsionFree() {\n            const { h: cofactor, isTorsionFree } = CURVE;\n            if (cofactor === _1n)\n                return true; // No subgroups, always torsion-free\n            if (isTorsionFree)\n                return isTorsionFree(Point, this);\n            throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n        }\n        clearCofactor() {\n            const { h: cofactor, clearCofactor } = CURVE;\n            if (cofactor === _1n)\n                return this; // Fast-path\n            if (clearCofactor)\n                return clearCofactor(Point, this);\n            return this.multiplyUnsafe(CURVE.h);\n        }\n        toRawBytes(isCompressed = true) {\n            abool('isCompressed', isCompressed);\n            this.assertValidity();\n            return toBytes(Point, this, isCompressed);\n        }\n        toHex(isCompressed = true) {\n            abool('isCompressed', isCompressed);\n            return bytesToHex(this.toRawBytes(isCompressed));\n        }\n    }\n    // base / generator point\n    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n    // zero / infinity / identity point\n    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n    const { endo, nBitLength } = CURVE;\n    const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\n    return {\n        CURVE,\n        ProjectivePoint: Point,\n        normPrivateKeyToScalar,\n        weierstrassEquation,\n        isWithinCurveOrder,\n    };\n}\nfunction validateOpts(curve) {\n    const opts = validateBasic(curve);\n    validateObject(opts, {\n        hash: 'hash',\n        hmac: 'function',\n        randomBytes: 'function',\n    }, {\n        bits2int: 'function',\n        bits2int_modN: 'function',\n        lowS: 'boolean',\n    });\n    return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n    const CURVE = validateOpts(curveDef);\n    const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;\n    const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n    const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n    function modN(a) {\n        return mod(a, CURVE_ORDER);\n    }\n    function invN(a) {\n        return invert(a, CURVE_ORDER);\n    }\n    const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n        ...CURVE,\n        toBytes(_c, point, isCompressed) {\n            const a = point.toAffine();\n            const x = Fp.toBytes(a.x);\n            const cat = concatBytes;\n            abool('isCompressed', isCompressed);\n            if (isCompressed) {\n                return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n            }\n            else {\n                return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n            }\n        },\n        fromBytes(bytes) {\n            const len = bytes.length;\n            const head = bytes[0];\n            const tail = bytes.subarray(1);\n            // this.assertValidity() is done inside of fromHex\n            if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n                const x = bytesToNumberBE(tail);\n                if (!inRange(x, _1n, Fp.ORDER))\n                    throw new Error('Point is not on curve');\n                const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n                let y;\n                try {\n                    y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n                }\n                catch (sqrtError) {\n                    const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n                    throw new Error('Point is not on curve' + suffix);\n                }\n                const isYOdd = (y & _1n) === _1n;\n                // ECDSA\n                const isHeadOdd = (head & 1) === 1;\n                if (isHeadOdd !== isYOdd)\n                    y = Fp.neg(y);\n                return { x, y };\n            }\n            else if (len === uncompressedLen && head === 0x04) {\n                const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n                const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n                return { x, y };\n            }\n            else {\n                const cl = compressedLen;\n                const ul = uncompressedLen;\n                throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);\n            }\n        },\n    });\n    function isBiggerThanHalfOrder(number) {\n        const HALF = CURVE_ORDER >> _1n;\n        return number > HALF;\n    }\n    function normalizeS(s) {\n        return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n    }\n    // slice bytes num\n    const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));\n    /**\n     * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n     */\n    class Signature {\n        constructor(r, s, recovery) {\n            aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n            aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n            this.r = r;\n            this.s = s;\n            if (recovery != null)\n                this.recovery = recovery;\n            Object.freeze(this);\n        }\n        // pair (bytes of r, bytes of s)\n        static fromCompact(hex) {\n            const l = nByteLength;\n            hex = ensureBytes('compactSignature', hex, l * 2);\n            return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n        }\n        // DER encoded ECDSA signature\n        // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n        static fromDER(hex) {\n            const { r, s } = DER.toSig(ensureBytes('DER', hex));\n            return new Signature(r, s);\n        }\n        /**\n         * @todo remove\n         * @deprecated\n         */\n        assertValidity() { }\n        addRecoveryBit(recovery) {\n            return new Signature(this.r, this.s, recovery);\n        }\n        recoverPublicKey(msgHash) {\n            const { r, s, recovery: rec } = this;\n            const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n            if (rec == null || ![0, 1, 2, 3].includes(rec))\n                throw new Error('recovery id invalid');\n            const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n            if (radj >= Fp.ORDER)\n                throw new Error('recovery id 2 or 3 invalid');\n            const prefix = (rec & 1) === 0 ? '02' : '03';\n            const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));\n            const ir = invN(radj); // r^-1\n            const u1 = modN(-h * ir); // -hr^-1\n            const u2 = modN(s * ir); // sr^-1\n            const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n            if (!Q)\n                throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n            Q.assertValidity();\n            return Q;\n        }\n        // Signatures should be low-s, to prevent malleability.\n        hasHighS() {\n            return isBiggerThanHalfOrder(this.s);\n        }\n        normalizeS() {\n            return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n        }\n        // DER-encoded\n        toDERRawBytes() {\n            return hexToBytes(this.toDERHex());\n        }\n        toDERHex() {\n            return DER.hexFromSig(this);\n        }\n        // padded bytes of r, then padded bytes of s\n        toCompactRawBytes() {\n            return hexToBytes(this.toCompactHex());\n        }\n        toCompactHex() {\n            const l = nByteLength;\n            return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\n        }\n    }\n    const utils = {\n        isValidPrivateKey(privateKey) {\n            try {\n                normPrivateKeyToScalar(privateKey);\n                return true;\n            }\n            catch (error) {\n                return false;\n            }\n        },\n        normPrivateKeyToScalar: normPrivateKeyToScalar,\n        /**\n         * Produces cryptographically secure private key from random of size\n         * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n         */\n        randomPrivateKey: () => {\n            const length = getMinHashLength(CURVE.n);\n            return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n        },\n        /**\n         * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n         * Allows to massively speed-up `point.multiply(scalar)`.\n         * @returns cached point\n         * @example\n         * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n         * fast.multiply(privKey); // much faster ECDH now\n         */\n        precompute(windowSize = 8, point = Point.BASE) {\n            point._setWindowSize(windowSize);\n            point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n            return point;\n        },\n    };\n    /**\n     * Computes public key for a private key. Checks for validity of the private key.\n     * @param privateKey private key\n     * @param isCompressed whether to return compact (default), or full key\n     * @returns Public key, full when isCompressed=false; short when isCompressed=true\n     */\n    function getPublicKey(privateKey, isCompressed = true) {\n        return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n    }\n    /**\n     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n     */\n    function isProbPub(item) {\n        if (typeof item === 'bigint')\n            return false;\n        if (item instanceof Point)\n            return true;\n        const arr = ensureBytes('key', item);\n        const len = arr.length;\n        const fpl = Fp.BYTES;\n        const compLen = fpl + 1; // e.g. 33 for 32\n        const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n        if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n            return undefined;\n        }\n        else {\n            return len === compLen || len === uncompLen;\n        }\n    }\n    /**\n     * ECDH (Elliptic Curve Diffie Hellman).\n     * Computes shared public key from private key and public key.\n     * Checks: 1) private key validity 2) shared key is on-curve.\n     * Does NOT hash the result.\n     * @param privateA private key\n     * @param publicB different public key\n     * @param isCompressed whether to return compact (default), or full key\n     * @returns shared public key\n     */\n    function getSharedSecret(privateA, publicB, isCompressed = true) {\n        if (isProbPub(privateA) === true)\n            throw new Error('first arg must be private key');\n        if (isProbPub(publicB) === false)\n            throw new Error('second arg must be public key');\n        const b = Point.fromHex(publicB); // check for being on-curve\n        return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n    }\n    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n    const bits2int = CURVE.bits2int ||\n        function (bytes) {\n            // Our custom check \"just in case\", for protection against DoS\n            if (bytes.length > 8192)\n                throw new Error('input is too large');\n            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n            // for some cases, since bytes.length * 8 is not actual bitLength.\n            const num = bytesToNumberBE(bytes); // check for == u8 done here\n            const delta = bytes.length * 8 - nBitLength; // truncate to nBitLength leftmost bits\n            return delta > 0 ? num >> BigInt(delta) : num;\n        };\n    const bits2int_modN = CURVE.bits2int_modN ||\n        function (bytes) {\n            return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n        };\n    // NOTE: pads output with zero as per spec\n    const ORDER_MASK = bitMask(nBitLength);\n    /**\n     * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n     */\n    function int2octets(num) {\n        aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n        // works with order, can have different size than numToField!\n        return numberToBytesBE(num, nByteLength);\n    }\n    // Steps A, D of RFC6979 3.2\n    // Creates RFC6979 seed; converts msg/privKey to numbers.\n    // Used only in sign, not in verify.\n    // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n    // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n    function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n        if (['recovered', 'canonical'].some((k) => k in opts))\n            throw new Error('sign() legacy options not supported');\n        const { hash, randomBytes } = CURVE;\n        let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n        if (lowS == null)\n            lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n        msgHash = ensureBytes('msgHash', msgHash);\n        validateSigVerOpts(opts);\n        if (prehash)\n            msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n        // We can't later call bits2octets, since nested bits2int is broken for curves\n        // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n        const h1int = bits2int_modN(msgHash);\n        const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n        const seedArgs = [int2octets(d), int2octets(h1int)];\n        // extraEntropy. RFC6979 3.6: additional k' (optional).\n        if (ent != null && ent !== false) {\n            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n            const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n        }\n        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n        // Converts signature params into point w r/s, checks result for validity.\n        function k2sig(kBytes) {\n            // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n            const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n            if (!isWithinCurveOrder(k))\n                return; // Important: all mod() calls here must be done over N\n            const ik = invN(k); // k^-1 mod n\n            const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n            const r = modN(q.x); // r = q.x mod n\n            if (r === _0n)\n                return;\n            // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n            // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n            // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n            const s = modN(ik * modN(m + r * d)); // Not using blinding here\n            if (s === _0n)\n                return;\n            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n            let normS = s;\n            if (lowS && isBiggerThanHalfOrder(s)) {\n                normS = normalizeS(s); // if lowS was passed, ensure s is always\n                recovery ^= 1; // // in the bottom half of N\n            }\n            return new Signature(r, normS, recovery); // use normS, not s\n        }\n        return { seed, k2sig };\n    }\n    const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n    const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n    /**\n     * Signs message hash with a private key.\n     * ```\n     * sign(m, d, k) where\n     *   (x, y) = G × k\n     *   r = x mod n\n     *   s = (m + dr)/k mod n\n     * ```\n     * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n     * @param privKey private key\n     * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n     * @returns signature with recovery param\n     */\n    function sign(msgHash, privKey, opts = defaultSigOpts) {\n        const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n        const C = CURVE;\n        const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n        return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n    }\n    // Enable precomputes. Slows down first publicKey computation by 20ms.\n    Point.BASE._setWindowSize(8);\n    // utils.precompute(8, ProjectivePoint.BASE)\n    /**\n     * Verifies a signature against message hash and public key.\n     * Rejects lowS signatures by default: to override,\n     * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n     *\n     * ```\n     * verify(r, s, h, P) where\n     *   U1 = hs^-1 mod n\n     *   U2 = rs^-1 mod n\n     *   R = U1⋅G - U2⋅P\n     *   mod(R.x, n) == r\n     * ```\n     */\n    function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n        const sg = signature;\n        msgHash = ensureBytes('msgHash', msgHash);\n        publicKey = ensureBytes('publicKey', publicKey);\n        const { lowS, prehash, format } = opts;\n        // Verify opts, deduce signature format\n        validateSigVerOpts(opts);\n        if ('strict' in opts)\n            throw new Error('options.strict was renamed to lowS');\n        if (format !== undefined && format !== 'compact' && format !== 'der')\n            throw new Error('format must be compact or der');\n        const isHex = typeof sg === 'string' || isBytes(sg);\n        const isObj = !isHex &&\n            !format &&\n            typeof sg === 'object' &&\n            sg !== null &&\n            typeof sg.r === 'bigint' &&\n            typeof sg.s === 'bigint';\n        if (!isHex && !isObj)\n            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n        let _sig = undefined;\n        let P;\n        try {\n            if (isObj)\n                _sig = new Signature(sg.r, sg.s);\n            if (isHex) {\n                // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n                // Since DER can also be 2*nByteLength bytes, we check for it first.\n                try {\n                    if (format !== 'compact')\n                        _sig = Signature.fromDER(sg);\n                }\n                catch (derError) {\n                    if (!(derError instanceof DER.Err))\n                        throw derError;\n                }\n                if (!_sig && format !== 'der')\n                    _sig = Signature.fromCompact(sg);\n            }\n            P = Point.fromHex(publicKey);\n        }\n        catch (error) {\n            return false;\n        }\n        if (!_sig)\n            return false;\n        if (lowS && _sig.hasHighS())\n            return false;\n        if (prehash)\n            msgHash = CURVE.hash(msgHash);\n        const { r, s } = _sig;\n        const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n        const is = invN(s); // s^-1\n        const u1 = modN(h * is); // u1 = hs^-1 mod n\n        const u2 = modN(r * is); // u2 = rs^-1 mod n\n        const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n        if (!R)\n            return false;\n        const v = modN(R.x);\n        return v === r;\n    }\n    return {\n        CURVE,\n        getPublicKey,\n        getSharedSecret,\n        sign,\n        verify,\n        ProjectivePoint: Point,\n        Signature,\n        utils,\n    };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n    // Generic implementation\n    const q = Fp.ORDER;\n    let l = _0n;\n    for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n        l += _1n;\n    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n    // 2n ** c1 == 2n << (c1-1)\n    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic\n    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic\n    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic\n    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic\n    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n    let sqrtRatio = (u, v) => {\n        let tv1 = c6; // 1. tv1 = c6\n        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n        // 17. for i in (c1, c1 - 1, ..., 2):\n        for (let i = c1; i > _1n; i--) {\n            let tv5 = i - _2n; // 18.    tv5 = i - 2\n            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5\n            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5\n            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1\n            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1\n            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1\n            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1\n            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)\n            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)\n        }\n        return { isValid: isQR, value: tv3 };\n    };\n    if (Fp.ORDER % _4n === _3n) {\n        // sqrt_ratio_3mod4(u, v)\n        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic\n        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n        sqrtRatio = (u, v) => {\n            let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n        };\n    }\n    // No curves uses that\n    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n    return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n    validateField(Fp);\n    if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n        throw new Error('mapToCurveSimpleSWU: invalid opts');\n    const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n    if (!Fp.isOdd)\n        throw new Error('Fp.isOdd is not implemented!');\n    // Input: u, an element of F.\n    // Output: (x, y), a point on E.\n    return (u) => {\n        // prettier-ignore\n        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n        tv1 = Fp.sqr(u); // 1.  tv1 = u^2\n        tv1 = Fp.mul(tv1, opts.Z); // 2.  tv1 = Z * tv1\n        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2\n        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1\n        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1\n        tv3 = Fp.mul(tv3, opts.B); // 6.  tv3 = B * tv3\n        tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)\n        tv4 = Fp.mul(tv4, opts.A); // 8.  tv4 = A * tv4\n        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2\n        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n        tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n        tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3\n        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1\n        y = Fp.mul(y, value); // 20.   y = y * y1\n        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)\n        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)\n        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)\n        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)\n        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4\n        return { x, y };\n    };\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from \"./abstract/weierstrass.js\";\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n    return {\n        hash,\n        hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n        randomBytes,\n    };\n}\nexport function createCurve(curveDef, defHash) {\n    const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n    return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","/**\n * Internal module for NIST P256, P384, P521 curves.\n * Do not use for now.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher } from \"./abstract/hash-to-curve.js\";\nimport { Field } from \"./abstract/modular.js\";\nimport { mapToCurveSimpleSWU } from \"./abstract/weierstrass.js\";\nconst Fp256 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst p256_a = Fp256.create(BigInt('-3'));\nconst p256_b = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n/**\n * secp256r1 curve, ECDSA and ECDH methods.\n * Field: `2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n`\n */\n// prettier-ignore\nexport const p256 = createCurve({\n    a: p256_a,\n    b: p256_b,\n    Fp: Fp256,\n    n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n    Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n    Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n    h: BigInt(1),\n    lowS: false\n}, sha256);\n/** Alias to p256. */\nexport const secp256r1 = p256;\nconst p256_mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp256, {\n    A: p256_a,\n    B: p256_b,\n    Z: Fp256.create(BigInt('-10')),\n}))();\n/** Hashing / encoding to p256 points / field. RFC 9380 methods. */\nexport const p256_hasher = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => p256_mapSWU(scalars[0]), {\n    DST: 'P256_XMD:SHA-256_SSWU_RO_',\n    encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n    p: Fp256.ORDER,\n    m: 1,\n    k: 128,\n    expand: 'xmd',\n    hash: sha256,\n}))();\n// Field over which we'll do calculations.\nconst Fp384 = Field(BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'));\nconst p384_a = Fp384.create(BigInt('-3'));\n// prettier-ignore\nconst p384_b = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n/**\n * secp384r1 curve, ECDSA and ECDH methods.\n * Field: `2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n`.\n * */\n// prettier-ignore\nexport const p384 = createCurve({\n    a: p384_a,\n    b: p384_b,\n    Fp: Fp384,\n    n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n    Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n    Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n    h: BigInt(1),\n    lowS: false\n}, sha384);\n/** Alias to p384. */\nexport const secp384r1 = p384;\nconst p384_mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp384, {\n    A: p384_a,\n    B: p384_b,\n    Z: Fp384.create(BigInt('-12')),\n}))();\n/** Hashing / encoding to p384 points / field. RFC 9380 methods. */\nexport const p384_hasher = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => p384_mapSWU(scalars[0]), {\n    DST: 'P384_XMD:SHA-384_SSWU_RO_',\n    encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n    p: Fp384.ORDER,\n    m: 1,\n    k: 192,\n    expand: 'xmd',\n    hash: sha384,\n}))();\n// Field over which we'll do calculations.\nconst Fp521 = Field(BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'));\nconst p521_a = Fp521.create(BigInt('-3'));\nconst p521_b = BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00');\n/**\n * NIST secp521r1 aka p521 curve, ECDSA and ECDH methods.\n * Field: `2n**521n - 1n`.\n */\n// prettier-ignore\nexport const p521 = createCurve({\n    a: p521_a,\n    b: p521_b,\n    Fp: Fp521,\n    n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n    Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n    Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n    h: BigInt(1),\n    lowS: false,\n    allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\n/** Alias to p521. */\nexport const secp521r1 = p521;\nconst p521_mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp521, {\n    A: p521_a,\n    B: p521_b,\n    Z: Fp521.create(BigInt('-4')),\n}))();\n/** Hashing / encoding to p521 points / field. RFC 9380 methods. */\nexport const p521_hasher = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => p521_mapSWU(scalars[0]), {\n    DST: 'P521_XMD:SHA-512_SSWU_RO_',\n    encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n    p: Fp521.ORDER,\n    m: 1,\n    k: 256,\n    expand: 'xmd',\n    hash: sha512,\n}))();\n//# sourceMappingURL=nist.js.map","import * as Schema from \"effect/Schema\";\n\nexport const DpopPublicJwk = Schema.Struct({\n  kty: Schema.Literal(\"EC\"),\n  crv: Schema.Literal(\"P-256\"),\n  x: Schema.String.check(Schema.isNonEmpty()),\n  y: Schema.String.check(Schema.isNonEmpty()),\n});\nexport type DpopPublicJwk = typeof DpopPublicJwk.Type;\n\nexport function normalizeDpopHtu(url: string): string | null {\n  try {\n    const parsed = new URL(url);\n    parsed.hash = \"\";\n    parsed.search = \"\";\n    return parsed.toString();\n  } catch {\n    return null;\n  }\n}\n","function isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function stableStringify(value: unknown): string {\n  if (Array.isArray(value)) {\n    return `[${value.map(stableStringify).join(\",\")}]`;\n  }\n  if (isRecord(value)) {\n    return `{${Object.entries(value)\n      .filter(([, entryValue]) => entryValue !== undefined)\n      .sort(([left], [right]) => left.localeCompare(right))\n      .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`)\n      .join(\",\")}}`;\n  }\n  return JSON.stringify(value) ?? \"null\";\n}\n","import { p256 } from \"@noble/curves/nist\";\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { DpopPublicJwk as DpopPublicJwkSchema, normalizeDpopHtu } from \"./dpopCommon.ts\";\nimport type { DpopPublicJwk as DpopPublicJwkType } from \"./dpopCommon.ts\";\nimport { stableStringify } from \"./relaySigning.ts\";\n\nconst DPOP_TYP = \"dpop+jwt\";\nconst DPOP_ALG = \"ES256\";\nconst DEFAULT_MAX_AGE_SECONDS = 300;\n\nexport const DpopPublicJwk = DpopPublicJwkSchema;\nexport type DpopPublicJwk = DpopPublicJwkType;\nexport { normalizeDpopHtu };\n\nconst DpopJwtHeaderPublicJwk = Schema.Struct({\n  ...DpopPublicJwkSchema.fields,\n  d: Schema.optionalKey(Schema.Never),\n});\n\nconst DpopJwtHeaderJson = Schema.fromJsonString(\n  Schema.Struct({\n    typ: Schema.Literal(DPOP_TYP),\n    alg: Schema.Literal(DPOP_ALG),\n    jwk: DpopJwtHeaderPublicJwk,\n  }),\n);\nconst decodeDpopJwtHeaderJson = Schema.decodeUnknownOption(DpopJwtHeaderJson);\n\nconst DpopJwtPayloadJson = Schema.fromJsonString(\n  Schema.Struct({\n    htm: Schema.String.check(Schema.isNonEmpty()),\n    htu: Schema.String.check(Schema.isNonEmpty()),\n    jti: Schema.String.check(Schema.isNonEmpty()),\n    iat: Schema.Int,\n    ath: Schema.optionalKey(Schema.String),\n  }),\n);\nconst decodeDpopJwtPayloadJson = Schema.decodeUnknownOption(DpopJwtPayloadJson);\n\nexport type DpopVerificationResult =\n  | {\n      readonly ok: true;\n      readonly thumbprint: string;\n      readonly jti: string;\n      readonly iat: number;\n    }\n  | {\n      readonly ok: false;\n      readonly reason: string;\n    };\n\nfunction base64UrlToBytes(value: string): Uint8Array {\n  return Result.getOrThrow(Encoding.decodeBase64Url(value));\n}\n\nfunction decodeBase64UrlDpopJwtHeader(value: string) {\n  return decodeDpopJwtHeaderJson(Result.getOrThrow(Encoding.decodeBase64UrlString(value)));\n}\n\nfunction decodeBase64UrlDpopJwtPayload(value: string) {\n  return decodeDpopJwtPayloadJson(Result.getOrThrow(Encoding.decodeBase64UrlString(value)));\n}\n\nfunction dpopThumbprintInput(jwk: DpopPublicJwkType): string {\n  return stableStringify({\n    crv: jwk.crv,\n    kty: jwk.kty,\n    x: jwk.x,\n    y: jwk.y,\n  });\n}\n\nexport function computeDpopJwkThumbprint(jwk: DpopPublicJwkType): string {\n  return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));\n}\n\nexport function computeDpopAccessTokenHash(accessToken: string): string {\n  return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(accessToken)));\n}\n\nfunction publicKeyBytesFromJwk(jwk: DpopPublicJwkType): Uint8Array {\n  const x = base64UrlToBytes(jwk.x);\n  const y = base64UrlToBytes(jwk.y);\n  if (x.length !== 32 || y.length !== 32) {\n    throw new Error(\"Invalid P-256 public key coordinate length.\");\n  }\n  const publicKey = new Uint8Array(65);\n  publicKey[0] = 0x04;\n  publicKey.set(x, 1);\n  publicKey.set(y, 33);\n  return publicKey;\n}\n\nexport function verifyDpopProof(input: {\n  readonly proof: string | null | undefined;\n  readonly method: string;\n  readonly url: string;\n  readonly nowEpochSeconds: number;\n  readonly expectedThumbprint?: string;\n  readonly expectedAccessToken?: string;\n  readonly maxAgeSeconds?: number;\n}): DpopVerificationResult {\n  if (!input.proof?.trim()) {\n    return { ok: false, reason: \"Missing DPoP proof.\" };\n  }\n\n  const parts = input.proof.split(\".\");\n  if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {\n    return { ok: false, reason: \"Invalid DPoP compact JWT.\" };\n  }\n\n  try {\n    const header = decodeBase64UrlDpopJwtHeader(parts[0]);\n    const payload = decodeBase64UrlDpopJwtPayload(parts[1]);\n    if (Option.isNone(header)) {\n      return { ok: false, reason: \"Invalid DPoP JWT header.\" };\n    }\n    if (Option.isNone(payload)) {\n      return { ok: false, reason: \"Invalid DPoP JWT payload.\" };\n    }\n\n    const thumbprint = computeDpopJwkThumbprint(header.value.jwk);\n    if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {\n      return { ok: false, reason: \"DPoP key thumbprint mismatch.\" };\n    }\n    if (payload.value.htm.toUpperCase() !== input.method.toUpperCase()) {\n      return { ok: false, reason: \"DPoP method mismatch.\" };\n    }\n    const normalizedHtu = normalizeDpopHtu(input.url);\n    if (normalizedHtu === null || payload.value.htu !== normalizedHtu) {\n      return { ok: false, reason: \"DPoP URL mismatch.\" };\n    }\n    if (input.expectedAccessToken) {\n      const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);\n      if (payload.value.ath !== expectedAth) {\n        return { ok: false, reason: \"DPoP access token hash mismatch.\" };\n      }\n    }\n\n    const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;\n    if (\n      payload.value.iat > input.nowEpochSeconds + 5 ||\n      input.nowEpochSeconds - payload.value.iat > maxAgeSeconds\n    ) {\n      return { ok: false, reason: \"DPoP proof is outside the allowed time window.\" };\n    }\n\n    const signature = base64UrlToBytes(parts[2]);\n    const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));\n    const verified = p256.verify(\n      signature,\n      signatureInputHash,\n      publicKeyBytesFromJwk(header.value.jwk),\n      {\n        prehash: false,\n        format: \"compact\",\n      },\n    );\n    return verified\n      ? {\n          ok: true,\n          thumbprint,\n          jti: payload.value.jti,\n          iat: payload.value.iat,\n        }\n      : { ok: false, reason: \"Invalid DPoP signature.\" };\n  } catch {\n    return { ok: false, reason: \"Invalid DPoP proof.\" };\n  }\n}\n","import { verifyDpopProof } from \"@t3tools/shared/dpop\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Option from \"effect/Option\";\nimport * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\n\nimport {\n  ServerAuthDpopReplayKeyCalculationError,\n  ServerAuthDpopReplayStateRecordError,\n  ServerAuthInvalidCredentialError,\n  type ServerAuthInternalError,\n} from \"./EnvironmentAuth.ts\";\nimport * as ServerSecretStore from \"./ServerSecretStore.ts\";\n\nexport const mapDpopReplayStoreError = (\n  error: ServerSecretStore.SecretStoreError,\n): ServerAuthInvalidCredentialError | ServerAuthInternalError =>\n  ServerSecretStore.isSecretAlreadyExistsError(error)\n    ? new ServerAuthInvalidCredentialError({\n        diagnostic: \"DPoP proof replayed.\",\n        cause: error,\n      })\n    : new ServerAuthDpopReplayStateRecordError({\n        cause: error,\n      });\n\nexport const verifyRequestDpopProof = (input: {\n  readonly request: HttpServerRequest.HttpServerRequest;\n  readonly expectedThumbprint?: string;\n  readonly expectedAccessToken?: string;\n}) =>\n  Effect.gen(function* () {\n    const proof = input.request.headers.dpop;\n    const url = HttpServerRequest.toURL(input.request);\n    if (Option.isNone(url)) {\n      return yield* new ServerAuthInvalidCredentialError({\n        diagnostic: \"Invalid DPoP request URL.\",\n      });\n    }\n    const now = yield* DateTime.now;\n    const result = verifyDpopProof({\n      proof,\n      method: input.request.method,\n      url: url.value.href,\n      nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),\n      ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),\n      ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),\n    });\n    if (!result.ok) {\n      return yield* new ServerAuthInvalidCredentialError({\n        diagnostic: result.reason,\n      });\n    }\n    const secretStore = yield* ServerSecretStore.ServerSecretStore;\n    const replayKey = yield* Crypto.Crypto.pipe(\n      Effect.flatMap((crypto) =>\n        crypto.digest(\"SHA-256\", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),\n      ),\n      Effect.map(Encoding.encodeBase64Url),\n      Effect.mapError(\n        (cause) =>\n          new ServerAuthDpopReplayKeyCalculationError({\n            cause,\n          }),\n      ),\n    );\n    yield* secretStore\n      .create(\n        `dpop-proof-${replayKey}`,\n        new TextEncoder().encode(\n          [\n            `thumbprint=${result.thumbprint}`,\n            `jti=${result.jti}`,\n            `iat=${result.iat}`,\n            `consumedAt=${DateTime.formatIso(now)}`,\n          ].join(\"\\n\"),\n        ),\n      )\n      .pipe(\n        Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>\n          Effect.fail(mapDpopReplayStoreError(error)),\n        ),\n      );\n    return result.thumbprint;\n  });\n","var __rewriteRelativeImportExtension = this && this.__rewriteRelativeImportExtension || function (path, preserveJsx) {\n  if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n    return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n      return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : d + ext + \".\" + cm.toLowerCase() + \"js\";\n    });\n  }\n  return path;\n};\n/**\n * Runs SQL migrations with `SqlClient`.\n *\n * A migrator loads numbered migration effects, records completed ids in a\n * migrations table, and runs only pending migrations in a transaction. It\n * creates the table when needed, detects duplicate ids, treats concurrent runs\n * as locked, and can dump the schema after successful migrations.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { FileSystem } from \"../../FileSystem.js\";\nimport { pipe } from \"../../Function.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Order from \"../../Order.js\";\nimport * as Client from \"./SqlClient.js\";\n/**\n * Error raised while loading, validating, locking, or running SQL migrations.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MigrationError extends /*#__PURE__*/Data.TaggedError(\"MigrationError\") {}\n/**\n * Creates a migrator that ensures the migrations table exists, runs pending\n * migrations in a transaction, and optionally dumps the schema after successful\n * migrations.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = ({\n  dumpSchema = () => Effect.void\n}) => ({\n  loader,\n  schemaDirectory,\n  table = \"effect_sql_migrations\"\n}) => Effect.gen(function* () {\n  const sql = yield* Client.SqlClient;\n  const ensureMigrationsTable = sql.onDialectOrElse({\n    mssql: () => sql`IF OBJECT_ID(N'${sql.literal(table)}', N'U') IS NULL\n  CREATE TABLE ${sql(table)} (\n    migration_id INT NOT NULL PRIMARY KEY,\n    name VARCHAR(255) NOT NULL,\n    created_at DATETIME NOT NULL DEFAULT GETDATE()\n  )`,\n    mysql: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (\n  migration_id INTEGER UNSIGNED NOT NULL,\n  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  name VARCHAR(255) NOT NULL,\n  PRIMARY KEY (migration_id)\n)`,\n    pg: () => Effect.catch(sql`select ${table}::regclass`, () => sql`CREATE TABLE ${sql(table)} (\n  migration_id integer primary key,\n  created_at timestamp with time zone not null default now(),\n  name text not null\n)`),\n    orElse: () => sql`CREATE TABLE IF NOT EXISTS ${sql(table)} (\n  migration_id integer PRIMARY KEY NOT NULL,\n  created_at datetime NOT NULL DEFAULT current_timestamp,\n  name VARCHAR(255) NOT NULL\n)`\n  });\n  const insertMigrations = rows => sql`INSERT INTO ${sql(table)} ${sql.insert(rows.map(([migration_id, name]) => ({\n    migration_id,\n    name\n  })))}`.withoutTransform;\n  const latestMigration = Effect.map(sql`SELECT migration_id, name, created_at FROM ${sql(table)} ORDER BY migration_id DESC`.withoutTransform, _ => Option.map(Option.fromNullishOr(_[0]), ({\n    created_at,\n    migration_id,\n    name\n  }) => ({\n    id: migration_id,\n    name,\n    createdAt: created_at\n  })));\n  const loadMigration = ([id, name, load]) => Effect.catchDefect(load, _ => Effect.fail(new MigrationError({\n    kind: \"ImportError\",\n    message: `Could not import migration \"${id}_${name}\"\\n\\n${_}`\n  }))).pipe(Effect.flatMap(_ => Effect.isEffect(_) ? Effect.succeed(_) : _.default ? Effect.succeed(_.default?.default ?? _.default) : Effect.fail(new MigrationError({\n    kind: \"ImportError\",\n    message: `Default export not found for migration \"${id}_${name}\"`\n  }))), Effect.filterOrFail(Effect.isEffect, () => new MigrationError({\n    kind: \"ImportError\",\n    message: `Default export was not an Effect for migration \"${id}_${name}\"`\n  })));\n  const runMigration = (id, name, effect) => Effect.catch(effect, error => Effect.die(new MigrationError({\n    cause: error,\n    kind: \"Failed\",\n    message: `Migration \"${id}_${name}\" failed`\n  })));\n  // === run\n  const run = Effect.gen(function* () {\n    yield* sql.onDialectOrElse({\n      pg: () => sql`LOCK TABLE ${sql(table)} IN ACCESS EXCLUSIVE MODE`,\n      orElse: () => Effect.void\n    });\n    const [latestMigrationId, current] = yield* Effect.all([Effect.map(latestMigration, Option.match({\n      onNone: () => 0,\n      onSome: _ => _.id\n    })), loader]);\n    if (new Set(current.map(([id]) => id)).size !== current.length) {\n      return yield* new MigrationError({\n        kind: \"Duplicates\",\n        message: \"Found duplicate migration id's\"\n      });\n    }\n    const required = [];\n    for (const resolved of current) {\n      const [currentId, currentName] = resolved;\n      if (currentId <= latestMigrationId) {\n        continue;\n      }\n      required.push([currentId, currentName, yield* loadMigration(resolved)]);\n    }\n    if (required.length > 0) {\n      yield* pipe(insertMigrations(required.map(([id, name]) => [id, name])), Effect.mapError(error => isConstraintConflict(error) ? new MigrationError({\n        kind: \"Locked\",\n        message: \"Migrations already running\"\n      }) : error));\n    }\n    yield* Effect.forEach(required, ([id, name, effect]) => Effect.logDebug(`Running migration`).pipe(Effect.flatMap(() => runMigration(id, name, effect)), Effect.annotateLogs(\"migration_id\", String(id)), Effect.annotateLogs(\"migration_name\", name), Effect.withSpan(`Migrator ${id}_${name}`)), {\n      discard: true\n    });\n    yield* pipe(latestMigration, Effect.flatMap(Option.match({\n      onNone: () => Effect.logDebug(`Migrations complete`),\n      onSome: _ => Effect.logDebug(`Migrations complete`).pipe(Effect.annotateLogs(\"latest_migration_id\", _.id.toString()), Effect.annotateLogs(\"latest_migration_name\", _.name))\n    })));\n    return required.map(([id, name]) => [id, name]);\n  });\n  yield* ensureMigrationsTable;\n  const completed = yield* pipe(sql.withTransaction(run), Effect.catchTag(\"MigrationError\", _ => _.kind === \"Locked\" ? Effect.as(Effect.logDebug(_.message), []) : Effect.fail(_)));\n  if (schemaDirectory && completed.length > 0) {\n    yield* dumpSchema(`${schemaDirectory}/_schema.sql`, table).pipe(Effect.catchCause(cause => Effect.logInfo(\"Could not dump schema\", cause)));\n  }\n  return completed;\n});\nconst migrationOrder = /*#__PURE__*/Order.make(([a], [b]) => Order.Number(a, b));\nconst isConstraintConflict = error => error.reason._tag === \"ConstraintError\" || error.reason._tag === \"UniqueViolation\";\n/**\n * Creates a migration loader from a glob record of dynamic import functions,\n * parsing files named `<id>_<name>.js`, `<id>_<name>.ts`,\n * `<id>_<name>.mjs`, or `<id>_<name>.mts` and sorting migrations by id.\n *\n * @category loaders\n * @since 4.0.0\n */\nexport const fromGlob = migrations => pipe(Object.keys(migrations), Arr.flatMapNullishOr(_ => _.match(/^(?:.*\\/)?(\\d+)_([^.]+)\\.(js|ts|mjs|mts)$/)), Arr.map(([key, id, name]) => [Number(id), name, Effect.promise(() => migrations[key]())]), Arr.sort(migrationOrder), Effect.succeed);\n/**\n * Creates a migration loader from a Babel-style glob record, parsing keys such\n * as `_<id>_<name>Js`, `_<id>_<name>Ts`, `_<id>_<name>Mjs`, or\n * `_<id>_<name>Mts` and sorting migrations by id.\n *\n * @category loaders\n * @since 4.0.0\n */\nexport const fromBabelGlob = migrations => pipe(Object.keys(migrations), Arr.flatMapNullishOr(_ => _.match(/^_(\\d+)_([^.]+?)(Js|Ts|Mjs|Mts)?$/)), Arr.map(([key, id, name]) => [Number(id), name, Effect.succeed(migrations[key])]), Arr.sort(migrationOrder), Effect.succeed);\n/**\n * Creates a migration loader from a record of migration effects keyed by\n * `<id>_<name>`, sorted by migration id.\n *\n * @category loaders\n * @since 4.0.0\n */\nexport const fromRecord = migrations => pipe(Object.keys(migrations), Arr.flatMapNullishOr(_ => _.match(/^(\\d+)_(.+)$/)), Arr.map(([key, id, name]) => [Number(id), name, Effect.succeed(migrations[key])]), Arr.sort(migrationOrder), Effect.succeed);\n/**\n * Creates a migration loader that reads a directory with `FileSystem`, imports\n * files named `<id>_<name>.js`, `<id>_<name>.ts`,\n * `<id>_<name>.mjs`, or `<id>_<name>.mts`, and sorts migrations by id.\n *\n * @category loaders\n * @since 4.0.0\n */\nexport const fromFileSystem = /*#__PURE__*/Effect.fnUntraced(function* (directory) {\n  const Fs = yield* FileSystem;\n  const files = yield* Effect.mapError(Fs.readDirectory(directory), cause => new MigrationError({\n    kind: \"Failed\",\n    cause,\n    message: \"Failed to read migrations directory\"\n  }));\n  return files.map(file => Option.fromNullishOr(file.match(/^(?:.*\\/)?(\\d+)_([^.]+)\\.(js|ts|mjs|mts)$/))).flatMap(Option.match({\n    onNone: () => [],\n    onSome: ([basename, id, name]) => [[Number(id), name, Effect.promise(() => import(__rewriteRelativeImportExtension(/* @vite-ignore */\n    /* webpackIgnore: true */\n    `${directory}/${basename}`)))]]\n  })).sort(([a], [b]) => a - b);\n});\n//# sourceMappingURL=Migrator.js.map","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS orchestration_events (\n      sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n      event_id TEXT NOT NULL UNIQUE,\n      aggregate_kind TEXT NOT NULL,\n      stream_id TEXT NOT NULL,\n      stream_version INTEGER NOT NULL,\n      event_type TEXT NOT NULL,\n      occurred_at TEXT NOT NULL,\n      command_id TEXT,\n      causation_event_id TEXT,\n      correlation_id TEXT,\n      actor_kind TEXT NOT NULL,\n      payload_json TEXT NOT NULL,\n      metadata_json TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE UNIQUE INDEX IF NOT EXISTS idx_orch_events_stream_version\n    ON orchestration_events(aggregate_kind, stream_id, stream_version)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_events_stream_sequence\n    ON orchestration_events(aggregate_kind, stream_id, sequence)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_events_command_id\n    ON orchestration_events(command_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_events_correlation_id\n    ON orchestration_events(correlation_id)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS orchestration_command_receipts (\n      command_id TEXT PRIMARY KEY,\n      aggregate_kind TEXT NOT NULL,\n      aggregate_id TEXT NOT NULL,\n      accepted_at TEXT NOT NULL,\n      result_sequence INTEGER NOT NULL,\n      status TEXT NOT NULL,\n      error TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_command_receipts_aggregate\n    ON orchestration_command_receipts(aggregate_kind, aggregate_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_command_receipts_sequence\n    ON orchestration_command_receipts(result_sequence)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS checkpoint_diff_blobs (\n      thread_id TEXT NOT NULL,\n      from_turn_count INTEGER NOT NULL,\n      to_turn_count INTEGER NOT NULL,\n      diff TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      UNIQUE (thread_id, from_turn_count, to_turn_count)\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_checkpoint_diff_blobs_thread_to_turn\n    ON checkpoint_diff_blobs(thread_id, to_turn_count)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS provider_session_runtime (\n      thread_id TEXT PRIMARY KEY,\n      provider_name TEXT NOT NULL,\n      adapter_key TEXT NOT NULL,\n      runtime_mode TEXT NOT NULL DEFAULT 'full-access',\n      status TEXT NOT NULL,\n      last_seen_at TEXT NOT NULL,\n      resume_cursor_json TEXT,\n      runtime_payload_json TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_status\n    ON provider_session_runtime(status)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_provider\n    ON provider_session_runtime(provider_name)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_projects (\n      project_id TEXT PRIMARY KEY,\n      title TEXT NOT NULL,\n      workspace_root TEXT NOT NULL,\n      default_model TEXT,\n      scripts_json TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL,\n      deleted_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_threads (\n      thread_id TEXT PRIMARY KEY,\n      project_id TEXT NOT NULL,\n      title TEXT NOT NULL,\n      model TEXT NOT NULL,\n      branch TEXT,\n      worktree_path TEXT,\n      latest_turn_id TEXT,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL,\n      deleted_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_messages (\n      message_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      role TEXT NOT NULL,\n      text TEXT NOT NULL,\n      is_streaming INTEGER NOT NULL,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_activities (\n      activity_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      tone TEXT NOT NULL,\n      kind TEXT NOT NULL,\n      summary TEXT NOT NULL,\n      payload_json TEXT NOT NULL,\n      created_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_sessions (\n      thread_id TEXT PRIMARY KEY,\n      status TEXT NOT NULL,\n      provider_name TEXT,\n      provider_session_id TEXT,\n      provider_thread_id TEXT,\n      active_turn_id TEXT,\n      last_error TEXT,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_turns (\n      row_id INTEGER PRIMARY KEY AUTOINCREMENT,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      pending_message_id TEXT,\n      assistant_message_id TEXT,\n      state TEXT NOT NULL,\n      requested_at TEXT NOT NULL,\n      started_at TEXT,\n      completed_at TEXT,\n      checkpoint_turn_count INTEGER,\n      checkpoint_ref TEXT,\n      checkpoint_status TEXT,\n      checkpoint_files_json TEXT NOT NULL,\n      UNIQUE (thread_id, turn_id),\n      UNIQUE (thread_id, checkpoint_turn_count)\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_pending_approvals (\n      request_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      status TEXT NOT NULL,\n      decision TEXT,\n      created_at TEXT NOT NULL,\n      resolved_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_state (\n      projector TEXT PRIMARY KEY,\n      last_applied_sequence INTEGER NOT NULL,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_projects_updated_at\n    ON projection_projects(updated_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_project_id\n    ON projection_threads(project_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created\n    ON projection_thread_messages(thread_id, created_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_created\n    ON projection_thread_activities(thread_id, created_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_provider_session\n    ON projection_thread_sessions(provider_session_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_requested\n    ON projection_turns(thread_id, requested_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_checkpoint_completed\n    ON projection_turns(thread_id, checkpoint_turn_count, completed_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_pending_approvals_thread_status\n    ON projection_pending_approvals(thread_id, status)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nconst DEFAULT_RUNTIME_MODE = \"full-access\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n      ALTER TABLE projection_thread_sessions\n      ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'\n    `;\n\n  yield* sql`\n    UPDATE projection_thread_sessions\n    SET runtime_mode = ${DEFAULT_RUNTIME_MODE}\n    WHERE runtime_mode IS NULL\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_thread_messages\n    ADD COLUMN attachments_json TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_thread_activities\n    ADD COLUMN sequence INTEGER\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence\n    ON projection_thread_activities(thread_id, sequence)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.asVoid(SqlClient.SqlClient);\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET runtime_mode = 'full-access'\n    WHERE runtime_mode IS NULL\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(payload_json, '$.runtimeMode', 'full-access')\n    WHERE event_type = 'thread.created'\n      AND json_type(payload_json, '$.runtimeMode') IS NULL\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN interaction_mode TEXT NOT NULL DEFAULT 'default'\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_proposed_plans (\n      plan_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      plan_markdown TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_proposed_plans_thread_created\n    ON projection_thread_proposed_plans(thread_id, created_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_thread_proposed_plans\n    ADD COLUMN implemented_at TEXT\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_thread_proposed_plans\n    ADD COLUMN implementation_thread_id TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_turns\n    ADD COLUMN source_proposed_plan_thread_id TEXT\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_turns\n    ADD COLUMN source_proposed_plan_id TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_projects\n    ADD COLUMN default_model_selection_json TEXT\n  `;\n\n  yield* sql`\n    UPDATE projection_projects\n    SET default_model_selection_json = CASE\n      WHEN default_model IS NULL THEN NULL\n      ELSE json_object(\n        'provider',\n        CASE\n          WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'\n          ELSE 'codex'\n        END,\n        'model',\n        default_model\n      )\n    END\n    WHERE default_model_selection_json IS NULL\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN model_selection_json TEXT\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET model_selection_json = json_object(\n      'provider',\n      COALESCE(\n        (\n          SELECT provider_name\n          FROM projection_thread_sessions\n          WHERE projection_thread_sessions.thread_id = projection_threads.thread_id\n        ),\n        CASE\n          WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'\n          ELSE 'codex'\n        END,\n        'codex'\n      ),\n      'model',\n      model\n    )\n    WHERE model_selection_json IS NULL\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_projects\n    DROP COLUMN default_model\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    DROP COLUMN model\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = CASE\n      WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove(\n        json_set(payload_json, '$.defaultModelSelection', json('null')),\n        '$.defaultProvider',\n        '$.defaultModel',\n        '$.defaultModelOptions'\n      )\n      ELSE json_remove(\n        json_set(\n          payload_json,\n          '$.defaultModelSelection',\n          json_patch(\n            json_object(\n              'provider',\n              CASE\n                WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL\n                THEN json_extract(payload_json, '$.defaultProvider')\n                WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'\n                THEN 'claudeAgent'\n                ELSE 'codex'\n              END,\n              'model',\n              json_extract(payload_json, '$.defaultModel')\n            ),\n              CASE\n                WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'\n                WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL\n                  OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL\n                THEN CASE\n                  WHEN (\n                  CASE\n                    WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL\n                    THEN json_extract(payload_json, '$.defaultProvider')\n                    WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'\n                    THEN 'claudeAgent'\n                    ELSE 'codex'\n                    END\n                  ) = 'claudeAgent'\n                  THEN CASE\n                    WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))\n                    )\n                    WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.codex'))\n                    )\n                    ELSE '{}'\n                  END\n                  ELSE CASE\n                    WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.codex'))\n                    )\n                    WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))\n                    )\n                    ELSE '{}'\n                  END\n                END\n              ELSE json_object(\n                'options',\n                json(json_extract(payload_json, '$.defaultModelOptions'))\n              )\n            END\n          )\n        ),\n        '$.defaultProvider',\n        '$.defaultModel',\n        '$.defaultModelOptions'\n      )\n    END\n    WHERE event_type IN ('project.created', 'project.meta-updated')\n      AND json_type(payload_json, '$.defaultModelSelection') IS NULL\n      AND json_type(payload_json, '$.defaultModel') IS NOT NULL\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_remove(\n      json_set(\n        payload_json,\n        '$.modelSelection',\n        json_patch(\n          json_object(\n            'provider',\n            CASE\n              WHEN json_extract(payload_json, '$.provider') IS NOT NULL\n              THEN json_extract(payload_json, '$.provider')\n              WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'\n              THEN 'claudeAgent'\n              ELSE 'codex'\n            END,\n            'model',\n            json_extract(payload_json, '$.model')\n          ),\n          CASE\n            WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}'\n            WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL\n              OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL\n            THEN CASE\n              WHEN (\n                CASE\n                  WHEN json_extract(payload_json, '$.provider') IS NOT NULL\n                  THEN json_extract(payload_json, '$.provider')\n                  WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'\n                  THEN 'claudeAgent'\n                  ELSE 'codex'\n                  END\n              ) = 'claudeAgent'\n              THEN CASE\n                WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.claudeAgent'))\n                )\n                WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.codex'))\n                )\n                ELSE '{}'\n              END\n              ELSE CASE\n                WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.codex'))\n                )\n                WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.claudeAgent'))\n                )\n                ELSE '{}'\n              END\n            END\n            ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions')))\n          END\n        )\n      ),\n      '$.provider',\n      '$.model',\n      '$.modelOptions'\n    )\n    WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested')\n      AND json_type(payload_json, '$.modelSelection') IS NULL\n      AND json_type(payload_json, '$.model') IS NOT NULL\n  `;\n\n  // Backfill thread.created events that predate the model field entirely\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(\n      payload_json,\n      '$.modelSelection',\n      json(json_object('provider', 'codex', 'model', 'gpt-5.4'))\n    )\n    WHERE event_type = 'thread.created'\n      AND json_type(payload_json, '$.modelSelection') IS NULL\n      AND json_type(payload_json, '$.model') IS NULL\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (columns.some((column) => column.name === \"archived_at\")) {\n    return;\n  }\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN archived_at TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at\n    ON projection_threads(project_id, archived_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at\n    ON projection_projects(workspace_root, deleted_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created\n    ON projection_threads(project_id, deleted_at, created_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS auth_pairing_links (\n      id TEXT PRIMARY KEY,\n      credential TEXT NOT NULL UNIQUE,\n      method TEXT NOT NULL,\n      role TEXT NOT NULL,\n      subject TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      consumed_at TEXT,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_auth_pairing_links_active\n    ON auth_pairing_links(revoked_at, consumed_at, expires_at)\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS auth_sessions (\n      session_id TEXT PRIMARY KEY,\n      subject TEXT NOT NULL,\n      role TEXT NOT NULL,\n      method TEXT NOT NULL,\n      issued_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_auth_sessions_active\n    ON auth_sessions(revoked_at, expires_at, issued_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const pairingLinkColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_pairing_links)\n  `;\n  if (!pairingLinkColumns.some((column) => column.name === \"label\")) {\n    yield* sql`\n      ALTER TABLE auth_pairing_links\n      ADD COLUMN label TEXT\n    `;\n  }\n\n  const sessionColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_sessions)\n  `;\n\n  if (!sessionColumns.some((column) => column.name === \"client_label\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_label TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_ip_address\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_ip_address TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_user_agent\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_user_agent TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_device_type\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_device_type TEXT NOT NULL DEFAULT 'unknown'\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_os\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_os TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_browser\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_browser TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const sessionColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_sessions)\n  `;\n\n  if (!sessionColumns.some((column) => column.name === \"last_connected_at\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN last_connected_at TEXT\n    `;\n  }\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN latest_user_message_at TEXT\n  `.pipe(Effect.catch(() => Effect.void));\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN pending_approval_count INTEGER NOT NULL DEFAULT 0\n  `.pipe(Effect.catch(() => Effect.void));\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN pending_user_input_count INTEGER NOT NULL DEFAULT 0\n  `.pipe(Effect.catch(() => Effect.void));\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN has_actionable_proposed_plan INTEGER NOT NULL DEFAULT 0\n  `.pipe(Effect.catch(() => Effect.void));\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    INSERT OR IGNORE INTO projection_pending_approvals (\n      request_id,\n      thread_id,\n      turn_id,\n      status,\n      decision,\n      created_at,\n      resolved_at\n    )\n    SELECT\n      requested.request_id,\n      requested.thread_id,\n      requested.turn_id,\n      'pending',\n      NULL,\n      requested.created_at,\n      NULL\n    FROM (\n      SELECT\n        json_extract(payload_json, '$.requestId') AS request_id,\n        thread_id,\n        turn_id,\n        created_at,\n        ROW_NUMBER() OVER (\n          PARTITION BY json_extract(payload_json, '$.requestId')\n          ORDER BY created_at ASC, activity_id ASC\n        ) AS row_number\n      FROM projection_thread_activities\n      WHERE kind = 'approval.requested'\n        AND json_extract(payload_json, '$.requestId') IS NOT NULL\n    ) AS requested\n    WHERE requested.row_number = 1\n  `;\n\n  yield* sql`\n    WITH latest_resolutions AS (\n      SELECT\n        resolved.request_id,\n        resolved.resolved_at,\n        resolved.decision\n      FROM (\n        SELECT\n          json_extract(payload_json, '$.requestId') AS request_id,\n          created_at AS resolved_at,\n          CASE\n            WHEN json_extract(payload_json, '$.decision') IN (\n              'accept',\n              'acceptForSession',\n              'decline',\n              'cancel'\n            )\n            THEN json_extract(payload_json, '$.decision')\n            ELSE NULL\n          END AS decision,\n          ROW_NUMBER() OVER (\n            PARTITION BY json_extract(payload_json, '$.requestId')\n            ORDER BY created_at DESC, activity_id DESC\n          ) AS row_number\n        FROM projection_thread_activities\n        WHERE kind = 'approval.resolved'\n          AND json_extract(payload_json, '$.requestId') IS NOT NULL\n      ) AS resolved\n      WHERE resolved.row_number = 1\n    )\n    UPDATE projection_pending_approvals\n    SET\n      status = 'resolved',\n      decision = (\n        SELECT latest_resolutions.decision\n        FROM latest_resolutions\n        WHERE latest_resolutions.request_id = projection_pending_approvals.request_id\n      ),\n      resolved_at = (\n        SELECT latest_resolutions.resolved_at\n        FROM latest_resolutions\n        WHERE latest_resolutions.request_id = projection_pending_approvals.request_id\n      )\n    WHERE EXISTS (\n      SELECT 1\n      FROM latest_resolutions\n      WHERE latest_resolutions.request_id = projection_pending_approvals.request_id\n    )\n  `;\n\n  yield* sql`\n    WITH latest_response_events AS (\n      SELECT\n        response.request_id,\n        response.resolved_at,\n        response.decision\n      FROM (\n        SELECT\n          json_extract(payload_json, '$.requestId') AS request_id,\n          occurred_at AS resolved_at,\n          CASE\n            WHEN json_extract(payload_json, '$.decision') IN (\n              'accept',\n              'acceptForSession',\n              'decline',\n              'cancel'\n            )\n            THEN json_extract(payload_json, '$.decision')\n            ELSE NULL\n          END AS decision,\n          ROW_NUMBER() OVER (\n            PARTITION BY json_extract(payload_json, '$.requestId')\n            ORDER BY occurred_at DESC, sequence DESC\n          ) AS row_number\n        FROM orchestration_events\n        WHERE event_type = 'thread.approval-response-requested'\n          AND json_extract(payload_json, '$.requestId') IS NOT NULL\n      ) AS response\n      WHERE response.row_number = 1\n    )\n    UPDATE projection_pending_approvals\n    SET\n      status = 'resolved',\n      decision = (\n        SELECT latest_response_events.decision\n        FROM latest_response_events\n        WHERE latest_response_events.request_id = projection_pending_approvals.request_id\n      ),\n      resolved_at = (\n        SELECT latest_response_events.resolved_at\n        FROM latest_response_events\n        WHERE latest_response_events.request_id = projection_pending_approvals.request_id\n      )\n    WHERE EXISTS (\n      SELECT 1\n      FROM latest_response_events\n      WHERE latest_response_events.request_id = projection_pending_approvals.request_id\n    )\n  `;\n\n  yield* sql`\n    WITH latest_stale_failures AS (\n      SELECT\n        failure.request_id,\n        failure.resolved_at\n      FROM (\n        SELECT\n          json_extract(payload_json, '$.requestId') AS request_id,\n          created_at AS resolved_at,\n          ROW_NUMBER() OVER (\n            PARTITION BY json_extract(payload_json, '$.requestId')\n            ORDER BY created_at DESC, activity_id DESC\n          ) AS row_number\n        FROM projection_thread_activities\n        WHERE kind = 'provider.approval.respond.failed'\n          AND json_extract(payload_json, '$.requestId') IS NOT NULL\n          AND (\n            lower(COALESCE(json_extract(payload_json, '$.detail'), ''))\n              LIKE '%stale pending approval request%'\n            OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))\n              LIKE '%unknown pending approval request%'\n            OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))\n              LIKE '%unknown pending permission request%'\n          )\n      ) AS failure\n      WHERE failure.row_number = 1\n    )\n    UPDATE projection_pending_approvals\n    SET\n      status = 'resolved',\n      decision = NULL,\n      resolved_at = (\n        SELECT latest_stale_failures.resolved_at\n        FROM latest_stale_failures\n        WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id\n      )\n    WHERE status = 'pending'\n      AND EXISTS (\n        SELECT 1\n        FROM latest_stale_failures\n        WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id\n      )\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET\n      latest_user_message_at = (\n        SELECT MAX(message.created_at)\n        FROM projection_thread_messages AS message\n        WHERE message.thread_id = projection_threads.thread_id\n          AND message.role = 'user'\n      ),\n      pending_approval_count = COALESCE((\n        SELECT COUNT(*)\n        FROM projection_pending_approvals\n        WHERE projection_pending_approvals.thread_id = projection_threads.thread_id\n          AND projection_pending_approvals.status = 'pending'\n      ), 0),\n      pending_user_input_count = COALESCE((\n        WITH latest_user_input_states AS (\n          SELECT\n            latest.request_id,\n            latest.kind,\n            latest.detail\n          FROM (\n            SELECT\n              json_extract(activity.payload_json, '$.requestId') AS request_id,\n              activity.kind,\n              lower(COALESCE(json_extract(activity.payload_json, '$.detail'), '')) AS detail,\n              ROW_NUMBER() OVER (\n                PARTITION BY json_extract(activity.payload_json, '$.requestId')\n                ORDER BY activity.created_at DESC, activity.activity_id DESC\n              ) AS row_number\n            FROM projection_thread_activities AS activity\n            WHERE activity.thread_id = projection_threads.thread_id\n              AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL\n              AND activity.kind IN (\n                'user-input.requested',\n                'user-input.resolved',\n                'provider.user-input.respond.failed'\n              )\n          ) AS latest\n          WHERE latest.row_number = 1\n        )\n        SELECT COUNT(*)\n        FROM latest_user_input_states\n        WHERE latest_user_input_states.kind = 'user-input.requested'\n          OR (\n            latest_user_input_states.kind = 'provider.user-input.respond.failed'\n            AND latest_user_input_states.detail NOT LIKE '%stale pending user-input request%'\n            AND latest_user_input_states.detail NOT LIKE '%unknown pending user-input request%'\n          )\n      ), 0),\n      has_actionable_proposed_plan = COALESCE((\n        SELECT CASE\n          WHEN projection_threads.latest_turn_id IS NOT NULL\n            AND EXISTS (\n              SELECT 1\n              FROM projection_thread_proposed_plans AS latest_turn_plan_exists\n              WHERE latest_turn_plan_exists.thread_id = projection_threads.thread_id\n                AND latest_turn_plan_exists.turn_id = projection_threads.latest_turn_id\n            )\n            THEN CASE\n              WHEN (\n                SELECT latest_turn_plan.implemented_at\n                FROM projection_thread_proposed_plans AS latest_turn_plan\n                WHERE latest_turn_plan.thread_id = projection_threads.thread_id\n                  AND latest_turn_plan.turn_id = projection_threads.latest_turn_id\n                ORDER BY latest_turn_plan.updated_at DESC, latest_turn_plan.plan_id DESC\n                LIMIT 1\n              ) IS NULL\n                THEN 1\n                ELSE 0\n              END\n          WHEN EXISTS (\n            SELECT 1\n            FROM projection_thread_proposed_plans AS any_plan\n            WHERE any_plan.thread_id = projection_threads.thread_id\n          )\n            THEN CASE\n              WHEN (\n                SELECT latest_plan.implemented_at\n                FROM projection_thread_proposed_plans AS latest_plan\n                WHERE latest_plan.thread_id = projection_threads.thread_id\n                ORDER BY latest_plan.updated_at DESC, latest_plan.plan_id DESC\n                LIMIT 1\n              ) IS NULL\n                THEN 1\n                ELSE 0\n              END\n          ELSE 0\n        END\n      ), 0)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    DELETE FROM projection_pending_approvals\n    WHERE NOT EXISTS (\n      SELECT 1\n      FROM projection_thread_activities AS activity\n      WHERE activity.kind = 'approval.requested'\n        AND json_extract(activity.payload_json, '$.requestId')\n          = projection_pending_approvals.request_id\n    )\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET pending_approval_count = COALESCE((\n      SELECT COUNT(*)\n      FROM projection_pending_approvals\n      WHERE projection_pending_approvals.thread_id = projection_threads.thread_id\n        AND projection_pending_approvals.status = 'pending'\n    ), 0)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/**\n * Canonicalize `modelSelection.options` / `defaultModelSelection.options` from\n * the legacy object shape (`{ effort: \"max\", fastMode: true, ... }`) to the\n * current array-of-selections shape (`[{ id: \"effort\", value: \"max\" }, ...]`).\n *\n * Migration 016 introduced `modelSelection` with `options` stored as a\n * per-provider object. Later the schema was reshaped so that options are a\n * generic `Array<{ id, value }>` of user-selected option entries. Stored rows\n * from before the reshape still have the object shape and fail to decode.\n *\n * For each value in the legacy object:\n *   - string values are kept if non-empty after trim\n *   - boolean values are always kept (true | false)\n *   - any other value type (number, null, nested object/array) is dropped,\n *     matching the permissive client-side normalizer in composerDraftStore.\n *\n * Touched storage:\n *   - `projection_threads.model_selection_json.options`\n *   - `projection_projects.default_model_selection_json.options`\n *   - `orchestration_events.payload_json.$.modelSelection.options`\n *     (thread.created | thread.meta-updated | thread.turn-start-requested)\n *   - `orchestration_events.payload_json.$.defaultModelSelection.options`\n *     (project.created | project.meta-updated)\n */\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET model_selection_json = json_set(\n      model_selection_json,\n      '$.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(model_selection_json, '$.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE model_selection_json IS NOT NULL\n      AND json_type(model_selection_json, '$.options') = 'object'\n  `;\n\n  yield* sql`\n    UPDATE projection_projects\n    SET default_model_selection_json = json_set(\n      default_model_selection_json,\n      '$.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(default_model_selection_json, '$.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE default_model_selection_json IS NOT NULL\n      AND json_type(default_model_selection_json, '$.options') = 'object'\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(\n      payload_json,\n      '$.modelSelection.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(payload_json, '$.modelSelection.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE event_type IN (\n      'thread.created',\n      'thread.meta-updated',\n      'thread.turn-start-requested'\n    )\n      AND json_type(payload_json, '$.modelSelection.options') = 'object'\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(\n      payload_json,\n      '$.defaultModelSelection.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(payload_json, '$.defaultModelSelection.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE event_type IN ('project.created', 'project.meta-updated')\n      AND json_type(payload_json, '$.defaultModelSelection.options') = 'object'\n  `;\n});\n","/**\n * Adds the nullable `provider_instance_id` routing column to\n * `provider_session_runtime`.\n *\n * Slice D of the provider-array refactor splits \"driver kind\" from\n * \"configured instance\". Existing rows have only the driver name in\n * `provider_name`; new rows additionally carry the user-defined instance\n * routing key. The column remains nullable so legacy rows can still decode;\n * the persistence boundary is responsible for materializing a concrete\n * instance id before any hot routing path sees the binding.\n *\n * The column is nullable on purpose — backfilling it during the migration\n * would require knowing which configured instance \"owned\" each historical\n * session, and that mapping is ambiguous when the user later configures\n * multiple instances of the same driver. Keeping that compatibility at the\n * persistence boundary keeps the fallback out of active routing code.\n */\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(provider_session_runtime)\n  `;\n  if (!columns.some((column) => column.name === \"provider_instance_id\")) {\n    yield* sql`\n      ALTER TABLE provider_session_runtime\n      ADD COLUMN provider_instance_id TEXT\n    `;\n  }\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance\n    ON provider_session_runtime(provider_instance_id)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_thread_sessions)\n  `;\n  if (!columns.some((column) => column.name === \"provider_instance_id\")) {\n    yield* sql`\n      ALTER TABLE projection_thread_sessions\n      ADD COLUMN provider_instance_id TEXT\n    `;\n  }\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance\n    ON projection_thread_sessions(provider_instance_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id\n    ON projection_thread_activities(thread_id, sequence, created_at, activity_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id\n    ON projection_thread_messages(thread_id, created_at, message_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_active\n    ON projection_threads(deleted_at, archived_at, project_id, created_at, thread_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_archived\n    ON projection_threads(deleted_at, archived_at, project_id, thread_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/**\n * This is an intentional alpha cutover: role-bearing credentials and sessions\n * cannot safely be assigned new capabilities implicitly.\n */\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`DROP TABLE IF EXISTS auth_pairing_links`;\n  yield* sql`DROP TABLE IF EXISTS auth_sessions`;\n\n  yield* sql`\n    CREATE TABLE auth_pairing_links (\n      id TEXT PRIMARY KEY,\n      credential TEXT NOT NULL UNIQUE,\n      method TEXT NOT NULL,\n      scopes TEXT NOT NULL,\n      subject TEXT NOT NULL,\n      label TEXT,\n      created_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      consumed_at TEXT,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX idx_auth_pairing_links_active\n    ON auth_pairing_links(revoked_at, consumed_at, expires_at)\n  `;\n\n  yield* sql`\n    CREATE TABLE auth_sessions (\n      session_id TEXT PRIMARY KEY,\n      subject TEXT NOT NULL,\n      scopes TEXT NOT NULL,\n      method TEXT NOT NULL,\n      client_label TEXT,\n      client_ip_address TEXT,\n      client_user_agent TEXT,\n      client_device_type TEXT NOT NULL DEFAULT 'unknown',\n      client_os TEXT,\n      client_browser TEXT,\n      issued_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      last_connected_at TEXT,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX idx_auth_sessions_active\n    ON auth_sessions(revoked_at, expires_at, issued_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const pairingLinkColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_pairing_links)\n  `;\n  if (!pairingLinkColumns.some((column) => column.name === \"proof_key_thumbprint\")) {\n    yield* sql`\n      ALTER TABLE auth_pairing_links\n      ADD COLUMN proof_key_thumbprint TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"settled_override\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN settled_override TEXT\n    `;\n  }\n\n  if (!columns.some((column) => column.name === \"settled_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN settled_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"snoozed_until\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN snoozed_until TEXT\n    `;\n  }\n\n  if (!columns.some((column) => column.name === \"snoozed_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN snoozed_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"title_regeneration_request_id\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN title_regeneration_request_id TEXT\n    `;\n  }\n\n  if (!columns.some((column) => column.name === \"title_regeneration_started_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN title_regeneration_started_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"pinned_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN pinned_at TEXT\n    `;\n  }\n});\n","/**\n * MigrationsLive - Migration runner with inline loader\n *\n * Uses Migrator.make with fromRecord to define migrations inline.\n * All migrations are statically imported - no dynamic file system loading.\n *\n * Migrations run automatically when the MigrationLayer is provided,\n * ensuring the database schema is always up-to-date before the application starts.\n */\n\nimport * as Migrator from \"effect/unstable/sql/Migrator\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\n// Import all migrations statically\nimport Migration0001 from \"./Migrations/001_OrchestrationEvents.ts\";\nimport Migration0002 from \"./Migrations/002_OrchestrationCommandReceipts.ts\";\nimport Migration0003 from \"./Migrations/003_CheckpointDiffBlobs.ts\";\nimport Migration0004 from \"./Migrations/004_ProviderSessionRuntime.ts\";\nimport Migration0005 from \"./Migrations/005_Projections.ts\";\nimport Migration0006 from \"./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts\";\nimport Migration0007 from \"./Migrations/007_ProjectionThreadMessageAttachments.ts\";\nimport Migration0008 from \"./Migrations/008_ProjectionThreadActivitySequence.ts\";\nimport Migration0009 from \"./Migrations/009_ProviderSessionRuntimeMode.ts\";\nimport Migration0010 from \"./Migrations/010_ProjectionThreadsRuntimeMode.ts\";\nimport Migration0011 from \"./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts\";\nimport Migration0012 from \"./Migrations/012_ProjectionThreadsInteractionMode.ts\";\nimport Migration0013 from \"./Migrations/013_ProjectionThreadProposedPlans.ts\";\nimport Migration0014 from \"./Migrations/014_ProjectionThreadProposedPlanImplementation.ts\";\nimport Migration0015 from \"./Migrations/015_ProjectionTurnsSourceProposedPlan.ts\";\nimport Migration0016 from \"./Migrations/016_CanonicalizeModelSelections.ts\";\nimport Migration0017 from \"./Migrations/017_ProjectionThreadsArchivedAt.ts\";\nimport Migration0018 from \"./Migrations/018_ProjectionThreadsArchivedAtIndex.ts\";\nimport Migration0019 from \"./Migrations/019_ProjectionSnapshotLookupIndexes.ts\";\nimport Migration0020 from \"./Migrations/020_AuthAccessManagement.ts\";\nimport Migration0021 from \"./Migrations/021_AuthSessionClientMetadata.ts\";\nimport Migration0022 from \"./Migrations/022_AuthSessionLastConnectedAt.ts\";\nimport Migration0023 from \"./Migrations/023_ProjectionThreadShellSummary.ts\";\nimport Migration0024 from \"./Migrations/024_BackfillProjectionThreadShellSummary.ts\";\nimport Migration0025 from \"./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts\";\nimport Migration0026 from \"./Migrations/026_CanonicalizeModelSelectionOptions.ts\";\nimport Migration0027 from \"./Migrations/027_ProviderSessionRuntimeInstanceId.ts\";\nimport Migration0028 from \"./Migrations/028_ProjectionThreadSessionInstanceId.ts\";\nimport Migration0029 from \"./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts\";\nimport Migration0030 from \"./Migrations/030_ProjectionThreadShellArchiveIndexes.ts\";\nimport Migration0031 from \"./Migrations/031_AuthAuthorizationScopes.ts\";\nimport Migration0032 from \"./Migrations/032_AuthPairingProofKeyThumbprint.ts\";\nimport Migration0033 from \"./Migrations/033_ProjectionThreadsSettled.ts\";\nimport Migration0034 from \"./Migrations/034_ProjectionThreadsSnoozed.ts\";\nimport Migration0035 from \"./Migrations/035_ProjectionThreadTitleRegeneration.ts\";\nimport Migration0036 from \"./Migrations/036_ProjectionThreadsPinned.ts\";\n\n/**\n * Migration loader with all migrations defined inline.\n *\n * Key format: \"{id}_{name}\" where:\n * - id: numeric migration ID (determines execution order)\n * - name: descriptive name for the migration\n *\n * Uses Migrator.fromRecord which parses the key format and\n * returns migrations sorted by ID.\n */\nexport const migrationEntries = [\n  [1, \"OrchestrationEvents\", Migration0001],\n  [2, \"OrchestrationCommandReceipts\", Migration0002],\n  [3, \"CheckpointDiffBlobs\", Migration0003],\n  [4, \"ProviderSessionRuntime\", Migration0004],\n  [5, \"Projections\", Migration0005],\n  [6, \"ProjectionThreadSessionRuntimeModeColumns\", Migration0006],\n  [7, \"ProjectionThreadMessageAttachments\", Migration0007],\n  [8, \"ProjectionThreadActivitySequence\", Migration0008],\n  [9, \"ProviderSessionRuntimeMode\", Migration0009],\n  [10, \"ProjectionThreadsRuntimeMode\", Migration0010],\n  [11, \"OrchestrationThreadCreatedRuntimeMode\", Migration0011],\n  [12, \"ProjectionThreadsInteractionMode\", Migration0012],\n  [13, \"ProjectionThreadProposedPlans\", Migration0013],\n  [14, \"ProjectionThreadProposedPlanImplementation\", Migration0014],\n  [15, \"ProjectionTurnsSourceProposedPlan\", Migration0015],\n  [16, \"CanonicalizeModelSelections\", Migration0016],\n  [17, \"ProjectionThreadsArchivedAt\", Migration0017],\n  [18, \"ProjectionThreadsArchivedAtIndex\", Migration0018],\n  [19, \"ProjectionSnapshotLookupIndexes\", Migration0019],\n  [20, \"AuthAccessManagement\", Migration0020],\n  [21, \"AuthSessionClientMetadata\", Migration0021],\n  [22, \"AuthSessionLastConnectedAt\", Migration0022],\n  [23, \"ProjectionThreadShellSummary\", Migration0023],\n  [24, \"BackfillProjectionThreadShellSummary\", Migration0024],\n  [25, \"CleanupInvalidProjectionPendingApprovals\", Migration0025],\n  [26, \"CanonicalizeModelSelectionOptions\", Migration0026],\n  [27, \"ProviderSessionRuntimeInstanceId\", Migration0027],\n  [28, \"ProjectionThreadSessionInstanceId\", Migration0028],\n  [29, \"ProjectionThreadDetailOrderingIndexes\", Migration0029],\n  [30, \"ProjectionThreadShellArchiveIndexes\", Migration0030],\n  [31, \"AuthAuthorizationScopes\", Migration0031],\n  [32, \"AuthPairingProofKeyThumbprint\", Migration0032],\n  [33, \"ProjectionThreadsSettled\", Migration0033],\n  [34, \"ProjectionThreadsSnoozed\", Migration0034],\n  [35, \"ProjectionThreadTitleRegeneration\", Migration0035],\n  [36, \"ProjectionThreadsPinned\", Migration0036],\n] as const;\n\nexport const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);\n\nexport const makeMigrationLoader = (throughId?: number) =>\n  Migrator.fromRecord(\n    Object.fromEntries(\n      migrationEntries\n        .filter(([id]) => throughId === undefined || id <= throughId)\n        .map(([id, name, migration]) => [`${id}_${name}`, migration]),\n    ),\n  );\n\n/**\n * Migrator run function - no schema dumping needed\n * Uses the base Migrator.make without platform dependencies\n */\nconst run = Migrator.make({});\n\nexport interface RunMigrationsOptions {\n  readonly toMigrationInclusive?: number | undefined;\n}\n\n/**\n * Run all pending migrations.\n *\n * Creates the migrations tracking table (effect_sql_migrations) if it doesn't exist,\n * then runs any migrations with ID greater than the latest recorded migration.\n *\n * Returns array of [id, name] tuples for migrations that were run.\n *\n * @returns Effect containing array of executed migrations\n */\nexport const runMigrations = Effect.fn(\"runMigrations\")(function* ({\n  toMigrationInclusive,\n}: RunMigrationsOptions = {}) {\n  const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });\n  const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);\n  yield* migrations.length === 0\n    ? Effect.logDebug(\"Database schema is current\")\n    : Effect.log(\"Migrations ran successfully\").pipe(Effect.annotateLogs({ migrations }));\n  return executedMigrations;\n});\n\n/**\n * Layer that runs migrations when the layer is built.\n *\n * Use this to ensure migrations run before your application starts.\n * Migrations are run automatically - no separate script is needed.\n *\n * @example\n * ```typescript\n * import { MigrationsLive } from \"@acme/db/Migrations\"\n * import * as SqliteClient from \"@acme/db/SqliteClient\"\n *\n * // Migrations run automatically when SqliteClient is provided\n * const AppLayer = MigrationsLive.pipe(\n *   Layer.provideMerge(SqliteClient.layer({ filename: \"database.sqlite\" }))\n * )\n * ```\n */\nexport const MigrationsLive = Layer.effectDiscard(runMigrations());\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport { runMigrations } from \"../Migrations.ts\";\nimport { ServerConfig } from \"../../config.ts\";\n\ntype RuntimeSqliteLayerConfig = {\n  readonly filename: string;\n  readonly spanAttributes?: Record<string, unknown>;\n};\n\ntype Loader = {\n  layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient, SqlError>;\n};\nconst defaultSqliteClientLoaders = {\n  bun: () => import(\"@effect/sql-sqlite-bun/SqliteClient\"),\n  node: () => import(\"../NodeSqliteClient.ts\"),\n} satisfies Record<string, () => Promise<Loader>>;\n\nconst makeRuntimeSqliteLayer = Effect.fn(\"makeRuntimeSqliteLayer\")(function* (\n  config: RuntimeSqliteLayerConfig,\n) {\n  const runtime = process.versions.bun !== undefined ? \"bun\" : \"node\";\n  const loader = defaultSqliteClientLoaders[runtime];\n  const clientModule = yield* Effect.promise<Loader>(loader);\n  return clientModule.layer(config);\n}, Layer.unwrap);\n\nconst setup = Layer.effectDiscard(\n  Effect.gen(function* () {\n    const sql = yield* SqlClient.SqlClient;\n    yield* sql`PRAGMA foreign_keys = ON;`;\n    yield* sql`PRAGMA journal_mode = WAL;`;\n    yield* runMigrations();\n  }),\n);\n\nexport const makeSqlitePersistenceLive = Effect.fn(\"makeSqlitePersistenceLive\")(function* (\n  dbPath: string,\n) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });\n\n  return Layer.provideMerge(\n    setup,\n    makeRuntimeSqliteLayer({\n      filename: dbPath,\n      spanAttributes: {\n        \"db.name\": path.basename(dbPath),\n        \"service.name\": \"t3-server\",\n      },\n    }),\n  );\n}, Layer.unwrap);\n\nexport const SqlitePersistenceMemory = Layer.provideMerge(\n  setup,\n  makeRuntimeSqliteLayer({ filename: \":memory:\" }),\n);\n\nexport const layerConfig = Layer.unwrap(\n  Effect.gen(function* () {\n    const { dbPath } = yield* ServerConfig;\n    return makeSqlitePersistenceLive(dbPath);\n  }),\n);\n","import {\n  AuthAccessTokenType,\n  AuthAccessWriteScope,\n  AuthAdministrativeScopes,\n  AuthStandardClientScopes,\n  type AuthAccessTokenResult,\n  type AuthBrowserSessionResult,\n  type AuthClientMetadata,\n  type AuthClientSession,\n  type AuthCreatePairingCredentialInput,\n  type AuthEnvironmentScope,\n  type AuthPairingLink,\n  type AuthPairingCredentialResult,\n  type AuthSessionId,\n  type AuthSessionState,\n  type ServerAuthDescriptor,\n  type ServerAuthSessionMethod,\n  type AuthWebSocketTicketResult,\n} from \"@t3tools/contracts\";\nimport { encodeOAuthScope } from \"@t3tools/shared/oauthScope\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\n\nimport * as EnvironmentAuthPolicy from \"./EnvironmentAuthPolicy.ts\";\nimport * as PairingGrantStore from \"./PairingGrantStore.ts\";\nimport * as ServerSecretStore from \"./ServerSecretStore.ts\";\nimport * as SessionStore from \"./SessionStore.ts\";\nimport { verifyRequestDpopProof } from \"./dpop.ts\";\nimport { layerConfig as SqlitePersistenceLayer } from \"../persistence/Layers/Sqlite.ts\";\n\nexport const DEFAULT_SESSION_SUBJECT = \"cli-issued-session\";\nexport const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = \"administrative-bootstrap\";\n\nexport interface IssuedPairingLink {\n  readonly id: string;\n  readonly credential: string;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly subject: string;\n  readonly label?: string;\n  readonly createdAt: DateTime.Utc;\n  readonly expiresAt: DateTime.Utc;\n}\n\nexport interface IssuedBearerSession {\n  readonly sessionId: AuthSessionId;\n  readonly token: string;\n  readonly method: \"bearer-access-token\";\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly subject: string;\n  readonly client: AuthClientMetadata;\n  readonly expiresAt: DateTime.Utc;\n}\n\nexport interface AuthenticatedSession {\n  readonly sessionId: AuthSessionId;\n  readonly subject: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt?: DateTime.DateTime;\n}\n\nconst serverAuthInternalErrorContext = {\n  cause: Schema.Defect(),\n};\n\nexport class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthBootstrapCredentialValidationError>()(\n  \"ServerAuthBootstrapCredentialValidationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to validate bootstrap credential.\";\n  }\n}\n\nexport class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(\n  \"ServerAuthSessionCredentialValidationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to validate session credential.\";\n  }\n}\n\nexport class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(\n  \"ServerAuthAuthenticatedSessionIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue authenticated session.\";\n  }\n}\n\nexport class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(\n  \"ServerAuthAuthenticatedAccessTokenIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue authenticated access token.\";\n  }\n}\n\nexport class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(\n  \"ServerAuthPairingLinkCreationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to create pairing link.\";\n  }\n}\n\nexport class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<ServerAuthPairingLinksListError>()(\n  \"ServerAuthPairingLinksListError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to list pairing links.\";\n  }\n}\n\nexport class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(\n  \"ServerAuthPairingLinkRevocationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke pairing link.\";\n  }\n}\n\nexport class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(\n  \"ServerAuthSessionTokenIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue session token.\";\n  }\n}\n\nexport class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerAuthSessionsListError>()(\n  \"ServerAuthSessionsListError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to list sessions.\";\n  }\n}\n\nexport class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(\n  \"ServerAuthSessionRevocationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke session.\";\n  }\n}\n\nexport class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(\n  \"ServerAuthOtherSessionsRevocationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke other sessions.\";\n  }\n}\n\nexport class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(\n  \"ServerAuthWebSocketTokenIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue websocket token.\";\n  }\n}\n\nexport class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(\n  \"ServerAuthDpopReplayStateRecordError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to record DPoP proof replay state.\";\n  }\n}\n\nexport class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(\n  \"ServerAuthDpopReplayKeyCalculationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to calculate DPoP replay key.\";\n  }\n}\n\nexport class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountVerificationError>()(\n  \"ServerAuthLinkedCloudAccountVerificationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Could not verify the linked cloud account.\";\n  }\n}\n\nexport class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountReadError>()(\n  \"ServerAuthLinkedCloudAccountReadError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Could not read the linked cloud account.\";\n  }\n}\n\nexport class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountMissingError>()(\n  \"ServerAuthLinkedCloudAccountMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Cloud linked user is not installed for this environment.\";\n  }\n}\n\nexport class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudLinkJwtSigningError>()(\n  \"ServerAuthCloudLinkJwtSigningError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to sign cloud link JWT.\";\n  }\n}\n\nexport class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedErrorClass<ServerAuthCloudMintPublicKeyMissingError>()(\n  \"ServerAuthCloudMintPublicKeyMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Cloud mint public key is not installed for this environment.\";\n  }\n}\n\nexport class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedErrorClass<ServerAuthCloudRelayIssuerMissingError>()(\n  \"ServerAuthCloudRelayIssuerMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Cloud relay issuer is not installed for this environment.\";\n  }\n}\n\nexport class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudHealthJwtSigningError>()(\n  \"ServerAuthCloudHealthJwtSigningError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to sign cloud health JWT.\";\n  }\n}\n\nexport class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudMintJwtSigningError>()(\n  \"ServerAuthCloudMintJwtSigningError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to sign cloud mint JWT.\";\n  }\n}\n\nexport const ServerAuthInternalError = Schema.Union([\n  ServerAuthBootstrapCredentialValidationError,\n  ServerAuthSessionCredentialValidationError,\n  ServerAuthAuthenticatedSessionIssueError,\n  ServerAuthAuthenticatedAccessTokenIssueError,\n  ServerAuthPairingLinkCreationError,\n  ServerAuthPairingLinksListError,\n  ServerAuthPairingLinkRevocationError,\n  ServerAuthSessionTokenIssueError,\n  ServerAuthSessionsListError,\n  ServerAuthSessionRevocationError,\n  ServerAuthOtherSessionsRevocationError,\n  ServerAuthWebSocketTokenIssueError,\n  ServerAuthDpopReplayStateRecordError,\n  ServerAuthDpopReplayKeyCalculationError,\n  ServerAuthLinkedCloudAccountVerificationError,\n  ServerAuthLinkedCloudAccountReadError,\n  ServerAuthLinkedCloudAccountMissingError,\n  ServerAuthCloudLinkJwtSigningError,\n  ServerAuthCloudMintPublicKeyMissingError,\n  ServerAuthCloudRelayIssuerMissingError,\n  ServerAuthCloudHealthJwtSigningError,\n  ServerAuthCloudMintJwtSigningError,\n]);\nexport type ServerAuthInternalError = typeof ServerAuthInternalError.Type;\nexport const isServerAuthInternalError = Schema.is(ServerAuthInternalError);\n\nexport class ServerAuthMissingCredentialError extends Schema.TaggedErrorClass<ServerAuthMissingCredentialError>()(\n  \"ServerAuthMissingCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Server authentication credential is missing.\";\n  }\n}\n\nexport class ServerAuthInvalidCredentialError extends Schema.TaggedErrorClass<ServerAuthInvalidCredentialError>()(\n  \"ServerAuthInvalidCredentialError\",\n  {\n    diagnostic: Schema.optional(Schema.String),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return \"Server authentication credential is invalid.\";\n  }\n}\n\nexport const ServerAuthCredentialError = Schema.Union([\n  ServerAuthMissingCredentialError,\n  ServerAuthInvalidCredentialError,\n]);\nexport type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;\nexport const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);\nexport const serverAuthCredentialReason = (\n  error: ServerAuthCredentialError,\n): \"missing_credential\" | \"invalid_credential\" =>\n  error._tag === \"ServerAuthMissingCredentialError\" ? \"missing_credential\" : \"invalid_credential\";\n\nexport class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(\n  \"ServerAuthInvalidScopeError\",\n  {},\n) {\n  override get message(): string {\n    return \"The requested authentication scope is invalid.\";\n  }\n}\n\nexport class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(\n  \"ServerAuthScopeNotGrantedError\",\n  {},\n) {\n  override get message(): string {\n    return \"The requested authentication scope was not granted.\";\n  }\n}\n\nexport const ServerAuthInvalidRequestError = Schema.Union([\n  ServerAuthInvalidScopeError,\n  ServerAuthScopeNotGrantedError,\n]);\nexport type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;\nexport const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);\nexport const serverAuthInvalidRequestReason = (\n  error: ServerAuthInvalidRequestError,\n): \"invalid_scope\" | \"scope_not_granted\" =>\n  error._tag === \"ServerAuthInvalidScopeError\" ? \"invalid_scope\" : \"scope_not_granted\";\n\nexport class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(\n  \"ServerAuthForbiddenOperationError\",\n  {},\n) {\n  override get message(): string {\n    return \"The current authentication session cannot revoke itself.\";\n  }\n}\n\nexport class EnvironmentAuth extends Context.Service<\n  EnvironmentAuth,\n  {\n    readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;\n    readonly getSessionState: (\n      request: HttpServerRequest.HttpServerRequest,\n    ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;\n    readonly createBrowserSession: (\n      credential: string,\n      requestMetadata: AuthClientMetadata,\n    ) => Effect.Effect<\n      {\n        readonly response: AuthBrowserSessionResult;\n        readonly sessionToken: string;\n      },\n      ServerAuthInvalidCredentialError | ServerAuthInternalError\n    >;\n    readonly exchangeBootstrapCredentialForAccessToken: (\n      credential: string,\n      requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,\n      requestMetadata: AuthClientMetadata,\n      input?: {\n        readonly proofKeyThumbprint?: string;\n      },\n    ) => Effect.Effect<\n      AuthAccessTokenResult,\n      ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError\n    >;\n    readonly createPairingLink: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly label?: string;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly subject?: string;\n      readonly proofKeyThumbprint?: string;\n      readonly purpose?: \"startup\";\n    }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;\n    readonly issuePairingCredential: (\n      input?: AuthCreatePairingCredentialInput,\n    ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;\n    readonly issueStartupPairingCredential: () => Effect.Effect<\n      AuthPairingCredentialResult,\n      ServerAuthInternalError\n    >;\n    readonly listPairingLinks: (input?: {\n      readonly excludeSubjects?: ReadonlyArray<string>;\n    }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;\n    readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;\n    readonly issueSession: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly subject?: string;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly label?: string;\n    }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;\n    readonly listSessions: () => Effect.Effect<\n      ReadonlyArray<AuthClientSession>,\n      ServerAuthInternalError\n    >;\n    readonly revokeSession: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<boolean, ServerAuthInternalError>;\n    readonly revokeOtherSessionsExcept: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<number, ServerAuthInternalError>;\n    readonly listClientSessions: (\n      currentSessionId: AuthSessionId,\n    ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;\n    readonly revokeClientSession: (\n      currentSessionId: AuthSessionId,\n      targetSessionId: AuthSessionId,\n    ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;\n    readonly revokeOtherClientSessions: (\n      currentSessionId: AuthSessionId,\n    ) => Effect.Effect<number, ServerAuthInternalError>;\n    readonly authenticateHttpRequest: (\n      request: HttpServerRequest.HttpServerRequest,\n    ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;\n    readonly authenticateWebSocketUpgrade: (\n      request: HttpServerRequest.HttpServerRequest,\n    ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;\n    readonly issueWebSocketTicket: (\n      session: Pick<AuthenticatedSession, \"sessionId\">,\n    ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;\n    readonly issueStartupPairingUrl: (\n      baseUrl: string,\n    ) => Effect.Effect<string, ServerAuthInternalError>;\n  }\n>()(\"t3/auth/EnvironmentAuth\") {}\n\ntype BootstrapExchangeResult = {\n  readonly response: AuthBrowserSessionResult;\n  readonly sessionToken: string;\n};\n\nconst AUTHORIZATION_PREFIX = \"Bearer \";\nconst DPOP_AUTHORIZATION_PREFIX = \"DPoP \";\nconst WEBSOCKET_TICKET_QUERY_PARAM = \"wsTicket\";\n\nconst bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {\n  const leftCanManage = left.scopes.includes(AuthAccessWriteScope);\n  const rightCanManage = right.scopes.includes(AuthAccessWriteScope);\n  if (leftCanManage !== rightCanManage) {\n    return leftCanManage ? -1 : 1;\n  }\n  if (left.connected !== right.connected) {\n    return left.connected ? -1 : 1;\n  }\n  return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;\n};\n\nexport function toBootstrapExchangeError(\n  cause: PairingGrantStore.BootstrapCredentialError,\n): ServerAuthInvalidCredentialError | ServerAuthInternalError {\n  if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {\n    return new ServerAuthBootstrapCredentialValidationError({ cause });\n  }\n\n  return new ServerAuthInvalidCredentialError({\n    cause,\n  });\n}\n\nconst mapSessionVerificationErrors = <A, R>(\n  effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,\n): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>\n  effect.pipe(\n    Effect.mapError((cause) =>\n      SessionStore.isSessionCredentialInvalidError(cause)\n        ? new ServerAuthInvalidCredentialError({ cause })\n        : new ServerAuthSessionCredentialValidationError({ cause }),\n    ),\n  );\n\nfunction parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {\n  const header = request.headers[\"authorization\"];\n  if (typeof header !== \"string\" || !header.startsWith(AUTHORIZATION_PREFIX)) {\n    return null;\n  }\n  const token = header.slice(AUTHORIZATION_PREFIX.length).trim();\n  return token.length > 0 ? token : null;\n}\n\nfunction parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {\n  const header = request.headers[\"authorization\"];\n  if (typeof header !== \"string\" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {\n    return null;\n  }\n  const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();\n  return token.length > 0 ? token : null;\n}\n\nexport const make = Effect.gen(function* () {\n  const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;\n  const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;\n  const sessions = yield* SessionStore.SessionStore;\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const crypto = yield* Crypto.Crypto;\n  const descriptor = yield* policy.getDescriptor();\n\n  const authenticateToken = (\n    token: string,\n  ): Effect.Effect<\n    AuthenticatedSession,\n    ServerAuthInvalidCredentialError | ServerAuthInternalError\n  > =>\n    sessions.verify(token).pipe(\n      Effect.tapError((cause) =>\n        SessionStore.isSessionCredentialInvalidError(cause)\n          ? Effect.logWarning(\"Rejected authenticated session credential.\").pipe(\n              Effect.annotateLogs({\n                reason: cause.message,\n              }),\n            )\n          : Effect.void,\n      ),\n      Effect.map((session) => ({\n        sessionId: session.sessionId,\n        subject: session.subject,\n        method: session.method,\n        scopes: session.scopes,\n        ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),\n        ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),\n      })),\n      mapSessionVerificationErrors,\n    );\n\n  const authenticateRequest = (\n    request: HttpServerRequest.HttpServerRequest,\n  ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {\n    const cookieToken = request.cookies[sessions.cookieName];\n    const bearerToken = parseBearerToken(request);\n    const dpopToken = parseDpopToken(request);\n    const credential = cookieToken ?? bearerToken ?? dpopToken;\n    if (!credential) {\n      return Effect.fail(new ServerAuthMissingCredentialError({}));\n    }\n    return authenticateToken(credential).pipe(\n      Effect.flatMap((session) => {\n        if (session.proofKeyThumbprint) {\n          if (!dpopToken || dpopToken !== credential) {\n            return Effect.fail(\n              new ServerAuthInvalidCredentialError({\n                diagnostic: \"DPoP-bound access token requires DPoP authorization.\",\n              }),\n            );\n          }\n          return verifyRequestDpopProof({\n            request,\n            expectedThumbprint: session.proofKeyThumbprint,\n            expectedAccessToken: dpopToken,\n          }).pipe(\n            Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),\n            Effect.provideService(Crypto.Crypto, crypto),\n            Effect.as(session),\n          );\n        }\n        if (dpopToken) {\n          return Effect.fail(\n            new ServerAuthInvalidCredentialError({\n              diagnostic: \"DPoP authorization requires a proof-bound access token.\",\n            }),\n          );\n        }\n        return Effect.succeed(session);\n      }),\n    );\n  };\n\n  const getSessionState: EnvironmentAuth[\"Service\"][\"getSessionState\"] = (request) =>\n    authenticateRequest(request).pipe(\n      Effect.map(\n        (session) =>\n          ({\n            authenticated: true,\n            auth: descriptor,\n            scopes: session.scopes,\n            sessionMethod: session.method,\n            ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),\n          }) satisfies AuthSessionState,\n      ),\n      Effect.catchIf(isServerAuthCredentialError, () =>\n        Effect.succeed({\n          authenticated: false,\n          auth: descriptor,\n        } satisfies AuthSessionState),\n      ),\n      Effect.withSpan(\"EnvironmentAuth.getSessionState\"),\n    );\n\n  const createBrowserSession: EnvironmentAuth[\"Service\"][\"createBrowserSession\"] = (\n    credential,\n    requestMetadata,\n  ) =>\n    bootstrapCredentials.consume(credential).pipe(\n      Effect.mapError(toBootstrapExchangeError),\n      Effect.flatMap((grant) =>\n        sessions\n          .issue({\n            method: \"browser-session-cookie\",\n            subject: grant.subject,\n            scopes: grant.scopes,\n            client: {\n              ...requestMetadata,\n              ...(grant.label ? { label: grant.label } : {}),\n            },\n          })\n          .pipe(\n            Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),\n          ),\n      ),\n      Effect.map(\n        (session) =>\n          ({\n            response: {\n              authenticated: true,\n              scopes: session.scopes,\n              sessionMethod: session.method,\n              expiresAt: DateTime.toUtc(session.expiresAt),\n            } satisfies AuthBrowserSessionResult,\n            sessionToken: session.token,\n          }) satisfies BootstrapExchangeResult,\n      ),\n      Effect.withSpan(\"EnvironmentAuth.createBrowserSession\"),\n    );\n\n  const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth[\"Service\"][\"exchangeBootstrapCredentialForAccessToken\"] =\n    (credential, requestedScopes, requestMetadata, input) =>\n      bootstrapCredentials.consume(credential, input).pipe(\n        Effect.mapError(toBootstrapExchangeError),\n        Effect.flatMap((grant) =>\n          Effect.gen(function* () {\n            const grantedScopes = requestedScopes ?? grant.scopes;\n            if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {\n              return yield* new ServerAuthScopeNotGrantedError({});\n            }\n            return yield* sessions\n              .issue({\n                method: input?.proofKeyThumbprint ? \"dpop-access-token\" : \"bearer-access-token\",\n                subject: grant.subject,\n                scopes: grantedScopes,\n                ...(input?.proofKeyThumbprint\n                  ? {\n                      proofKeyThumbprint: input.proofKeyThumbprint,\n                      ttl: Duration.hours(1),\n                    }\n                  : {}),\n                client: {\n                  ...requestMetadata,\n                  ...(grant.label ? { label: grant.label } : {}),\n                },\n              })\n              .pipe(\n                Effect.mapError(\n                  (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),\n                ),\n              );\n          }),\n        ),\n        Effect.flatMap((session) =>\n          DateTime.now.pipe(\n            Effect.map(\n              (now) =>\n                ({\n                  access_token: session.token,\n                  issued_token_type: AuthAccessTokenType,\n                  token_type: input?.proofKeyThumbprint ? \"DPoP\" : \"Bearer\",\n                  expires_in: Math.max(\n                    0,\n                    Math.floor(\n                      (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,\n                    ),\n                  ),\n                  scope: encodeOAuthScope(session.scopes),\n                }) satisfies AuthAccessTokenResult,\n            ),\n          ),\n        ),\n        Effect.withSpan(\"EnvironmentAuth.exchangeBootstrapCredentialForAccessToken\"),\n      );\n\n  const issuePairingCredentialForSubject = (input: {\n    readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n    readonly subject: string;\n    readonly label?: string;\n    readonly purpose?: \"startup\";\n  }) =>\n    createPairingLink({\n      scopes: input.scopes,\n      subject: input.subject,\n      ...(input.label ? { label: input.label } : {}),\n      ...(input.purpose ? { purpose: input.purpose } : {}),\n    }).pipe(\n      Effect.map(\n        (issued) =>\n          ({\n            id: issued.id,\n            credential: issued.credential,\n            ...(issued.label ? { label: issued.label } : {}),\n            expiresAt: issued.expiresAt,\n          }) satisfies AuthPairingCredentialResult,\n      ),\n    );\n\n  const createPairingLink: EnvironmentAuth[\"Service\"][\"createPairingLink\"] = Effect.fn(\n    \"EnvironmentAuth.createPairingLink\",\n  )(\n    function* (input) {\n      const createdAt = yield* DateTime.now;\n      const issued = yield* bootstrapCredentials.issueOneTimeToken({\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        subject: input?.subject ?? \"one-time-token\",\n        ...(input?.ttl ? { ttl: input.ttl } : {}),\n        ...(input?.label ? { label: input.label } : {}),\n        ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),\n        ...(input?.purpose ? { purpose: input.purpose } : {}),\n      });\n      return {\n        id: issued.id,\n        credential: issued.credential,\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        subject: input?.subject ?? \"one-time-token\",\n        ...(issued.label ? { label: issued.label } : {}),\n        createdAt: DateTime.toUtc(createdAt),\n        expiresAt: DateTime.toUtc(issued.expiresAt),\n      } satisfies IssuedPairingLink;\n    },\n    Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),\n  );\n\n  const listPairingLinks: EnvironmentAuth[\"Service\"][\"listPairingLinks\"] = (input) =>\n    bootstrapCredentials.listActive().pipe(\n      Effect.map((pairingLinks) => {\n        const excludedSubjects = input?.excludeSubjects ?? [\n          INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,\n        ];\n        return pairingLinks\n          .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))\n          .toSorted(\n            (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,\n          );\n      }),\n      Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.listPairingLinks\"),\n    );\n\n  const revokePairingLink: EnvironmentAuth[\"Service\"][\"revokePairingLink\"] = (id) =>\n    bootstrapCredentials.revoke(id).pipe(\n      Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.revokePairingLink\"),\n    );\n\n  const issueSession: EnvironmentAuth[\"Service\"][\"issueSession\"] = (input) =>\n    sessions\n      .issue({\n        subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,\n        method: \"bearer-access-token\",\n        scopes: input?.scopes ?? AuthAdministrativeScopes,\n        client: {\n          ...(input?.label ? { label: input.label } : {}),\n          deviceType: \"bot\",\n        },\n        ...(input?.ttl ? { ttl: input.ttl } : {}),\n      })\n      .pipe(\n        Effect.map(\n          (issued) =>\n            ({\n              sessionId: issued.sessionId,\n              token: issued.token,\n              method: \"bearer-access-token\",\n              scopes: issued.scopes,\n              subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,\n              client: issued.client,\n              expiresAt: DateTime.toUtc(issued.expiresAt),\n            }) satisfies IssuedBearerSession,\n        ),\n        Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),\n        Effect.withSpan(\"EnvironmentAuth.issueSession\"),\n      );\n\n  const listSessions: EnvironmentAuth[\"Service\"][\"listSessions\"] = () =>\n    sessions.listActive().pipe(\n      Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),\n      Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.listSessions\"),\n    );\n\n  const revokeSession: EnvironmentAuth[\"Service\"][\"revokeSession\"] = (sessionId) =>\n    sessions.revoke(sessionId).pipe(\n      Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.revokeSession\"),\n    );\n\n  const revokeOtherSessionsExcept: EnvironmentAuth[\"Service\"][\"revokeOtherSessionsExcept\"] = (\n    sessionId,\n  ) =>\n    sessions.revokeAllExcept(sessionId).pipe(\n      Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.revokeOtherSessionsExcept\"),\n    );\n\n  const issuePairingCredential: EnvironmentAuth[\"Service\"][\"issuePairingCredential\"] = (input) =>\n    issuePairingCredentialForSubject({\n      scopes: input?.scopes ?? AuthStandardClientScopes,\n      subject: \"one-time-token\",\n      ...(input?.label ? { label: input.label } : {}),\n    }).pipe(Effect.withSpan(\"EnvironmentAuth.issuePairingCredential\"));\n\n  const issueStartupPairingCredential: EnvironmentAuth[\"Service\"][\"issueStartupPairingCredential\"] =\n    () =>\n      issuePairingCredentialForSubject({\n        scopes: AuthAdministrativeScopes,\n        subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,\n        purpose: \"startup\",\n      }).pipe(Effect.withSpan(\"EnvironmentAuth.issueStartupPairingCredential\"));\n\n  const listClientSessions: EnvironmentAuth[\"Service\"][\"listClientSessions\"] = (currentSessionId) =>\n    listSessions().pipe(\n      Effect.map((clientSessions) =>\n        clientSessions.map(\n          (clientSession): AuthClientSession => ({\n            ...clientSession,\n            current: clientSession.sessionId === currentSessionId,\n          }),\n        ),\n      ),\n      Effect.withSpan(\"EnvironmentAuth.listClientSessions\"),\n    );\n\n  const revokeClientSession: EnvironmentAuth[\"Service\"][\"revokeClientSession\"] = Effect.fn(\n    \"EnvironmentAuth.revokeClientSession\",\n  )(function* (currentSessionId, targetSessionId) {\n    if (currentSessionId === targetSessionId) {\n      return yield* new ServerAuthForbiddenOperationError({});\n    }\n    return yield* revokeSession(targetSessionId);\n  });\n\n  const revokeOtherClientSessions: EnvironmentAuth[\"Service\"][\"revokeOtherClientSessions\"] = (\n    currentSessionId,\n  ) =>\n    revokeOtherSessionsExcept(currentSessionId).pipe(\n      Effect.withSpan(\"EnvironmentAuth.revokeOtherClientSessions\"),\n    );\n\n  const issueStartupPairingUrl: EnvironmentAuth[\"Service\"][\"issueStartupPairingUrl\"] = (baseUrl) =>\n    issueStartupPairingCredential().pipe(\n      Effect.map((issued) => {\n        const url = new URL(baseUrl);\n        url.pathname = \"/pair\";\n        url.searchParams.delete(\"token\");\n        url.hash = new URLSearchParams([[\"token\", issued.credential]]).toString();\n        return url.toString();\n      }),\n      Effect.withSpan(\"EnvironmentAuth.issueStartupPairingUrl\"),\n    );\n\n  const issueWebSocketTicket: EnvironmentAuth[\"Service\"][\"issueWebSocketTicket\"] = (session) =>\n    sessions.issueWebSocketToken(session.sessionId).pipe(\n      Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),\n      Effect.map(\n        (issued) =>\n          ({\n            ticket: issued.token,\n            expiresAt: DateTime.toUtc(issued.expiresAt),\n          }) satisfies AuthWebSocketTicketResult,\n      ),\n      Effect.withSpan(\"EnvironmentAuth.issueWebSocketTicket\"),\n    );\n\n  const authenticateHttpRequest: EnvironmentAuth[\"Service\"][\"authenticateHttpRequest\"] = (\n    request,\n  ) =>\n    authenticateRequest(request).pipe(Effect.withSpan(\"EnvironmentAuth.authenticateHttpRequest\"));\n\n  const authenticateWebSocketUpgrade: EnvironmentAuth[\"Service\"][\"authenticateWebSocketUpgrade\"] =\n    Effect.fn(\"EnvironmentAuth.authenticateWebSocketUpgrade\")(function* (request) {\n      const requestUrl = HttpServerRequest.toURL(request);\n      if (Option.isSome(requestUrl)) {\n        const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);\n        if (websocketTicket && websocketTicket.trim().length > 0) {\n          return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(\n            Effect.map((session) => ({\n              sessionId: session.sessionId,\n              subject: session.subject,\n              method: session.method,\n              scopes: session.scopes,\n              ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),\n            })),\n            mapSessionVerificationErrors,\n          );\n        }\n      }\n\n      return yield* authenticateRequest(request);\n    });\n\n  return EnvironmentAuth.of({\n    getDescriptor: () =>\n      Effect.succeed(descriptor).pipe(Effect.withSpan(\"EnvironmentAuth.getDescriptor\")),\n    getSessionState,\n    createBrowserSession,\n    exchangeBootstrapCredentialForAccessToken,\n    createPairingLink,\n    issuePairingCredential,\n    issueStartupPairingCredential,\n    listPairingLinks,\n    revokePairingLink,\n    issueSession,\n    listSessions,\n    revokeSession,\n    revokeOtherSessionsExcept,\n    listClientSessions,\n    revokeClientSession,\n    revokeOtherClientSessions,\n    authenticateHttpRequest,\n    authenticateWebSocketUpgrade,\n    issueWebSocketTicket,\n    issueStartupPairingUrl,\n  });\n});\n\nexport const layer = Layer.effect(EnvironmentAuth, make).pipe(\n  Layer.provideMerge(PairingGrantStore.layer),\n  Layer.provideMerge(SessionStore.layer),\n  Layer.provideMerge(EnvironmentAuthPolicy.layer),\n);\n\nexport const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);\n\nexport const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));\n","import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\n\nimport type { IssuedBearerSession, IssuedPairingLink } from \"./auth/EnvironmentAuth.ts\";\n\nconst newline = \"\\n\";\n\nfunction serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {\n  return values.filter((value): value is string => typeof value === \"string\" && value.length > 0);\n}\n\nfunction formatClientMetadata(metadata: AuthClientMetadata): string {\n  const details = serializeOptionalFields([\n    metadata.label,\n    metadata.deviceType !== \"unknown\" ? metadata.deviceType : undefined,\n    metadata.os,\n    metadata.browser,\n    metadata.ipAddress,\n  ]);\n  return details.length > 0 ? details.join(\" | \") : \"unlabeled client\";\n}\n\nfunction toIsoString(value: DateTime.DateTime | DateTime.Utc): string {\n  return DateTime.formatIso(DateTime.toUtc(value));\n}\n\nexport function formatIssuedPairingCredential(\n  credential: IssuedPairingLink,\n  options?: {\n    readonly json?: boolean;\n    readonly baseUrl?: string;\n  },\n): string {\n  const pairUrl =\n    options?.baseUrl != null && options.baseUrl.length > 0\n      ? (() => {\n          const url = new URL(\"/pair\", options.baseUrl);\n          url.searchParams.delete(\"token\");\n          url.hash = new URLSearchParams([[\"token\", credential.credential]]).toString();\n          return url.toString();\n        })()\n      : undefined;\n\n  if (options?.json) {\n    return `${JSON.stringify(\n      {\n        id: credential.id,\n        credential: credential.credential,\n        ...(credential.label ? { label: credential.label } : {}),\n        scopes: credential.scopes,\n        expiresAt: toIsoString(credential.expiresAt),\n        ...(pairUrl ? { pairUrl } : {}),\n      },\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  return (\n    [\n      `Issued client pairing token ${credential.id}.`,\n      `Token: ${credential.credential}`,\n      ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),\n      `Expires at: ${credential.expiresAt}`,\n    ].join(newline) + newline\n  );\n}\n\nexport function formatPairingCredentialList(\n  credentials: ReadonlyArray<AuthPairingLink>,\n  options?: {\n    readonly json?: boolean;\n  },\n): string {\n  if (options?.json) {\n    return `${JSON.stringify(\n      credentials.map((credential) => ({\n        id: credential.id,\n        ...(credential.label ? { label: credential.label } : {}),\n        scopes: credential.scopes,\n        createdAt: toIsoString(credential.createdAt),\n        expiresAt: toIsoString(credential.expiresAt),\n      })),\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  if (credentials.length === 0) {\n    return `No active pairing credentials.${newline}`;\n  }\n\n  return (\n    credentials\n      .map((credential) =>\n        [\n          `${credential.id}${credential.label ? ` (${credential.label})` : \"\"}`,\n          `  scopes: ${credential.scopes.join(\" \")}`,\n          `  created: ${toIsoString(credential.createdAt)}`,\n          `  expires: ${toIsoString(credential.expiresAt)}`,\n        ].join(newline),\n      )\n      .join(`${newline}${newline}`) + newline\n  );\n}\n\nexport function formatIssuedSession(\n  session: IssuedBearerSession,\n  options?: {\n    readonly json?: boolean;\n    readonly tokenOnly?: boolean;\n  },\n): string {\n  if (options?.tokenOnly) {\n    return `${session.token}${newline}`;\n  }\n\n  if (options?.json) {\n    return `${JSON.stringify(\n      {\n        sessionId: session.sessionId,\n        token: session.token,\n        method: session.method,\n        scopes: session.scopes,\n        subject: session.subject,\n        client: session.client,\n        expiresAt: toIsoString(session.expiresAt),\n      },\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  return (\n    [\n      `Issued bearer access token ${session.sessionId}.`,\n      `Scopes: ${session.scopes.join(\" \")}`,\n      `Token: ${session.token}`,\n      `Subject: ${session.subject}`,\n      `Client: ${formatClientMetadata(session.client)}`,\n      `Expires at: ${toIsoString(session.expiresAt)}`,\n    ].join(newline) + newline\n  );\n}\n\nexport function formatSessionList(\n  sessions: ReadonlyArray<AuthClientSession>,\n  options?: {\n    readonly json?: boolean;\n  },\n): string {\n  if (options?.json) {\n    return `${JSON.stringify(\n      sessions.map((session) => ({\n        sessionId: session.sessionId,\n        method: session.method,\n        scopes: session.scopes,\n        subject: session.subject,\n        client: session.client,\n        connected: session.connected,\n        issuedAt: toIsoString(session.issuedAt),\n        expiresAt: toIsoString(session.expiresAt),\n        lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,\n      })),\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  if (sessions.length === 0) {\n    return `No active sessions.${newline}`;\n  }\n\n  return (\n    sessions\n      .map((session) =>\n        [\n          `${session.sessionId}${session.connected ? \" connected\" : \"\"}`,\n          `  scopes: ${session.scopes.join(\" \")}`,\n          `  method: ${session.method}`,\n          `  subject: ${session.subject}`,\n          `  client: ${formatClientMetadata(session.client)}`,\n          `  issued: ${toIsoString(session.issuedAt)}`,\n          `  last connected: ${\n            session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : \"never\"\n          }`,\n          `  expires: ${toIsoString(session.expiresAt)}`,\n        ].join(newline),\n      )\n      .join(`${newline}${newline}`) + newline\n  );\n}\n","import * as P from \"effect/Predicate\";\n\nexport type DeepPartial<T> = T extends readonly (infer U)[]\n  ? readonly DeepPartial<U>[]\n  : T extends object\n    ? { [K in keyof T]?: DeepPartial<T[K]> }\n    : T;\n\nexport function deepMerge<T extends Record<string, unknown>>(current: T, patch: DeepPartial<T>): T {\n  if (!P.isObject(current) || !P.isObject(patch)) {\n    return patch as T;\n  }\n\n  const next = { ...current } as Record<string, unknown>;\n  for (const [key, value] of Object.entries(patch)) {\n    if (value === undefined) continue;\n\n    const existing = next[key];\n    next[key] = P.isObject(existing) && P.isObject(value) ? deepMerge(existing, value) : value;\n  }\n\n  return next as T;\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nconst MAX_SCHEMA_DIAGNOSTIC_ISSUES = 8;\nconst MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS = 16;\nconst MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH = 64;\nconst MAX_SCHEMA_DIAGNOSTIC_LENGTH = 2_048;\n\ninterface SchemaDiagnosticIssue {\n  readonly message: string;\n  readonly path: ReadonlyArray<PropertyKey>;\n}\n\n// Schema's default formatter includes actual values. These diagnostics cross\n// process and UI boundaries, so retain only issue kinds and bounded paths.\n\nfunction truncateDiagnostic(value: string, maxLength: number): string {\n  return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;\n}\n\nfunction formatDiagnosticPathSegment(key: PropertyKey): string {\n  if (typeof key === \"number\") {\n    return `[${key}]`;\n  }\n  const value = truncateDiagnostic(\n    typeof key === \"symbol\" ? String(key) : key,\n    MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH,\n  );\n  return `[${JSON.stringify(value)}]`;\n}\n\nfunction formatDiagnosticIssue(issue: SchemaDiagnosticIssue): string {\n  if (issue.path.length === 0) {\n    return issue.message;\n  }\n  const path = issue.path\n    .slice(0, MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS)\n    .map(formatDiagnosticPathSegment)\n    .join(\"\");\n  const suffix = issue.path.length > MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS ? \"[...]\" : \"\";\n  return `${issue.message}\\n  at ${path}${suffix}`;\n}\n\nfunction schemaDiagnosticMessage(issue: SchemaIssue.Issue): string {\n  switch (issue._tag) {\n    case \"InvalidType\":\n      return \"Invalid type\";\n    case \"InvalidValue\":\n    case \"Filter\":\n    case \"AnyOf\":\n    case \"Encoding\":\n    case \"Pointer\":\n    case \"Composite\":\n      return \"Invalid value\";\n    case \"MissingKey\":\n      return \"Missing key\";\n    case \"UnexpectedKey\":\n      return \"Unexpected key\";\n    case \"Forbidden\":\n      return \"Forbidden operation\";\n    case \"OneOf\":\n      return \"Expected exactly one schema member to match\";\n  }\n}\n\nfunction collectSchemaDiagnosticIssues(\n  issue: SchemaIssue.Issue,\n  path: ReadonlyArray<PropertyKey>,\n  diagnostics: Array<SchemaDiagnosticIssue>,\n): number {\n  switch (issue._tag) {\n    case \"Encoding\":\n      return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);\n    case \"Filter\":\n      if (issue.issue._tag !== \"InvalidValue\") {\n        return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);\n      }\n      break;\n    case \"Pointer\":\n      return collectSchemaDiagnosticIssues(issue.issue, [...path, ...issue.path], diagnostics);\n    case \"Composite\":\n      return issue.issues.reduce(\n        (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),\n        0,\n      );\n    case \"AnyOf\":\n      if (issue.issues.length > 0) {\n        return issue.issues.reduce(\n          (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),\n          0,\n        );\n      }\n      break;\n  }\n\n  if (diagnostics.length < MAX_SCHEMA_DIAGNOSTIC_ISSUES) {\n    diagnostics.push({ message: schemaDiagnosticMessage(issue), path });\n  }\n  return 1;\n}\n\nexport const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(\n  schema: S,\n) => {\n  const decode = Schema.decodeExit(Schema.fromJsonString(schema));\n  return (input: string) => {\n    const result = decode(input);\n    if (Exit.isFailure(result)) {\n      return Result.fail(result.cause);\n    }\n    return Result.succeed(result.value);\n  };\n};\n\nexport const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(\n  schema: S,\n) => {\n  const decode = Schema.decodeUnknownExit(Schema.fromJsonString(schema));\n  return (input: unknown) => {\n    const result = decode(input);\n    if (Exit.isFailure(result)) {\n      return Result.fail(result.cause);\n    }\n    return Result.succeed(result.value);\n  };\n};\n\nexport const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {\n  const issues: Array<SchemaDiagnosticIssue> = [];\n  let issueCount = 0;\n  let failureCount = 0;\n  let defectCount = 0;\n  let interruptionCount = 0;\n\n  for (const reason of cause.reasons) {\n    switch (reason._tag) {\n      case \"Fail\":\n        failureCount += 1;\n        if (Schema.isSchemaError(reason.error)) {\n          issueCount += collectSchemaDiagnosticIssues(reason.error.issue, [], issues);\n        }\n        break;\n      case \"Die\":\n        defectCount += 1;\n        break;\n      case \"Interrupt\":\n        interruptionCount += 1;\n        break;\n    }\n  }\n\n  if (issues.length === 0) {\n    return `Schema validation failed (failureCount=${failureCount}, defectCount=${defectCount}, interruptionCount=${interruptionCount}).`;\n  }\n\n  const omittedIssueCount = issueCount - issues.length;\n  const formatted = issues.map(formatDiagnosticIssue).join(\"\\n\");\n  if (omittedIssueCount === 0) {\n    return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH);\n  }\n  const suffix = `\\n... and ${omittedIssueCount} more issue(s)`;\n  return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH - suffix.length) + suffix;\n};\n\n/**\n * A `Getter` that parses a lenient JSON string (tolerating trailing commas\n * and JS-style comments) into an unknown value.\n *\n * Mirrors `SchemaGetter.parseJson()` but strips JSONC syntax before parsing.\n */\nconst decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseLenientJsonGetter = SchemaGetter.onSome((input: string) => {\n  // Strip single-line comments - alternation preserves quoted strings.\n  let stripped = input.replace(\n    /(\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\/[^\\n]*/g,\n    (match, stringLiteral: string | undefined) => (stringLiteral ? match : \"\"),\n  );\n\n  // Strip multi-line comments.\n  stripped = stripped.replace(\n    /(\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\*[\\s\\S]*?\\*\\//g,\n    (match, stringLiteral: string | undefined) => (stringLiteral ? match : \"\"),\n  );\n\n  // Strip trailing commas before `}` or `]`. The alternation preserves quoted\n  // strings so a comma inside a string value (e.g. `{\"note\":\"a,]\"}`) is not\n  // mistaken for a trailing comma and removed.\n  stripped = stripped.replace(\n    /(\"(?:[^\"\\\\]|\\\\.)*\")|,(\\s*[}\\]])/g,\n    (match, stringLiteral: string | undefined, bracket: string | undefined) =>\n      stringLiteral ? match : (bracket ?? \"\"),\n  );\n\n  return decodeJsonString(stripped).pipe(\n    Effect.map(Option.some),\n    Effect.mapError((error) => error.issue),\n  );\n});\n\n/**\n * Schema transformation: lenient JSONC string ↔ unknown.\n *\n * Same API as `SchemaTransformation.fromJsonString`, but the decode side\n * strips trailing commas and JS-style comments before parsing.\n * Encoding produces strict JSON via `JSON.stringify`.\n */\nexport const fromLenientJsonString = new SchemaTransformation.Transformation(\n  parseLenientJsonGetter,\n  SchemaGetter.stringifyJson(),\n);\n\nexport const prettyJsonString = SchemaGetter.parseJson<string>().compose(\n  SchemaGetter.stringifyJson({ space: 2 }),\n);\n\n/**\n * Build a schema that decodes a lenient JSON string into `A`.\n *\n * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates\n * trailing commas and comments in the input.\n */\nexport const fromLenientJson = <S extends Schema.Top>(schema: S) =>\n  Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));\n\nexport function extractJsonObject(raw: string): string {\n  const trimmed = raw.trim();\n  if (trimmed.length === 0) {\n    return trimmed;\n  }\n\n  const start = trimmed.indexOf(\"{\");\n  if (start < 0) {\n    return trimmed;\n  }\n\n  let depth = 0;\n  let inString = false;\n  let escaping = false;\n  for (let index = start; index < trimmed.length; index += 1) {\n    const char = trimmed[index];\n    if (inString) {\n      if (escaping) {\n        escaping = false;\n      } else if (char === \"\\\\\") {\n        escaping = true;\n      } else if (char === '\"') {\n        inString = false;\n      }\n      continue;\n    }\n\n    if (char === '\"') {\n      inString = true;\n      continue;\n    }\n\n    if (char === \"{\") {\n      depth += 1;\n      continue;\n    }\n\n    if (char === \"}\") {\n      depth -= 1;\n      if (depth === 0) {\n        return trimmed.slice(start, index + 1);\n      }\n    }\n  }\n\n  return trimmed.slice(start);\n}\n\n/**\n * Build a JSON string schema that encodes with stable 2-space formatting.\n *\n * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior\n * keeps the transformation schema-based while preserving human-readable JSON.\n */\nexport const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>\n  Schema.fromJsonString(schema).pipe(\n    Schema.encode({\n      decode: prettyJsonString,\n      encode: prettyJsonString,\n    }),\n  );\n","import {\n  DEFAULT_MODEL,\n  DEFAULT_MODEL_BY_PROVIDER,\n  MODEL_SLUG_ALIASES_BY_PROVIDER,\n  type ModelCapabilities,\n  type ModelSelection,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  type ProviderOptionDescriptor,\n  type ProviderOptionSelection,\n} from \"@t3tools/contracts\";\n\nconst DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make(\"codex\");\n\nexport interface SelectableModelOption {\n  slug: string;\n  name: string;\n}\n\nexport function createModelCapabilities(input: {\n  optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;\n}): ModelCapabilities {\n  return {\n    optionDescriptors: input.optionDescriptors.map(cloneDescriptor),\n  };\n}\n\nfunction getRawSelectionValueById(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): string | boolean | undefined {\n  const selection = selections?.find((candidate) => candidate.id === id);\n  return selection?.value;\n}\n\nexport function getProviderOptionSelectionValue(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): string | boolean | undefined {\n  return getRawSelectionValueById(selections, id);\n}\n\nexport function getProviderOptionStringSelectionValue(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): string | undefined {\n  const value = getProviderOptionSelectionValue(selections, id);\n  return typeof value === \"string\" ? value : undefined;\n}\n\nexport function getProviderOptionBooleanSelectionValue(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): boolean | undefined {\n  const value = getProviderOptionSelectionValue(selections, id);\n  return typeof value === \"boolean\" ? value : undefined;\n}\n\nexport function getModelSelectionOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n  id: string,\n): string | boolean | undefined {\n  return getProviderOptionSelectionValue(modelSelection?.options, id);\n}\n\nexport function getModelSelectionStringOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n  id: string,\n): string | undefined {\n  return getProviderOptionStringSelectionValue(modelSelection?.options, id);\n}\n\nexport function getModelSelectionBooleanOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n  id: string,\n): boolean | undefined {\n  return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);\n}\n\nfunction resolveDescriptorChoiceValue(\n  descriptor: Extract<ProviderOptionDescriptor, { type: \"select\" }>,\n  raw: string | null | undefined,\n): string | undefined {\n  const trimmed = trimOrNull(raw);\n  if (!trimmed) {\n    return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;\n  }\n  if (descriptor.options.length === 0) {\n    return trimmed;\n  }\n  if (\n    descriptor.promptInjectedValues?.includes(trimmed) &&\n    descriptor.options.some((option) => option.id === trimmed)\n  ) {\n    return descriptor.options.find((option) => option.isDefault)?.id;\n  }\n  if (descriptor.options.some((option) => option.id === trimmed)) {\n    return trimmed;\n  }\n  return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;\n}\n\nfunction cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {\n  return descriptor.type === \"select\"\n    ? {\n        ...descriptor,\n        options: [...descriptor.options],\n        ...(descriptor.promptInjectedValues\n          ? { promptInjectedValues: [...descriptor.promptInjectedValues] }\n          : {}),\n      }\n    : { ...descriptor };\n}\n\nfunction cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {\n  return { ...selection };\n}\n\nfunction withDescriptorCurrentValue(\n  descriptor: ProviderOptionDescriptor,\n  rawCurrentValue: string | boolean | undefined,\n): ProviderOptionDescriptor {\n  if (descriptor.type === \"boolean\") {\n    if (typeof rawCurrentValue === \"boolean\") {\n      return {\n        ...descriptor,\n        currentValue: rawCurrentValue,\n      };\n    }\n    return descriptor;\n  }\n  const currentValue =\n    typeof rawCurrentValue === \"string\"\n      ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)\n      : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);\n  if (!currentValue) {\n    const { currentValue: _unusedCurrentValue, ...rest } = descriptor;\n    return rest;\n  }\n  return {\n    ...descriptor,\n    currentValue,\n  };\n}\n\nexport function getProviderOptionDescriptors(input: {\n  caps: ModelCapabilities;\n  selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;\n}): ReadonlyArray<ProviderOptionDescriptor> {\n  const { caps, selections } = input;\n  const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);\n\n  return baseDescriptors.map((descriptor) =>\n    withDescriptorCurrentValue(\n      descriptor,\n      getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,\n    ),\n  );\n}\n\nexport function getProviderOptionCurrentValue(\n  descriptor: ProviderOptionDescriptor | null | undefined,\n): string | boolean | undefined {\n  if (!descriptor) {\n    return undefined;\n  }\n  if (descriptor.type === \"boolean\") {\n    return descriptor.currentValue;\n  }\n  if (descriptor.currentValue) {\n    return descriptor.currentValue;\n  }\n  return descriptor.options.find((option) => option.isDefault)?.id;\n}\n\nexport function getProviderOptionCurrentLabel(\n  descriptor: ProviderOptionDescriptor | null | undefined,\n): string | undefined {\n  if (!descriptor) {\n    return undefined;\n  }\n  if (descriptor.type === \"boolean\") {\n    return typeof descriptor.currentValue === \"boolean\"\n      ? descriptor.currentValue\n        ? \"On\"\n        : \"Off\"\n      : undefined;\n  }\n  const currentValue = getProviderOptionCurrentValue(descriptor);\n  if (typeof currentValue !== \"string\") {\n    return undefined;\n  }\n  return descriptor.options.find((option) => option.id === currentValue)?.label;\n}\n\nexport function buildProviderOptionSelectionsFromDescriptors(\n  descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,\n): Array<ProviderOptionSelection> | undefined {\n  if (!descriptors || descriptors.length === 0) {\n    return undefined;\n  }\n\n  const nextSelections: Array<ProviderOptionSelection> = [];\n\n  for (const descriptor of descriptors) {\n    const value = getProviderOptionCurrentValue(descriptor);\n    if (typeof value === \"string\" || typeof value === \"boolean\") {\n      nextSelections.push({ id: descriptor.id, value });\n    }\n  }\n\n  return nextSelections.length > 0 ? nextSelections : undefined;\n}\n\nexport function getModelSelectionOptionDescriptors(\n  modelSelection: ModelSelection | null | undefined,\n  caps?: ModelCapabilities | null | undefined,\n): ReadonlyArray<ProviderOptionDescriptor> {\n  if (!modelSelection) {\n    return [];\n  }\n  if (!caps) {\n    return [];\n  }\n  return getProviderOptionDescriptors({\n    caps,\n    selections: modelSelection.options,\n  });\n}\n\nexport function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {\n  return typeof text === \"string\" && /\\bultrathink\\b/i.test(text);\n}\n\nexport function normalizeModelSlug(\n  model: string | null | undefined,\n  provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,\n): string | null {\n  const trimmed = normalizeCustomModelSlug(model);\n  if (!trimmed) {\n    return null;\n  }\n\n  const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};\n  const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)\n    ? aliases[trimmed]\n    : undefined;\n  return typeof aliased === \"string\" ? aliased : trimmed;\n}\n\n/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */\nexport function normalizeCustomModelSlug(model: string | null | undefined): string | null {\n  if (typeof model !== \"string\") {\n    return null;\n  }\n\n  return model.trim() || null;\n}\n\nexport function resolveSelectableModel(\n  provider: ProviderDriverKind,\n  value: string | null | undefined,\n  options: ReadonlyArray<SelectableModelOption>,\n): string | null {\n  if (typeof value !== \"string\") {\n    return null;\n  }\n\n  const trimmed = value.trim();\n  if (!trimmed) {\n    return null;\n  }\n\n  const direct = options.find((option) => option.slug === trimmed);\n  if (direct) {\n    return direct.slug;\n  }\n\n  const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());\n  if (byName) {\n    return byName.slug;\n  }\n\n  const normalized = normalizeModelSlug(trimmed, provider);\n  if (!normalized) {\n    return null;\n  }\n\n  const resolved = options.find((option) => option.slug === normalized);\n  return resolved ? resolved.slug : null;\n}\n\nfunction resolveModelSlug(model: string | null | undefined, provider: ProviderDriverKind): string {\n  const normalized = normalizeModelSlug(model, provider);\n  if (!normalized) {\n    return DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;\n  }\n  return normalized;\n}\n\nexport function resolveModelSlugForProvider(\n  provider: ProviderDriverKind,\n  model: string | null | undefined,\n): string {\n  return resolveModelSlug(model, provider);\n}\n\n/** Trim a string, returning null for empty/missing values. */\nexport function trimOrNull<T extends string>(value: T | null | undefined): T | null {\n  if (typeof value !== \"string\") return null;\n  const trimmed = value.trim() as T;\n  return trimmed || null;\n}\n\nfunction cloneSelections(\n  selections: ReadonlyArray<ProviderOptionSelection>,\n): Array<ProviderOptionSelection> {\n  return selections.map(cloneSelection);\n}\n\nexport function createModelSelection(\n  instanceId: ProviderInstanceId,\n  model: string,\n  options?: ReadonlyArray<ProviderOptionSelection> | null,\n): ModelSelection {\n  const selections = options ? cloneSelections(options) : [];\n  const base: ModelSelection = {\n    instanceId,\n    model,\n  };\n  return selections.length > 0 ? { ...base, options: selections } : base;\n}\n\n/**\n * Returns the effort value if it is a prompt-injected value according to\n * any select descriptor in the given capabilities, or null otherwise.\n *\n * Unlike a single `find`, this checks every descriptor so that the\n * correct descriptor's `promptInjectedValues` list is consulted even when\n * multiple select descriptors exist.\n */\nexport function resolvePromptInjectedEffort(\n  caps: ModelCapabilities,\n  rawEffort: string | null | undefined,\n): string | null {\n  const trimmed = trimOrNull(rawEffort);\n  if (!trimmed) return null;\n  const descriptors = getProviderOptionDescriptors({ caps });\n  for (const descriptor of descriptors) {\n    if (descriptor.type === \"select\" && descriptor.promptInjectedValues?.includes(trimmed)) {\n      return trimmed;\n    }\n  }\n  return null;\n}\n\nexport function applyClaudePromptEffortPrefix(\n  text: string,\n  effort: string | null | undefined,\n): string {\n  const trimmed = text.trim();\n  if (!trimmed) {\n    return trimmed;\n  }\n  if (effort !== \"ultrathink\") {\n    return trimmed;\n  }\n  if (trimmed.startsWith(\"Ultrathink:\")) {\n    return trimmed;\n  }\n  return `Ultrathink:\\n${trimmed}`;\n}\n","import {\n  type BackgroundActivityProfile,\n  type BackgroundActivitySettings,\n  DEFAULT_BACKGROUND_ACTIVITY_PROFILE,\n  DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,\n  DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,\n  type ServerSettings,\n} from \"@t3tools/contracts\";\nimport * as Duration from \"effect/Duration\";\n\nexport interface ResolvedBackgroundActivitySettings {\n  readonly profile: BackgroundActivityProfile;\n  readonly automaticGitFetchInterval: Duration.Duration;\n  readonly providerHealthRefreshInterval: Duration.Duration;\n  readonly hostPowerMonitorActiveInterval: Duration.Duration;\n  readonly hostPowerMonitorIdleInterval: Duration.Duration;\n  readonly idleClientTtl: Duration.Duration;\n  readonly pauseWhenHostLocked: boolean;\n  readonly pauseWhenHostLowPower: boolean;\n  readonly pauseWhenClientLowPower: boolean;\n  readonly pauseWhenOnBattery: boolean;\n}\n\nconst PRESET_SETTINGS: Record<BackgroundActivityProfile, ResolvedBackgroundActivitySettings> = {\n  performance: {\n    profile: \"performance\",\n    automaticGitFetchInterval: Duration.seconds(15),\n    providerHealthRefreshInterval: Duration.minutes(1),\n    hostPowerMonitorActiveInterval: Duration.seconds(30),\n    hostPowerMonitorIdleInterval: Duration.minutes(2),\n    idleClientTtl: Duration.seconds(45),\n    pauseWhenHostLocked: true,\n    pauseWhenHostLowPower: false,\n    pauseWhenClientLowPower: false,\n    pauseWhenOnBattery: false,\n  },\n  balanced: {\n    profile: \"balanced\",\n    automaticGitFetchInterval: DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,\n    providerHealthRefreshInterval: DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,\n    hostPowerMonitorActiveInterval: Duration.seconds(30),\n    hostPowerMonitorIdleInterval: Duration.minutes(5),\n    idleClientTtl: Duration.seconds(45),\n    pauseWhenHostLocked: true,\n    pauseWhenHostLowPower: true,\n    pauseWhenClientLowPower: true,\n    pauseWhenOnBattery: false,\n  },\n  \"battery-saver\": {\n    profile: \"battery-saver\",\n    automaticGitFetchInterval: Duration.seconds(0),\n    providerHealthRefreshInterval: Duration.minutes(15),\n    hostPowerMonitorActiveInterval: Duration.minutes(1),\n    hostPowerMonitorIdleInterval: Duration.minutes(10),\n    idleClientTtl: Duration.seconds(45),\n    pauseWhenHostLocked: true,\n    pauseWhenHostLowPower: true,\n    pauseWhenClientLowPower: true,\n    pauseWhenOnBattery: true,\n  },\n};\n\nexport function getBackgroundActivityPresetSettings(\n  profile: BackgroundActivityProfile,\n): ResolvedBackgroundActivitySettings {\n  return PRESET_SETTINGS[profile];\n}\n\nexport function getBackgroundActivityBaseProfile(\n  backgroundActivity: BackgroundActivitySettings,\n): BackgroundActivityProfile {\n  if (backgroundActivity.profile === \"custom\") {\n    return backgroundActivity.baseProfile ?? DEFAULT_BACKGROUND_ACTIVITY_PROFILE;\n  }\n  return backgroundActivity.profile;\n}\n\nexport function resolveBackgroundActivitySettings(\n  backgroundActivity: BackgroundActivitySettings,\n): ResolvedBackgroundActivitySettings {\n  const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);\n  const preset = PRESET_SETTINGS[baseProfile];\n  const overrides = backgroundActivity.profile === \"custom\" ? backgroundActivity.overrides : {};\n  return {\n    profile: baseProfile,\n    automaticGitFetchInterval:\n      overrides.automaticGitFetchInterval ?? preset.automaticGitFetchInterval,\n    providerHealthRefreshInterval:\n      overrides.providerHealthRefreshInterval ?? preset.providerHealthRefreshInterval,\n    hostPowerMonitorActiveInterval:\n      overrides.hostPowerMonitorActiveInterval ?? preset.hostPowerMonitorActiveInterval,\n    hostPowerMonitorIdleInterval:\n      overrides.hostPowerMonitorIdleInterval ?? preset.hostPowerMonitorIdleInterval,\n    idleClientTtl: overrides.idleClientTtl ?? preset.idleClientTtl,\n    pauseWhenHostLocked: overrides.pauseWhenHostLocked ?? preset.pauseWhenHostLocked,\n    pauseWhenHostLowPower: overrides.pauseWhenHostLowPower ?? preset.pauseWhenHostLowPower,\n    pauseWhenClientLowPower: overrides.pauseWhenClientLowPower ?? preset.pauseWhenClientLowPower,\n    pauseWhenOnBattery: overrides.pauseWhenOnBattery ?? preset.pauseWhenOnBattery,\n  };\n}\n\nfunction durationsEqual(a: Duration.Duration, b: Duration.Duration): boolean {\n  return Duration.toMillis(a) === Duration.toMillis(b);\n}\n\nfunction resolvedSettingsEqual(\n  a: ResolvedBackgroundActivitySettings,\n  b: ResolvedBackgroundActivitySettings,\n): boolean {\n  return (\n    durationsEqual(a.automaticGitFetchInterval, b.automaticGitFetchInterval) &&\n    durationsEqual(a.providerHealthRefreshInterval, b.providerHealthRefreshInterval) &&\n    durationsEqual(a.hostPowerMonitorActiveInterval, b.hostPowerMonitorActiveInterval) &&\n    durationsEqual(a.hostPowerMonitorIdleInterval, b.hostPowerMonitorIdleInterval) &&\n    durationsEqual(a.idleClientTtl, b.idleClientTtl) &&\n    a.pauseWhenHostLocked === b.pauseWhenHostLocked &&\n    a.pauseWhenHostLowPower === b.pauseWhenHostLowPower &&\n    a.pauseWhenClientLowPower === b.pauseWhenClientLowPower &&\n    a.pauseWhenOnBattery === b.pauseWhenOnBattery\n  );\n}\n\nexport function normalizeBackgroundActivitySettings(\n  backgroundActivity: BackgroundActivitySettings,\n): BackgroundActivitySettings {\n  if (backgroundActivity.profile !== \"custom\") {\n    return {\n      schemaVersion: 1,\n      profile: backgroundActivity.profile,\n      overrides: {},\n    };\n  }\n\n  const resolved = resolveBackgroundActivitySettings(backgroundActivity);\n  const profiles: ReadonlyArray<BackgroundActivityProfile> = [\n    getBackgroundActivityBaseProfile(backgroundActivity),\n    \"balanced\",\n    \"performance\",\n    \"battery-saver\",\n  ];\n  for (const profile of profiles) {\n    if (resolvedSettingsEqual(resolved, PRESET_SETTINGS[profile])) {\n      return {\n        schemaVersion: 1,\n        profile,\n        overrides: {},\n      };\n    }\n  }\n\n  const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);\n  const preset = PRESET_SETTINGS[baseProfile];\n  const overrides: BackgroundActivitySettings[\"overrides\"] = {\n    ...(!durationsEqual(resolved.automaticGitFetchInterval, preset.automaticGitFetchInterval)\n      ? { automaticGitFetchInterval: resolved.automaticGitFetchInterval }\n      : {}),\n    ...(!durationsEqual(\n      resolved.providerHealthRefreshInterval,\n      preset.providerHealthRefreshInterval,\n    )\n      ? { providerHealthRefreshInterval: resolved.providerHealthRefreshInterval }\n      : {}),\n    ...(!durationsEqual(\n      resolved.hostPowerMonitorActiveInterval,\n      preset.hostPowerMonitorActiveInterval,\n    )\n      ? { hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval }\n      : {}),\n    ...(!durationsEqual(resolved.hostPowerMonitorIdleInterval, preset.hostPowerMonitorIdleInterval)\n      ? { hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval }\n      : {}),\n    ...(!durationsEqual(resolved.idleClientTtl, preset.idleClientTtl)\n      ? { idleClientTtl: resolved.idleClientTtl }\n      : {}),\n    ...(resolved.pauseWhenHostLocked !== preset.pauseWhenHostLocked\n      ? { pauseWhenHostLocked: resolved.pauseWhenHostLocked }\n      : {}),\n    ...(resolved.pauseWhenHostLowPower !== preset.pauseWhenHostLowPower\n      ? { pauseWhenHostLowPower: resolved.pauseWhenHostLowPower }\n      : {}),\n    ...(resolved.pauseWhenClientLowPower !== preset.pauseWhenClientLowPower\n      ? { pauseWhenClientLowPower: resolved.pauseWhenClientLowPower }\n      : {}),\n    ...(resolved.pauseWhenOnBattery !== preset.pauseWhenOnBattery\n      ? { pauseWhenOnBattery: resolved.pauseWhenOnBattery }\n      : {}),\n  };\n\n  return {\n    schemaVersion: 1,\n    profile: \"custom\",\n    baseProfile,\n    overrides,\n  };\n}\n\nexport function resolveServerBackgroundActivitySettings(\n  settings: ServerSettings,\n): ResolvedBackgroundActivitySettings {\n  const defaultBackgroundActivity: BackgroundActivitySettings = {\n    schemaVersion: 1,\n    profile: DEFAULT_BACKGROUND_ACTIVITY_PROFILE,\n    overrides: {},\n  };\n  const backgroundActivityIsDefault =\n    settings.backgroundActivity.profile === defaultBackgroundActivity.profile &&\n    settings.backgroundActivity.baseProfile === undefined &&\n    Object.keys(settings.backgroundActivity.overrides).length === 0;\n  const legacyProfile = settings.backgroundActivityProfile;\n  const hasLegacyOverrides =\n    legacyProfile !== DEFAULT_BACKGROUND_ACTIVITY_PROFILE ||\n    Duration.toMillis(settings.automaticGitFetchInterval) !==\n      Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) ||\n    Duration.toMillis(settings.providerHealthRefreshInterval) !==\n      Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL);\n  if (backgroundActivityIsDefault && hasLegacyOverrides) {\n    return resolveBackgroundActivitySettings({\n      schemaVersion: 1,\n      profile:\n        Duration.toMillis(settings.automaticGitFetchInterval) ===\n          Duration.toMillis(\n            getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,\n          ) &&\n        Duration.toMillis(settings.providerHealthRefreshInterval) ===\n          Duration.toMillis(\n            getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,\n          )\n          ? legacyProfile\n          : \"custom\",\n      baseProfile: legacyProfile,\n      overrides: {\n        ...(Duration.toMillis(settings.automaticGitFetchInterval) !==\n        Duration.toMillis(\n          getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,\n        )\n          ? { automaticGitFetchInterval: settings.automaticGitFetchInterval }\n          : {}),\n        ...(Duration.toMillis(settings.providerHealthRefreshInterval) !==\n        Duration.toMillis(\n          getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,\n        )\n          ? { providerHealthRefreshInterval: settings.providerHealthRefreshInterval }\n          : {}),\n      },\n    });\n  }\n  return resolveBackgroundActivitySettings(settings.backgroundActivity);\n}\n\nexport function normalizeServerBackgroundActivitySettings(\n  settings: ServerSettings,\n): BackgroundActivitySettings {\n  const resolved = resolveServerBackgroundActivitySettings(settings);\n  return normalizeBackgroundActivitySettings({\n    schemaVersion: 1,\n    profile: \"custom\",\n    baseProfile: resolved.profile,\n    overrides: {\n      automaticGitFetchInterval: resolved.automaticGitFetchInterval,\n      providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,\n      hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,\n      hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,\n      idleClientTtl: resolved.idleClientTtl,\n      pauseWhenHostLocked: resolved.pauseWhenHostLocked,\n      pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,\n      pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,\n      pauseWhenOnBattery: resolved.pauseWhenOnBattery,\n    },\n  });\n}\n","import {\n  isProviderDriverKind,\n  isProviderAvailable,\n  type ModelSelection,\n  type ProviderDriverKind,\n  type ServerProvider,\n  ServerSettings,\n  type ServerSettingsPatch,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { deepMerge } from \"./Struct.ts\";\nimport { fromLenientJson } from \"./schemaJson.ts\";\nimport { createModelSelection } from \"./model.ts\";\nimport {\n  getBackgroundActivityBaseProfile,\n  normalizeBackgroundActivitySettings,\n  normalizeServerBackgroundActivitySettings,\n  resolveBackgroundActivitySettings,\n} from \"./backgroundActivitySettings.ts\";\n\nconst ServerSettingsJson = fromLenientJson(ServerSettings);\nconst decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);\n\ntype LegacyProviderSettings = ServerSettings[\"providers\"][keyof ServerSettings[\"providers\"]];\n\nconst getLegacyProviderSettings = (\n  settings: ServerSettings,\n  provider: ProviderDriverKind,\n): LegacyProviderSettings | undefined =>\n  (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];\n\nexport function isModelSelectionProviderEnabled(\n  settings: ServerSettings,\n  selection: ModelSelection,\n): boolean {\n  const instanceConfig = settings.providerInstances[selection.instanceId];\n  if (instanceConfig !== undefined) {\n    return instanceConfig.enabled ?? true;\n  }\n\n  return (\n    isProviderDriverKind(selection.instanceId) &&\n    getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true\n  );\n}\n\nexport function resolveSourceControlWriterModelSelection(\n  settings: ServerSettings,\n  providers?: ReadonlyArray<ServerProvider>,\n): ModelSelection {\n  const selection = settings.sourceControlWriterModelSelection;\n  if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {\n    return settings.textGenerationModelSelection;\n  }\n  if (providers === undefined) {\n    return selection;\n  }\n\n  const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);\n  return provider?.enabled === true && isProviderAvailable(provider)\n    ? selection\n    : settings.textGenerationModelSelection;\n}\n\nexport interface PersistedServerObservabilitySettings {\n  readonly otlpTracesUrl: string | undefined;\n  readonly otlpMetricsUrl: string | undefined;\n}\n\nexport function normalizePersistedServerSettingString(\n  value: string | null | undefined,\n): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function extractPersistedServerObservabilitySettings(input: {\n  readonly observability?: {\n    readonly otlpTracesUrl?: string;\n    readonly otlpMetricsUrl?: string;\n  };\n}): PersistedServerObservabilitySettings {\n  return {\n    otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),\n    otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),\n  };\n}\n\nexport function parsePersistedServerObservabilitySettings(\n  raw: string,\n): PersistedServerObservabilitySettings {\n  const decoded = decodeServerSettingsJson(raw);\n  if (Option.isSome(decoded)) {\n    return extractPersistedServerObservabilitySettings(decoded.value);\n  }\n  return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };\n}\n\nfunction shouldReplaceTextGenerationModelSelection(\n  patch: ServerSettingsPatch[\"textGenerationModelSelection\"] | undefined,\n): boolean {\n  return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));\n}\n\nfunction mergeModelSelectionOptionsById(input: {\n  current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;\n  patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;\n}): Array<{ id: string; value: string | boolean }> | undefined {\n  if (input.patch === undefined) {\n    return input.current ? [...input.current] : undefined;\n  }\n  if (input.patch.length === 0) {\n    return undefined;\n  }\n\n  const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));\n  for (const selection of input.patch) {\n    merged.set(selection.id, selection.value);\n  }\n  return [...merged.entries()].map(([id, value]) => ({ id, value }));\n}\n\nexport function applyServerSettingsPatch(\n  current: ServerSettings,\n  patch: ServerSettingsPatch,\n): ServerSettings {\n  const selectionPatch = patch.textGenerationModelSelection;\n  const {\n    automaticGitFetchInterval,\n    providerHealthRefreshInterval,\n    backgroundActivityProfile,\n    backgroundActivity,\n    ...patchForMerge\n  } = patch;\n  const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);\n  const backgroundActivityPatch =\n    backgroundActivityProfile !== undefined\n      ? {\n          schemaVersion: 1 as const,\n          profile:\n            automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined\n              ? (\"custom\" as const)\n              : backgroundActivityProfile,\n          ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined\n            ? { baseProfile: backgroundActivityProfile }\n            : {}),\n          overrides: {\n            ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),\n            ...(providerHealthRefreshInterval !== undefined\n              ? { providerHealthRefreshInterval }\n              : {}),\n          },\n        }\n      : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined\n        ? {\n            schemaVersion: 1 as const,\n            profile: \"custom\" as const,\n            baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),\n            overrides: {\n              ...(currentBackgroundActivity.profile === \"custom\"\n                ? currentBackgroundActivity.overrides\n                : {}),\n              ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),\n              ...(providerHealthRefreshInterval !== undefined\n                ? { providerHealthRefreshInterval }\n                : {}),\n            },\n          }\n        : undefined;\n  const next = deepMerge(current, patchForMerge);\n  const nextWithReplacementsBase = {\n    ...next,\n    ...(backgroundActivity !== undefined\n      ? {\n          backgroundActivity: {\n            ...deepMerge(currentBackgroundActivity, backgroundActivity),\n            ...(backgroundActivity.overrides !== undefined\n              ? { overrides: backgroundActivity.overrides }\n              : {}),\n          },\n        }\n      : { backgroundActivity: currentBackgroundActivity }),\n    ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined\n      ? { backgroundActivity: backgroundActivityPatch }\n      : {}),\n    ...(patch.providerInstances !== undefined\n      ? { providerInstances: patch.providerInstances }\n      : {}),\n    ...(patch.sourceControlWriterModelSelection !== undefined\n      ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }\n      : {}),\n    ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),\n    ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),\n  };\n  const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(\n    nextWithReplacementsBase.backgroundActivity,\n  );\n  const resolvedBackgroundActivity = resolveBackgroundActivitySettings(\n    normalizedBackgroundActivity,\n  );\n  const nextWithReplacements = {\n    ...nextWithReplacementsBase,\n    backgroundActivity: normalizedBackgroundActivity,\n    automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,\n    providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,\n    backgroundActivityProfile: resolvedBackgroundActivity.profile,\n  };\n  if (!selectionPatch) {\n    return nextWithReplacements;\n  }\n\n  const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;\n  const model = selectionPatch.model ?? current.textGenerationModelSelection.model;\n  const options = shouldReplaceTextGenerationModelSelection(selectionPatch)\n    ? selectionPatch.options\n    : mergeModelSelectionOptionsById({\n        current: current.textGenerationModelSelection.options,\n        patch: selectionPatch.options,\n      });\n\n  return {\n    ...nextWithReplacements,\n    textGenerationModelSelection: createModelSelection(instanceId, model, options),\n  };\n}\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as NodeOS from \"node:os\";\n\nexport const HostProcessPlatform = Context.Reference<NodeJS.Platform>(\n  \"@t3tools/shared/hostProcess/HostProcessPlatform\",\n  {\n    defaultValue: () => process.platform,\n  },\n);\n\nexport const HostProcessArchitecture = Context.Reference<NodeJS.Architecture>(\n  \"@t3tools/shared/hostProcess/HostProcessArchitecture\",\n  {\n    defaultValue: () => process.arch,\n  },\n);\n\nexport const HostProcessHostname = Context.Reference<string>(\n  \"@t3tools/shared/hostProcess/HostProcessHostname\",\n  {\n    defaultValue: () => NodeOS.hostname(),\n  },\n);\n\nexport const HostProcessEnvironment = Context.Reference<NodeJS.ProcessEnv>(\n  \"@t3tools/shared/hostProcess/HostProcessEnvironment\",\n  {\n    defaultValue: () => process.env,\n  },\n);\n\nexport const HostProcessWorkingDirectory = Context.Reference<string>(\n  \"@t3tools/shared/hostProcess/HostProcessWorkingDirectory\",\n  {\n    defaultValue: () => process.cwd(),\n  },\n);\n\nexport const HostProcessExecutablePath = Context.Reference<string>(\n  \"@t3tools/shared/hostProcess/HostProcessExecutablePath\",\n  {\n    defaultValue: () => process.execPath,\n  },\n);\n\nexport const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(\n  \"@t3tools/shared/hostProcess/HostProcessArguments\",\n  {\n    defaultValue: () => process.argv,\n  },\n);\n\nexport const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === \"win32\");\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodeNet from \"node:net\";\nimport * as NodeReadline from \"node:readline\";\nimport type * as NodeStream from \"node:stream\";\n\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { decodeJsonResult } from \"@t3tools/shared/schemaJson\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\n\nexport class BootstrapFdStatError extends Schema.TaggedErrorClass<BootstrapFdStatError>()(\n  \"BootstrapFdStatError\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to stat bootstrap file descriptor ${this.fd}.`;\n  }\n}\n\nexport class BootstrapInputStreamOpenError extends Schema.TaggedErrorClass<BootstrapInputStreamOpenError>()(\n  \"BootstrapInputStreamOpenError\",\n  {\n    fd: Schema.Number,\n    platform: Schema.String,\n    fdPath: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const path = this.fdPath === undefined ? \"\" : ` via '${this.fdPath}'`;\n    return `Failed to open bootstrap input stream for file descriptor ${this.fd}${path} on '${this.platform}'.`;\n  }\n}\n\nexport class BootstrapEnvelopeReadError extends Schema.TaggedErrorClass<BootstrapEnvelopeReadError>()(\n  \"BootstrapEnvelopeReadError\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read bootstrap envelope from file descriptor ${this.fd}.`;\n  }\n}\n\nexport class BootstrapEnvelopeDecodeError extends Schema.TaggedErrorClass<BootstrapEnvelopeDecodeError>()(\n  \"BootstrapEnvelopeDecodeError\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to decode bootstrap envelope from file descriptor ${this.fd}.`;\n  }\n}\n\nexport const BootstrapError = Schema.Union([\n  BootstrapFdStatError,\n  BootstrapInputStreamOpenError,\n  BootstrapEnvelopeReadError,\n  BootstrapEnvelopeDecodeError,\n]);\nexport type BootstrapError = typeof BootstrapError.Type;\n\nexport const readBootstrapEnvelope = Effect.fn(\"readBootstrapEnvelope\")(function* <A, I>(\n  schema: Schema.Codec<A, I>,\n  fd: number,\n  options?: {\n    timeoutMs?: number;\n  },\n): Effect.fn.Return<Option.Option<A>, BootstrapError> {\n  const fdReady = yield* isFdReady(fd);\n  if (!fdReady) return Option.none();\n\n  const stream = yield* makeBootstrapInputStream(fd);\n\n  const timeoutMs = options?.timeoutMs ?? 1000;\n\n  return yield* Effect.callback<\n    Option.Option<A>,\n    BootstrapEnvelopeReadError | BootstrapEnvelopeDecodeError\n  >((resume) => {\n    const input = NodeReadline.createInterface({\n      input: stream,\n      crlfDelay: Infinity,\n    });\n\n    const cleanup = () => {\n      stream.removeListener(\"error\", handleError);\n      input.removeListener(\"line\", handleLine);\n      input.removeListener(\"close\", handleClose);\n      input.close();\n      stream.destroy();\n    };\n\n    const handleError = (error: Error) => {\n      if (isUnavailableBootstrapFdError(error)) {\n        resume(Effect.succeedNone);\n        return;\n      }\n      resume(\n        Effect.fail(\n          new BootstrapEnvelopeReadError({\n            fd,\n            cause: error,\n          }),\n        ),\n      );\n    };\n\n    const handleLine = (line: string) => {\n      const parsed = decodeJsonResult(schema)(line);\n      if (Result.isSuccess(parsed)) {\n        resume(Effect.succeedSome(parsed.success));\n      } else {\n        resume(\n          Effect.fail(\n            new BootstrapEnvelopeDecodeError({\n              fd,\n              cause: parsed.failure,\n            }),\n          ),\n        );\n      }\n    };\n\n    const handleClose = () => {\n      resume(Effect.succeedNone);\n    };\n\n    stream.once(\"error\", handleError);\n    input.once(\"line\", handleLine);\n    input.once(\"close\", handleClose);\n\n    return Effect.sync(cleanup);\n  }).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));\n});\n\nconst isUnavailableBootstrapFdError = Predicate.compose(\n  Predicate.hasProperty(\"code\"),\n  (_) => _.code === \"EBADF\" || _.code === \"ENOENT\",\n);\n\nconst isFdReady = (fd: number) =>\n  Effect.try({\n    try: () => NodeFS.fstatSync(fd),\n    catch: (error) =>\n      new BootstrapFdStatError({\n        fd,\n        cause: error,\n      }),\n  }).pipe(\n    Effect.as(true),\n    Effect.catchTags({\n      BootstrapFdStatError: (error) =>\n        isUnavailableBootstrapFdError(error.cause) ? Effect.succeed(false) : Effect.fail(error),\n    }),\n  );\n\nconst makeBootstrapInputStream = (fd: number) =>\n  Effect.gen(function* () {\n    const platform = yield* HostProcessPlatform;\n    const fdPath = resolveFdPath(fd, platform);\n    return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({\n      try: () => {\n        if (fdPath === undefined) {\n          return makeDirectBootstrapStream(fd);\n        }\n\n        let streamFd: number | undefined;\n        try {\n          streamFd = NodeFS.openSync(fdPath, \"r\");\n          return NodeFS.createReadStream(\"\", {\n            fd: streamFd,\n            encoding: \"utf8\",\n            autoClose: true,\n          });\n        } catch (error) {\n          if (isBootstrapFdPathDuplicationError(error)) {\n            if (streamFd !== undefined) {\n              NodeFS.closeSync(streamFd);\n            }\n            return makeDirectBootstrapStream(fd);\n          }\n          throw error;\n        }\n      },\n      catch: (error) =>\n        new BootstrapInputStreamOpenError({\n          fd,\n          platform,\n          ...(fdPath === undefined ? {} : { fdPath }),\n          cause: error,\n        }),\n    });\n  });\n\nconst makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {\n  try {\n    return NodeFS.createReadStream(\"\", {\n      fd,\n      encoding: \"utf8\",\n      autoClose: true,\n    });\n  } catch {\n    const stream = new NodeNet.Socket({\n      fd,\n      readable: true,\n      writable: false,\n    });\n    stream.setEncoding(\"utf8\");\n    return stream;\n  }\n};\n\n// Stdin pipes inherited across the wsl.exe boundary report EACCES when we try\n// to re-open them via /proc/self/fd/0 — fall back to reading the fd directly\n// in that case, the same way we already do for ENXIO/EINVAL/EPERM.\nconst isBootstrapFdPathDuplicationError = Predicate.compose(\n  Predicate.hasProperty(\"code\"),\n  (_) => _.code === \"ENXIO\" || _.code === \"EINVAL\" || _.code === \"EPERM\" || _.code === \"EACCES\",\n);\n\nfunction resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {\n  if (platform === \"linux\") {\n    return `/proc/self/fd/${fd}`;\n  }\n  if (platform === \"win32\") {\n    return undefined;\n  }\n  return `/dev/fd/${fd}`;\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\nimport * as NodeChildProcess from \"node:child_process\";\nimport * as NodeFS from \"node:fs\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\n\nimport { HostProcessEnvironment, HostProcessPlatform } from \"./hostProcess.ts\";\nimport * as Context from \"effect/Context\";\n\nconst PATH_CAPTURE_START = \"__T3CODE_PATH_START__\";\nconst PATH_CAPTURE_END = \"__T3CODE_PATH_END__\";\nconst SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;\nconst WINDOWS_PATH_DELIMITER = \";\";\nconst POSIX_PATH_DELIMITER = \":\";\nconst WINDOWS_SHELL_CANDIDATES = [\"pwsh.exe\", \"powershell.exe\"] as const;\n\ntype ExecFileSyncLike = (\n  file: string,\n  args: ReadonlyArray<string>,\n  options: { encoding: \"utf8\"; timeout: number },\n) => string;\n\nfunction canExecuteFile(filePath: string): boolean {\n  try {\n    NodeFS.accessSync(filePath, NodeFS.constants.X_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport interface CommandAvailabilityOptions {\n  readonly env?: NodeJS.ProcessEnv;\n  readonly extendEnv?: boolean;\n}\n\nexport type CommandAvailabilityChecker = (\n  command: string,\n  options?: CommandAvailabilityOptions,\n) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;\n\nexport class CommandResolutionError extends Data.TaggedError(\"CommandResolutionError\")<{\n  readonly command: string;\n  readonly reason: \"not-found\";\n}> {}\n\nconst WINDOWS_SHELL_META_CHARS = /([()\\][%!^\"`<>&|;, *?])/g;\n\n/**\n * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`\n * on Windows). Node joins the command and arguments with spaces and hands the\n * resulting string to `cmd.exe` without any quoting, so every dynamic argument\n * must be escaped to survive both cmd.exe parsing and the target program's\n * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.\n */\nfunction escapeWindowsShellArg(arg: string): string {\n  // Double up backslashes that precede a double quote, then escape the quote\n  // itself so it survives CommandLineToArgvW.\n  let escaped = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n  // Double up trailing backslashes so the closing quote is not escaped away.\n  escaped = escaped.replace(/(\\\\*)$/, \"$1$1\");\n  // Quote the whole argument so embedded whitespace is preserved.\n  escaped = `\"${escaped}\"`;\n  // Escape cmd.exe metacharacters so cmd passes them through verbatim.\n  return escaped.replace(WINDOWS_SHELL_META_CHARS, \"^$1\");\n}\n\n/**\n * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}\n * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)\n * and returns the arguments untouched everywhere else.\n */\nfunction sanitizeShellModeArgsForPlatform(\n  args: ReadonlyArray<string>,\n  platform: NodeJS.Platform,\n): Array<string> {\n  return platform === \"win32\" ? args.map(escapeWindowsShellArg) : [...args];\n}\n\nexport interface ResolvedSpawnCommand {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly shell: boolean;\n}\n\nexport type SpawnExecutableResolver = (\n  command: string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n) => string | undefined;\n\nfunction resolveSpawnExecutableWithNode(\n  command: string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n): string | undefined {\n  const path = platform === \"win32\" ? NodePath.win32 : NodePath.posix;\n  const windowsPathExtensions = platform === \"win32\" ? resolveWindowsPathExtensions(env) : [];\n  const candidates = resolveCommandCandidates(\n    command,\n    platform,\n    windowsPathExtensions,\n    path.extname,\n  );\n  const isExecutable = (candidate: string) => {\n    try {\n      if (!NodeFS.statSync(candidate).isFile()) return false;\n      if (platform === \"win32\") {\n        return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());\n      }\n      return canExecuteFile(candidate);\n    } catch {\n      return false;\n    }\n  };\n\n  if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n    return candidates.find(isExecutable);\n  }\n\n  for (const pathEntry of (readEnvPath(env) ?? \"\").split(pathDelimiterForPlatform(platform))) {\n    const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());\n    if (normalizedPathEntry.length === 0) continue;\n    for (const candidate of candidates) {\n      const candidatePath = path.join(normalizedPathEntry, candidate);\n      if (isExecutable(candidatePath)) return candidatePath;\n    }\n  }\n  return undefined;\n}\n\nexport const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(\n  \"@t3tools/shared/shell/SpawnExecutableResolution\",\n  {\n    defaultValue: () => resolveSpawnExecutableWithNode,\n  },\n);\n\nexport interface WindowsEnvironmentProbeOptions {\n  readonly loadProfile?: boolean;\n}\n\nfunction trimNonEmpty(value: string | null | undefined): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction readUserLoginShell(): string | undefined {\n  try {\n    return trimNonEmpty(NodeOS.userInfo().shell);\n  } catch {\n    return undefined;\n  }\n}\n\nexport function listLoginShellCandidates(\n  platform: NodeJS.Platform,\n  shell: string | undefined,\n  userShell = readUserLoginShell(),\n): ReadonlyArray<string> {\n  const fallbackShell =\n    platform === \"darwin\" ? \"/bin/zsh\" : platform === \"linux\" ? \"/bin/bash\" : undefined;\n  const seen = new Set<string>();\n  const candidates: string[] = [];\n\n  for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {\n    if (!candidate || seen.has(candidate)) {\n      continue;\n    }\n    seen.add(candidate);\n    candidates.push(candidate);\n  }\n\n  return candidates;\n}\n\nexport function extractPathFromShellOutput(output: string): string | null {\n  const startIndex = output.indexOf(PATH_CAPTURE_START);\n  if (startIndex === -1) return null;\n\n  const valueStartIndex = startIndex + PATH_CAPTURE_START.length;\n  const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);\n  if (endIndex === -1) return null;\n\n  const pathValue = output.slice(valueStartIndex, endIndex).trim();\n  return pathValue.length > 0 ? pathValue : null;\n}\n\nexport function readPathFromLoginShell(\n  shell: string,\n  execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,\n): string | undefined {\n  return readEnvironmentFromLoginShell(shell, [\"PATH\"], execFile).PATH;\n}\n\nexport function readPathFromLaunchctl(\n  execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,\n): string | undefined {\n  try {\n    return trimNonEmpty(\n      execFile(\"/bin/launchctl\", [\"getenv\", \"PATH\"], {\n        encoding: \"utf8\",\n        timeout: 2000,\n      }),\n    );\n  } catch {\n    return undefined;\n  }\n}\n\nexport function mergePathEntries(\n  preferredPath: string | undefined,\n  inheritedPath: string | undefined,\n  platform: NodeJS.Platform,\n): string | undefined {\n  const delimiter = platform === \"win32\" ? \";\" : \":\";\n  const merged: string[] = [];\n  const seen = new Set<string>();\n\n  for (const pathValue of [preferredPath, inheritedPath]) {\n    if (!pathValue) continue;\n    for (const entry of pathValue.split(delimiter)) {\n      const trimmedEntry = entry.trim();\n      if (!trimmedEntry || seen.has(trimmedEntry)) {\n        continue;\n      }\n      seen.add(trimmedEntry);\n      merged.push(trimmedEntry);\n    }\n  }\n\n  return merged.length > 0 ? merged.join(delimiter) : undefined;\n}\n\nfunction envCaptureStart(name: string): string {\n  return `__T3CODE_ENV_${name}_START__`;\n}\n\nfunction envCaptureEnd(name: string): string {\n  return `__T3CODE_ENV_${name}_END__`;\n}\n\nfunction buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {\n  return names\n    .map((name) => {\n      if (!SHELL_ENV_NAME_PATTERN.test(name)) {\n        throw new Error(`Unsupported environment variable name: ${name}`);\n      }\n\n      return [\n        `printf '%s\\\\n' '${envCaptureStart(name)}'`,\n        `printenv ${name} || true`,\n        `printf '%s\\\\n' '${envCaptureEnd(name)}'`,\n      ].join(\"; \");\n    })\n    .join(\"; \");\n}\n\nfunction buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {\n  return [\n    \"$ErrorActionPreference = 'Stop'\",\n    ...names.flatMap((name) => {\n      if (!SHELL_ENV_NAME_PATTERN.test(name)) {\n        throw new Error(`Unsupported environment variable name: ${name}`);\n      }\n\n      return [\n        `Write-Output '${envCaptureStart(name)}'`,\n        `$value = [Environment]::GetEnvironmentVariable('${name}')`,\n        \"if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }\",\n        `Write-Output '${envCaptureEnd(name)}'`,\n      ];\n    }),\n  ].join(\"; \");\n}\n\nfunction extractEnvironmentValue(output: string, name: string): string | undefined {\n  const startMarker = envCaptureStart(name);\n  const endMarker = envCaptureEnd(name);\n  const startIndex = output.indexOf(startMarker);\n  if (startIndex === -1) return undefined;\n\n  const valueStartIndex = startIndex + startMarker.length;\n  const endIndex = output.indexOf(endMarker, valueStartIndex);\n  if (endIndex === -1) return undefined;\n\n  const value = output\n    .slice(valueStartIndex, endIndex)\n    .replace(/^\\r?\\n/, \"\")\n    .replace(/\\r?\\n$/, \"\");\n\n  return value.length > 0 ? value : undefined;\n}\n\nexport type ShellEnvironmentReader = (\n  shell: string,\n  names: ReadonlyArray<string>,\n  execFile?: ExecFileSyncLike,\n) => Partial<Record<string, string>>;\n\nexport const readEnvironmentFromLoginShell: ShellEnvironmentReader = (\n  shell,\n  names,\n  execFile = NodeChildProcess.execFileSync,\n) => {\n  if (names.length === 0) {\n    return {};\n  }\n\n  const output = execFile(shell, [\"-ilc\", buildEnvironmentCaptureCommand(names)], {\n    encoding: \"utf8\",\n    timeout: 5000,\n  });\n\n  const environment: Partial<Record<string, string>> = {};\n  for (const name of names) {\n    const value = extractEnvironmentValue(output, name);\n    if (value !== undefined) {\n      environment[name] = value;\n    }\n  }\n\n  return environment;\n};\n\nexport type WindowsShellEnvironmentReader = (\n  names: ReadonlyArray<string>,\n  options?: WindowsEnvironmentProbeOptions,\n) => Partial<Record<string, string>>;\n\nexport const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(\n  \"@t3tools/shared/shell/WindowsShellEnvironment\",\n  {\n    defaultValue: () => readEnvironmentFromWindowsShell,\n  },\n);\n\nexport const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(\n  \"@t3tools/shared/shell/CommandAvailability\",\n  {\n    defaultValue: () => isCommandAvailable,\n  },\n);\n\nexport function readEnvironmentFromWindowsShell(\n  names: ReadonlyArray<string>,\n  execFile?: ExecFileSyncLike,\n): Partial<Record<string, string>>;\nexport function readEnvironmentFromWindowsShell(\n  names: ReadonlyArray<string>,\n  options?: WindowsEnvironmentProbeOptions,\n  execFile?: ExecFileSyncLike,\n): Partial<Record<string, string>>;\nexport function readEnvironmentFromWindowsShell(\n  names: ReadonlyArray<string>,\n  optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,\n  maybeExecFile?: ExecFileSyncLike,\n): Partial<Record<string, string>> {\n  if (names.length === 0) {\n    return {};\n  }\n\n  const options =\n    typeof optionsOrExecFile === \"function\"\n      ? ({} satisfies WindowsEnvironmentProbeOptions)\n      : (optionsOrExecFile ?? {});\n  const execFile: ExecFileSyncLike =\n    typeof optionsOrExecFile === \"function\"\n      ? optionsOrExecFile\n      : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));\n  const command = buildWindowsEnvironmentCaptureCommand(names);\n  const args = [\n    \"-NoLogo\",\n    ...(options.loadProfile ? ([] as const) : ([\"-NoProfile\"] as const)),\n    \"-NonInteractive\",\n    \"-Command\",\n    command,\n  ];\n  for (const shell of WINDOWS_SHELL_CANDIDATES) {\n    try {\n      const output = execFile(shell, args, { encoding: \"utf8\", timeout: 5000 });\n\n      const environment: Partial<Record<string, string>> = {};\n      for (const name of names) {\n        const value = extractEnvironmentValue(output, name);\n        if (value !== undefined) {\n          environment[name] = value;\n        }\n      }\n      return environment;\n    } catch {\n      continue;\n    }\n  }\n\n  return {};\n}\n\nfunction stripWrappingQuotes(value: string): string {\n  return value.replace(/^\"+|\"+$/g, \"\");\n}\n\nfunction pathDelimiterForPlatform(platform: NodeJS.Platform): string {\n  return platform === \"win32\" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;\n}\n\nfunction normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {\n  const normalized = stripWrappingQuotes(entry.trim());\n  return platform === \"win32\" ? normalized.toLowerCase() : normalized;\n}\n\nexport function mergePathValues(\n  preferredPath: string | undefined,\n  inheritedPath: string | undefined,\n  platform: NodeJS.Platform,\n): string | undefined {\n  const delimiter = pathDelimiterForPlatform(platform);\n  const merged: string[] = [];\n  const seen = new Set<string>();\n\n  for (const rawValue of [preferredPath, inheritedPath]) {\n    if (!rawValue) continue;\n\n    for (const entry of rawValue.split(delimiter)) {\n      const trimmed = entry.trim();\n      if (trimmed.length === 0) continue;\n\n      const normalized = normalizePathEntryForComparison(trimmed, platform);\n      if (normalized.length === 0 || seen.has(normalized)) continue;\n\n      seen.add(normalized);\n      merged.push(trimmed);\n    }\n  }\n\n  return merged.length > 0 ? merged.join(delimiter) : undefined;\n}\n\nfunction readEnvPath(env: NodeJS.ProcessEnv): string | undefined {\n  return env.PATH ?? env.Path ?? env.path;\n}\n\nfunction resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {\n  return readEnvPath(env) ?? \"\";\n}\n\nfunction resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {\n  const rawValue = env.PATHEXT;\n  const fallback = [\".COM\", \".EXE\", \".BAT\", \".CMD\"];\n  if (!rawValue) return fallback;\n\n  const parsed: string[] = [];\n  for (const entry of rawValue.split(\";\")) {\n    const trimmed = entry.trim();\n    if (trimmed.length === 0) continue;\n    parsed.push(trimmed.startsWith(\".\") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);\n  }\n  return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;\n}\n\nfunction resolveCommandCandidates(\n  command: string,\n  platform: NodeJS.Platform,\n  windowsPathExtensions: ReadonlyArray<string>,\n  extname: (path: string) => string,\n): ReadonlyArray<string> {\n  if (platform !== \"win32\") return [command];\n  const extension = extname(command);\n  const normalizedExtension = extension.toUpperCase();\n\n  if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {\n    const commandWithoutExtension = command.slice(0, -extension.length);\n    return Array.from(\n      new Set([\n        command,\n        `${commandWithoutExtension}${normalizedExtension}`,\n        `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,\n      ]),\n    );\n  }\n\n  const candidates: string[] = [];\n  for (const candidateExtension of windowsPathExtensions) {\n    candidates.push(`${command}${candidateExtension}`);\n    candidates.push(`${command}${candidateExtension.toLowerCase()}`);\n  }\n  return Array.from(new Set(candidates));\n}\n\nconst isExecutableFile = Effect.fn(\"shell.isExecutableFile\")(function* (\n  filePath: string,\n  platform: NodeJS.Platform,\n  windowsPathExtensions: ReadonlyArray<string>,\n): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));\n  if (stat === null || stat.type !== \"File\") return false;\n\n  if (platform === \"win32\") {\n    const extension = path.extname(filePath);\n    if (extension.length === 0) return false;\n    return windowsPathExtensions.includes(extension.toUpperCase());\n  }\n\n  return canExecuteFile(filePath);\n});\n\nconst resolveCommandPathForPlatform = Effect.fn(\"shell.resolveCommandPathForPlatform\")(function* (\n  command: string,\n  options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },\n): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {\n  const path = yield* Path.Path;\n  const platform = options.platform;\n  const env = options.env ?? process.env;\n  const windowsPathExtensions = platform === \"win32\" ? resolveWindowsPathExtensions(env) : [];\n  const commandCandidates = resolveCommandCandidates(\n    command,\n    platform,\n    windowsPathExtensions,\n    path.extname,\n  );\n\n  if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n    for (const candidate of commandCandidates) {\n      if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {\n        return candidate;\n      }\n    }\n    return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n  }\n\n  const pathValue = resolvePathEnvironmentVariable(env);\n  if (pathValue.length === 0) {\n    return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n  }\n  const pathEntries: string[] = [];\n  for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {\n    const pathEntry = stripWrappingQuotes(entry.trim());\n    if (pathEntry.length > 0) {\n      pathEntries.push(pathEntry);\n    }\n  }\n\n  for (const pathEntry of pathEntries) {\n    for (const candidate of commandCandidates) {\n      const candidatePath = path.join(pathEntry, candidate);\n      if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {\n        return candidatePath;\n      }\n    }\n  }\n  return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n});\n\nexport const resolveCommandPath = Effect.fn(\"shell.resolveCommandPath\")(function* (\n  command: string,\n  options: CommandAvailabilityOptions = {},\n) {\n  return yield* resolveCommandPathForPlatform(command, {\n    env: options.env ?? (yield* HostProcessEnvironment),\n    platform: yield* HostProcessPlatform,\n  });\n});\n\nexport const resolveSpawnCommand = Effect.fn(\"shell.resolveSpawnCommand\")(function* (\n  command: string,\n  args: ReadonlyArray<string>,\n  options: CommandAvailabilityOptions = {},\n): Effect.fn.Return<ResolvedSpawnCommand> {\n  const platform = yield* HostProcessPlatform;\n  if (platform !== \"win32\") {\n    return { command, args: [...args], shell: false };\n  }\n\n  const hostEnvironment = yield* HostProcessEnvironment;\n  const env =\n    options.env === undefined\n      ? hostEnvironment\n      : options.extendEnv\n        ? { ...hostEnvironment, ...options.env }\n        : options.env;\n  const resolveExecutable = yield* SpawnExecutableResolution;\n  const resolvedCommand = resolveExecutable(command, platform, env) ?? command;\n  const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();\n  if (extension !== \".cmd\" && extension !== \".bat\") {\n    return { command: resolvedCommand, args: [...args], shell: false };\n  }\n\n  return {\n    command: escapeWindowsShellArg(resolvedCommand),\n    args: sanitizeShellModeArgsForPlatform(args, platform),\n    shell: true,\n  };\n});\n\nexport const isCommandAvailable = Effect.fn(\"shell.isCommandAvailable\")(function* (\n  command: string,\n  options: CommandAvailabilityOptions = {},\n) {\n  return yield* resolveCommandPath(command, options).pipe(\n    Effect.as(true),\n    Effect.catchTag(\"CommandResolutionError\", () => Effect.succeed(false)),\n  );\n});\n\nexport function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {\n  const appData = env.APPDATA?.trim();\n  const localAppData = env.LOCALAPPDATA?.trim();\n  const userProfile = env.USERPROFILE?.trim();\n\n  return [\n    ...(appData ? [`${appData}\\\\npm`] : []),\n    ...(localAppData ? [`${localAppData}\\\\Programs\\\\nodejs`, `${localAppData}\\\\Volta\\\\bin`] : []),\n    ...(localAppData ? [`${localAppData}\\\\pnpm`] : []),\n    ...(userProfile ? [`${userProfile}\\\\.bun\\\\bin`, `${userProfile}\\\\scoop\\\\shims`] : []),\n  ];\n}\n\nfunction readWindowsEnvironmentSafely(\n  readEnvironment: WindowsShellEnvironmentReader,\n  names: ReadonlyArray<string>,\n  options?: WindowsEnvironmentProbeOptions,\n): Partial<Record<string, string>> {\n  try {\n    return readEnvironment(names, options);\n  } catch {\n    return {};\n  }\n}\n\nfunction mergeWindowsEnv(\n  currentEnv: NodeJS.ProcessEnv,\n  patch: Partial<Record<string, string>>,\n): NodeJS.ProcessEnv {\n  const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };\n  for (const [key, value] of Object.entries(patch)) {\n    if (value !== undefined) {\n      nextEnv[key] = value;\n    }\n  }\n  return nextEnv;\n}\n\nexport const resolveWindowsEnvironment = Effect.fn(\"shell.resolveWindowsEnvironment\")(function* (\n  env: NodeJS.ProcessEnv,\n): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {\n  const readEnvironment = yield* WindowsShellEnvironment;\n  const commandAvailable = yield* CommandAvailability;\n  const inheritedPath = readEnvPath(env);\n  const shellPath = readWindowsEnvironmentSafely(readEnvironment, [\"PATH\"], {\n    loadProfile: false,\n  }).PATH;\n  const mergedPath = mergePathValues(shellPath, inheritedPath, \"win32\");\n  const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);\n  const baselinePath = mergePathValues(knownCliPath, mergedPath, \"win32\");\n  const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};\n  const baselineEnv = mergeWindowsEnv(env, baselinePatch);\n\n  if (yield* commandAvailable(\"node\", { env: baselineEnv })) {\n    return baselinePatch;\n  }\n\n  const profiledEnvironment = readWindowsEnvironmentSafely(\n    readEnvironment,\n    [\"PATH\", \"FNM_DIR\", \"FNM_MULTISHELL_PATH\"],\n    { loadProfile: true },\n  );\n  const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, \"win32\");\n  const profiledPatch: Partial<NodeJS.ProcessEnv> = {\n    ...(profiledPath ? { PATH: profiledPath } : {}),\n    ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),\n    ...(profiledEnvironment.FNM_MULTISHELL_PATH\n      ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }\n      : {}),\n  };\n  return Object.keys(profiledPatch).length > 0\n    ? { ...baselinePatch, ...profiledPatch }\n    : baselinePatch;\n});\n","import { HostProcessEnvironment, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport {\n  listLoginShellCandidates,\n  mergePathEntries,\n  readPathFromLoginShell,\n  readPathFromLaunchctl,\n  resolveWindowsEnvironment,\n} from \"@t3tools/shared/shell\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as NodeOS from \"node:os\";\n\nfunction logPathHydrationWarning(message: string, error?: unknown): void {\n  process.stderr.write(\n    `[server] ${message} ${error instanceof Error ? error.message : (error ?? \"\")}\\n`,\n  );\n}\n\nfunction hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {\n  let shellPath: string | undefined;\n  for (const shell of listLoginShellCandidates(platform, env.SHELL)) {\n    try {\n      shellPath = readPathFromLoginShell(shell);\n    } catch (error) {\n      logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);\n    }\n\n    if (shellPath) break;\n  }\n\n  const launchctlPath = platform === \"darwin\" && !shellPath ? readPathFromLaunchctl() : undefined;\n  const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);\n  if (mergedPath) {\n    env.PATH = mergedPath;\n  }\n}\n\nexport function hydratePosixHome(\n  env: NodeJS.ProcessEnv,\n  resolveHomeDir = () => NodeOS.userInfo().homedir,\n): void {\n  if ((env.HOME?.trim() ?? \"\").length > 0) return;\n\n  const homeDir = resolveHomeDir();\n  if (homeDir.length > 0) {\n    env.HOME = homeDir;\n  }\n}\n\nexport const fixPath = Effect.fn(\"fixPath\")(function* (): Effect.fn.Return<\n  void,\n  never,\n  FileSystem.FileSystem | Path.Path\n> {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* HostProcessEnvironment;\n\n  if (platform === \"win32\") {\n    const repairedEnvironment = yield* resolveWindowsEnvironment(env).pipe(\n      Effect.catchDefect((defect) =>\n        Effect.sync(() => {\n          logPathHydrationWarning(\"Failed to hydrate PATH from the user environment.\", defect);\n          return {} as Partial<NodeJS.ProcessEnv>;\n        }),\n      ),\n    );\n    for (const [key, value] of Object.entries(repairedEnvironment)) {\n      if (value !== undefined) {\n        env[key] = value;\n      }\n    }\n    return;\n  }\n\n  if (platform !== \"darwin\" && platform !== \"linux\") return;\n\n  yield* Effect.sync(() => hydratePosixHome(env)).pipe(\n    Effect.catchDefect((defect) =>\n      Effect.sync(() => {\n        logPathHydrationWarning(\"Failed to hydrate HOME from the user account.\", defect);\n      }),\n    ),\n  );\n  yield* Effect.sync(() => hydratePosixPath(env, platform)).pipe(\n    Effect.catchDefect((defect) =>\n      Effect.sync(() => {\n        logPathHydrationWarning(\"Failed to hydrate PATH from the user environment.\", defect);\n      }),\n    ),\n  );\n});\n\nexport const expandHomePath = Effect.fn(function* (input: string) {\n  const { join } = yield* Path.Path;\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n});\n\nexport const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {\n  const { join, resolve } = yield* Path.Path;\n  if (!raw || raw.trim().length === 0) {\n    return join(NodeOS.homedir(), \".t3\");\n  }\n  return resolve(yield* expandHomePath(raw.trim()));\n});\n","import * as NetService from \"@t3tools/shared/Net\";\nimport { parsePersistedServerObservabilitySettings } from \"@t3tools/shared/serverSettings\";\nimport { DesktopBackendBootstrap, PortSchema } from \"@t3tools/contracts\";\nimport * as Config from \"effect/Config\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as LogLevel from \"effect/LogLevel\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport { Argument, Flag } from \"effect/unstable/cli\";\n\nimport { readBootstrapEnvelope } from \"../bootstrap.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { expandHomePath, resolveBaseDir } from \"../os-jank.ts\";\n\nexport const modeFlag = Flag.choice(\"mode\", ServerConfig.RuntimeMode.literals).pipe(\n  Flag.withDescription(\"Runtime mode. `desktop` keeps loopback defaults unless overridden.\"),\n  Flag.optional,\n);\nexport const portFlag = Flag.integer(\"port\").pipe(\n  Flag.withSchema(PortSchema),\n  Flag.withDescription(\"Port for the HTTP/WebSocket server.\"),\n  Flag.optional,\n);\nexport const hostFlag = Flag.string(\"host\").pipe(\n  Flag.withDescription(\"Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP).\"),\n  Flag.optional,\n);\nexport const baseDirFlag = Flag.string(\"base-dir\").pipe(\n  Flag.withDescription(\n    \"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).\",\n  ),\n  Flag.optional,\n);\nexport const devUrlFlag = Flag.string(\"dev-url\").pipe(\n  Flag.withSchema(Schema.URLFromString),\n  Flag.withDescription(\"Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL).\"),\n  Flag.optional,\n);\nexport const noBrowserFlag = Flag.boolean(\"no-browser\").pipe(\n  Flag.withDescription(\"Disable automatic browser opening.\"),\n  Flag.optional,\n);\nexport const bootstrapFdFlag = Flag.integer(\"bootstrap-fd\").pipe(\n  Flag.withSchema(Schema.Int),\n  Flag.withDescription(\"Read one-time bootstrap secrets from the given file descriptor.\"),\n  Flag.optional,\n);\nexport const autoBootstrapProjectFromCwdFlag = Flag.boolean(\"auto-bootstrap-project-from-cwd\").pipe(\n  Flag.withDescription(\n    \"Create a project for the current working directory on startup when missing.\",\n  ),\n  Flag.optional,\n);\nexport const logWebSocketEventsFlag = Flag.boolean(\"log-websocket-events\").pipe(\n  Flag.withDescription(\n    \"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).\",\n  ),\n  Flag.withAlias(\"log-ws-events\"),\n  Flag.optional,\n);\nexport const tailscaleServeFlag = Flag.boolean(\"tailscale-serve\").pipe(\n  Flag.withDescription(\n    \"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.\",\n  ),\n  Flag.optional,\n);\nexport const tailscaleServePortFlag = Flag.integer(\"tailscale-serve-port\").pipe(\n  Flag.withSchema(PortSchema),\n  Flag.withDescription(\"HTTPS port for Tailscale Serve when --tailscale-serve is enabled.\"),\n  Flag.optional,\n);\n\n// agentlink fork (步骤 6): hub tunnel egress. All three together enable the\n// outbound /daemon-tunnel bridge; any subset is a startup error (resolved in\n// resolveServerConfig).\nexport const hubFlag = Flag.string(\"hub\").pipe(\n  Flag.withDescription(\n    \"AgentLink hub URL (ws:// or wss://) to tunnel through (equivalent to T3CODE_HUB_URL).\",\n  ),\n  Flag.optional,\n);\nexport const machineTokenFlag = Flag.string(\"machine-token\").pipe(\n  Flag.withDescription(\n    \"Machine credential for the hub tunnel: al1 auth half, or a single-mode token (equivalent to T3CODE_HUB_MACHINE_TOKEN).\",\n  ),\n  Flag.optional,\n);\nexport const enckeyFlag = Flag.string(\"enckey\").pipe(\n  Flag.withDescription(\n    \"E2EE master key (base64url, 32 bytes) for hub tunnel frames — never sent to the hub (equivalent to T3CODE_HUB_ENCKEY).\",\n  ),\n  Flag.optional,\n);\n\nconst EnvServerConfig = Config.all({\n  logLevel: Config.logLevel(\"T3CODE_LOG_LEVEL\").pipe(Config.withDefault(\"Info\")),\n  traceMinLevel: Config.logLevel(\"T3CODE_TRACE_MIN_LEVEL\").pipe(Config.withDefault(\"Info\")),\n  traceTimingEnabled: Config.boolean(\"T3CODE_TRACE_TIMING_ENABLED\").pipe(Config.withDefault(true)),\n  traceFile: Config.string(\"T3CODE_TRACE_FILE\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  traceMaxBytes: Config.int(\"T3CODE_TRACE_MAX_BYTES\").pipe(Config.withDefault(10 * 1024 * 1024)),\n  traceMaxFiles: Config.int(\"T3CODE_TRACE_MAX_FILES\").pipe(Config.withDefault(10)),\n  traceBatchWindowMs: Config.int(\"T3CODE_TRACE_BATCH_WINDOW_MS\").pipe(Config.withDefault(1_000)),\n  otlpTracesUrl: Config.string(\"T3CODE_OTLP_TRACES_URL\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  otlpMetricsUrl: Config.string(\"T3CODE_OTLP_METRICS_URL\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  otlpExportIntervalMs: Config.int(\"T3CODE_OTLP_EXPORT_INTERVAL_MS\").pipe(\n    Config.withDefault(10_000),\n  ),\n  otlpServiceName: Config.string(\"T3CODE_OTLP_SERVICE_NAME\").pipe(Config.withDefault(\"t3-server\")),\n  mode: Config.schema(ServerConfig.RuntimeMode, \"T3CODE_MODE\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  port: Config.port(\"T3CODE_PORT\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  host: Config.string(\"T3CODE_HOST\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  t3Home: Config.string(\"T3CODE_HOME\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  devUrl: Config.url(\"VITE_DEV_SERVER_URL\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  devAllowedOrigins: Config.string(\"T3CODE_DEV_ALLOWED_ORIGINS\").pipe(\n    Config.withDefault(\"\"),\n    Config.map((value) =>\n      value\n        .split(\",\")\n        .map((entry) => entry.trim())\n        .filter((entry) => entry.length > 0),\n    ),\n  ),\n  noBrowser: Config.boolean(\"T3CODE_NO_BROWSER\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  bootstrapFd: Config.int(\"T3CODE_BOOTSTRAP_FD\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  autoBootstrapProjectFromCwd: Config.boolean(\"T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  logWebSocketEvents: Config.boolean(\"T3CODE_LOG_WS_EVENTS\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  tailscaleServeEnabled: Config.boolean(\"T3CODE_TAILSCALE_SERVE\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  tailscaleServePort: Config.port(\"T3CODE_TAILSCALE_SERVE_PORT\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  hubUrl: Config.string(\"T3CODE_HUB_URL\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  hubMachineToken: Config.string(\"T3CODE_HUB_MACHINE_TOKEN\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  hubEnckey: Config.string(\"T3CODE_HUB_ENCKEY\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n});\n\nexport interface CliServerFlags {\n  readonly mode: Option.Option<ServerConfig.RuntimeMode>;\n  readonly port: Option.Option<number>;\n  readonly host: Option.Option<string>;\n  readonly baseDir: Option.Option<string>;\n  readonly cwd: Option.Option<string>;\n  readonly devUrl: Option.Option<URL>;\n  readonly noBrowser: Option.Option<boolean>;\n  readonly bootstrapFd: Option.Option<number>;\n  readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;\n  readonly logWebSocketEvents: Option.Option<boolean>;\n  readonly tailscaleServeEnabled: Option.Option<boolean>;\n  readonly tailscaleServePort: Option.Option<number>;\n  readonly hub: Option.Option<string>;\n  readonly machineToken: Option.Option<string>;\n  readonly enckey: Option.Option<string>;\n}\n\nexport interface CliAuthLocationFlags {\n  readonly baseDir: Option.Option<string>;\n  readonly devUrl?: Option.Option<URL>;\n}\n\nexport const sharedServerLocationFlags = {\n  baseDir: baseDirFlag,\n  devUrl: devUrlFlag,\n} as const;\n\nexport const projectLocationFlags = {\n  baseDir: baseDirFlag,\n} as const;\n\nexport const sharedServerCommandFlags = {\n  mode: modeFlag,\n  port: portFlag,\n  host: hostFlag,\n  baseDir: baseDirFlag,\n  cwd: Argument.string(\"cwd\").pipe(\n    Argument.withDescription(\n      \"Working directory for provider sessions (defaults to the current directory).\",\n    ),\n    Argument.optional,\n  ),\n  devUrl: devUrlFlag,\n  noBrowser: noBrowserFlag,\n  bootstrapFd: bootstrapFdFlag,\n  autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,\n  logWebSocketEvents: logWebSocketEventsFlag,\n  tailscaleServeEnabled: tailscaleServeFlag,\n  tailscaleServePort: tailscaleServePortFlag,\n  hub: hubFlag,\n  machineToken: machineTokenFlag,\n  enckey: enckeyFlag,\n} as const;\n\nexport const authLocationFlags = sharedServerLocationFlags;\n\nconst resolveOptionPrecedence = <Value>(\n  ...values: ReadonlyArray<Option.Option<Value>>\n): Option.Option<Value> => Option.firstSomeOf(values);\n\nconst loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {\n  const fs = yield* FileSystem.FileSystem;\n  const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));\n  if (!exists) {\n    return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };\n  }\n\n  const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => \"\"));\n  return parsePersistedServerObservabilitySettings(raw);\n});\n\nexport const resolveServerConfig = (\n  flags: CliServerFlags,\n  cliLogLevel: Option.Option<LogLevel.LogLevel>,\n  options?: {\n    readonly startupPresentation?: ServerConfig.StartupPresentation;\n    readonly forceAutoBootstrapProjectFromCwd?: boolean;\n  },\n) =>\n  Effect.gen(function* () {\n    const { findAvailablePort } = yield* NetService.NetService;\n    const path = yield* Path.Path;\n    const fs = yield* FileSystem.FileSystem;\n    const env = yield* EnvServerConfig;\n    const normalizedFlags = {\n      mode: flags.mode ?? Option.none(),\n      port: flags.port ?? Option.none(),\n      host: flags.host ?? Option.none(),\n      baseDir: flags.baseDir ?? Option.none(),\n      cwd: flags.cwd ?? Option.none(),\n      devUrl: flags.devUrl ?? Option.none(),\n      noBrowser: flags.noBrowser ?? Option.none(),\n      bootstrapFd: flags.bootstrapFd ?? Option.none(),\n      autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),\n      logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),\n      tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),\n      tailscaleServePort: flags.tailscaleServePort ?? Option.none(),\n      hub: flags.hub ?? Option.none(),\n      machineToken: flags.machineToken ?? Option.none(),\n      enckey: flags.enckey ?? Option.none(),\n    } satisfies CliServerFlags;\n    const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;\n    const bootstrapEnvelope =\n      bootstrapFd !== undefined\n        ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)\n        : Option.none();\n    const bootstrap = Option.getOrUndefined(bootstrapEnvelope);\n\n    const mode: ServerConfig.RuntimeMode = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.mode,\n        Option.fromUndefinedOr(env.mode),\n        Option.fromUndefinedOr(bootstrap?.mode),\n      ),\n      () => \"web\",\n    );\n\n    const port = yield* Option.match(\n      resolveOptionPrecedence(\n        normalizedFlags.port,\n        Option.fromUndefinedOr(env.port),\n        Option.fromUndefinedOr(bootstrap?.port),\n      ),\n      {\n        onSome: (value) => Effect.succeed(value),\n        onNone: () => {\n          if (mode === \"desktop\") {\n            return Effect.succeed(ServerConfig.DEFAULT_PORT);\n          }\n          return findAvailablePort(ServerConfig.DEFAULT_PORT);\n        },\n      },\n    );\n    const devUrl = Option.getOrElse(\n      resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),\n      () => undefined,\n    );\n    const explicitBaseDir = resolveOptionPrecedence(\n      normalizedFlags.baseDir,\n      Option.fromUndefinedOr(env.t3Home),\n    ).pipe(Option.filter((value) => value.trim().length > 0));\n    const baseDir = yield* resolveBaseDir(\n      Option.getOrUndefined(\n        resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),\n      ),\n    );\n    const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());\n    const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));\n    yield* fs.makeDirectory(cwd, { recursive: true });\n    const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {\n      baseDirIsExplicit: Option.isSome(explicitBaseDir),\n    });\n    yield* ServerConfig.ensureServerDirectories(derivedPaths);\n    const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(\n      derivedPaths.settingsPath,\n    );\n    const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;\n    yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });\n    const startupPresentation = options?.startupPresentation ?? \"browser\";\n    const isHeadlessStartup = startupPresentation === \"headless\";\n    const noBrowser = Option.getOrElse(\n      resolveOptionPrecedence(\n        isHeadlessStartup ? Option.some(true) : Option.none(),\n        normalizedFlags.noBrowser,\n        Option.fromUndefinedOr(env.noBrowser),\n        Option.fromUndefinedOr(bootstrap?.noBrowser),\n      ),\n      () => mode === \"desktop\",\n    );\n    const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;\n    const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;\n    const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;\n    const resourceMonitorPath = bootstrap?.resourceMonitorPath;\n    const autoBootstrapProjectFromCwd = Option.getOrElse(\n      resolveOptionPrecedence(\n        Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),\n        isHeadlessStartup ? Option.some(false) : Option.none(),\n        normalizedFlags.autoBootstrapProjectFromCwd,\n        Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),\n      ),\n      () => mode === \"web\",\n    );\n    const logWebSocketEvents = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.logWebSocketEvents,\n        Option.fromUndefinedOr(env.logWebSocketEvents),\n      ),\n      () => Boolean(devUrl),\n    );\n    const tailscaleServeEnabled = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.tailscaleServeEnabled,\n        Option.fromUndefinedOr(env.tailscaleServeEnabled),\n        Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),\n      ),\n      () => false,\n    );\n    const tailscaleServePort = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.tailscaleServePort,\n        Option.fromUndefinedOr(env.tailscaleServePort),\n        Option.fromUndefinedOr(bootstrap?.tailscaleServePort),\n      ),\n      () => 443,\n    );\n    // agentlink fork (步骤 6): hub tunnel egress. All-or-nothing — a partial\n    // configuration is a startup error, not a silent no-op.\n    const hubUrl = Option.getOrUndefined(\n      resolveOptionPrecedence(normalizedFlags.hub, Option.fromUndefinedOr(env.hubUrl)),\n    );\n    const hubMachineToken = Option.getOrUndefined(\n      resolveOptionPrecedence(\n        normalizedFlags.machineToken,\n        Option.fromUndefinedOr(env.hubMachineToken),\n      ),\n    );\n    const hubEnckey = Option.getOrUndefined(\n      resolveOptionPrecedence(normalizedFlags.enckey, Option.fromUndefinedOr(env.hubEnckey)),\n    );\n    if (hubEnckey !== undefined && !/^[A-Za-z0-9_-]{43}$/.test(hubEnckey)) {\n      return yield* Effect.fail(\n        new Error(\"--enckey/T3CODE_HUB_ENCKEY must be unpadded base64url for exactly 32 bytes\"),\n      );\n    }\n    const hubTunnelProvided = [hubUrl, hubMachineToken, hubEnckey].filter(\n      (v) => v !== undefined,\n    ).length;\n    if (hubTunnelProvided > 0 && hubTunnelProvided < 3) {\n      return yield* Effect.fail(\n        new Error(\n          \"hub tunnel needs ALL THREE of --hub/--machine-token/--enckey (or T3CODE_HUB_URL/T3CODE_HUB_MACHINE_TOKEN/T3CODE_HUB_ENCKEY) — a partial set would silently run local-only.\",\n        ),\n      );\n    }\n    const hubTunnel: ServerConfig.HubTunnelConfig | undefined =\n      hubUrl !== undefined && hubMachineToken !== undefined && hubEnckey !== undefined\n        ? { hubUrl, machineToken: hubMachineToken, enckey: hubEnckey }\n        : undefined;\n    const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();\n    const host = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.host,\n        Option.fromUndefinedOr(env.host),\n        Option.fromUndefinedOr(bootstrap?.host),\n      ),\n      () => (mode === \"desktop\" ? \"127.0.0.1\" : undefined),\n    );\n    const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);\n\n    const config: ServerConfig.ServerConfig[\"Service\"] = {\n      logLevel,\n      traceMinLevel: env.traceMinLevel,\n      traceTimingEnabled: env.traceTimingEnabled,\n      traceBatchWindowMs: env.traceBatchWindowMs,\n      traceMaxBytes: env.traceMaxBytes,\n      traceMaxFiles: env.traceMaxFiles,\n      otlpTracesUrl:\n        env.otlpTracesUrl ??\n        bootstrap?.otlpTracesUrl ??\n        persistedObservabilitySettings.otlpTracesUrl,\n      otlpMetricsUrl:\n        env.otlpMetricsUrl ??\n        bootstrap?.otlpMetricsUrl ??\n        persistedObservabilitySettings.otlpMetricsUrl,\n      otlpExportIntervalMs: env.otlpExportIntervalMs,\n      otlpServiceName: env.otlpServiceName,\n      mode,\n      port,\n      cwd,\n      baseDir,\n      ...derivedPaths,\n      serverTracePath,\n      host,\n      staticDir,\n      devUrl,\n      devAllowedOrigins: env.devAllowedOrigins,\n      noBrowser,\n      startupPresentation,\n      desktopBootstrapToken,\n      desktopTelemetryFd,\n      desktopTelemetryControlFd,\n      resourceMonitorPath,\n      autoBootstrapProjectFromCwd,\n      logWebSocketEvents,\n      tailscaleServeEnabled,\n      tailscaleServePort,\n      ...(hubTunnel !== undefined ? { hubTunnel } : {}),\n    };\n\n    return config;\n  });\n\nexport const resolveCliAuthConfig = (\n  flags: CliAuthLocationFlags,\n  cliLogLevel: Option.Option<LogLevel.LogLevel>,\n) =>\n  resolveServerConfig(\n    {\n      mode: Option.none(),\n      port: Option.none(),\n      host: Option.none(),\n      baseDir: flags.baseDir,\n      cwd: Option.none(),\n      devUrl: flags.devUrl ?? Option.none(),\n      noBrowser: Option.none(),\n      bootstrapFd: Option.none(),\n      autoBootstrapProjectFromCwd: Option.none(),\n      logWebSocketEvents: Option.none(),\n      tailscaleServeEnabled: Option.none(),\n      tailscaleServePort: Option.none(),\n      hub: Option.none(),\n      machineToken: Option.none(),\n      enckey: Option.none(),\n    },\n    cliLogLevel,\n  );\n\nconst DurationShorthandPattern = /^(?<value>\\d+)(?<unit>ms|s|m|h|d|w)$/i;\n\nconst parseDurationInput = (value: string): Duration.Duration | null => {\n  const trimmed = value.trim();\n  if (trimmed.length === 0) return null;\n\n  const shorthand = DurationShorthandPattern.exec(trimmed);\n  const normalizedInput = shorthand?.groups\n    ? (() => {\n        const amountText = shorthand.groups.value;\n        const unitText = shorthand.groups.unit;\n        if (typeof amountText !== \"string\" || typeof unitText !== \"string\") {\n          return null;\n        }\n\n        const amount = Number.parseInt(amountText, 10);\n        if (!Number.isFinite(amount)) return null;\n\n        switch (unitText.toLowerCase()) {\n          case \"ms\":\n            return `${amount} millis`;\n          case \"s\":\n            return `${amount} seconds`;\n          case \"m\":\n            return `${amount} minutes`;\n          case \"h\":\n            return `${amount} hours`;\n          case \"d\":\n            return `${amount} days`;\n          case \"w\":\n            return `${amount} weeks`;\n          default:\n            return null;\n        }\n      })()\n    : (trimmed as Duration.Input);\n\n  if (normalizedInput === null) return null;\n\n  const decoded = Duration.fromInput(normalizedInput as Duration.Input);\n  return Option.isSome(decoded) ? decoded.value : null;\n};\n\nexport const DurationFromString = Schema.String.pipe(\n  Schema.decodeTo(\n    Schema.Duration,\n    SchemaTransformation.transformOrFail({\n      decode: (value) => {\n        const duration = parseDurationInput(value);\n        if (duration !== null) {\n          return Effect.succeed(duration);\n        }\n        return Effect.fail(\n          new SchemaIssue.InvalidValue({\n            message: \"Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.\",\n          }),\n        );\n      },\n      encode: (duration) => Effect.succeed(Duration.format(duration)),\n    }),\n  ),\n);\n","import {\n  AuthAdministrativeScopes,\n  AuthSessionId,\n  AuthStandardClientScopes,\n} from \"@t3tools/contracts\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport { Argument, Command, Flag, GlobalFlag } from \"effect/unstable/cli\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\n\nimport {\n  formatIssuedPairingCredential,\n  formatIssuedSession,\n  formatPairingCredentialList,\n  formatSessionList,\n} from \"../cliAuthFormat.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport {\n  authLocationFlags,\n  type CliAuthLocationFlags,\n  DurationFromString,\n  resolveCliAuthConfig,\n} from \"./config.ts\";\n\nconst runWithEnvironmentAuth = <A, E>(\n  flags: CliAuthLocationFlags,\n  run: (environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"]) => Effect.Effect<A, E>,\n  options?: {\n    readonly quietLogs?: boolean;\n  },\n) =>\n  Effect.gen(function* () {\n    const logLevel = yield* GlobalFlag.LogLevel;\n    const config = yield* resolveCliAuthConfig(flags, logLevel);\n    const minimumLogLevel = options?.quietLogs ? \"Error\" : config.logLevel;\n    return yield* Effect.gen(function* () {\n      const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;\n      return yield* run(environmentAuth);\n    }).pipe(\n      Effect.provide(\n        Layer.mergeAll(EnvironmentAuth.runtimeLayer).pipe(\n          Layer.provide(ServerConfig.layer(config)),\n          Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),\n        ),\n      ),\n    );\n  });\n\nconst ttlFlag = Flag.string(\"ttl\").pipe(\n  Flag.withSchema(DurationFromString),\n  Flag.withDescription(\"TTL, for example `5m`, `1h`, `30d`, or `15 minutes`.\"),\n  Flag.optional,\n);\n\nconst jsonFlag = Flag.boolean(\"json\").pipe(\n  Flag.withDescription(\"Emit JSON instead of human-readable output.\"),\n  Flag.withDefault(false),\n);\n\nconst labelFlag = Flag.string(\"label\").pipe(\n  Flag.withDescription(\"Optional human-readable label.\"),\n  Flag.optional,\n);\n\nconst subjectFlag = Flag.string(\"subject\").pipe(\n  Flag.withDescription(\"Optional session subject.\"),\n  Flag.optional,\n);\n\nconst baseUrlFlag = Flag.string(\"base-url\").pipe(\n  Flag.withDescription(\"Optional public base URL used to print a ready `/pair#token=...` link.\"),\n  Flag.optional,\n);\n\nconst tokenOnlyFlag = Flag.boolean(\"token-only\").pipe(\n  Flag.withDescription(\"Print only the issued bearer token.\"),\n  Flag.withDefault(false),\n);\n\nconst pairingCreateCommand = Command.make(\"create\", {\n  ...authLocationFlags,\n  ttl: ttlFlag,\n  label: labelFlag,\n  baseUrl: baseUrlFlag,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"Issue a new client pairing token.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const issued = yield* environmentAuth.createPairingLink({\n            scopes: AuthStandardClientScopes,\n            subject: \"one-time-token\",\n            ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),\n            ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),\n          });\n          const output = formatIssuedPairingCredential(issued, {\n            json: flags.json,\n            ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),\n          });\n          yield* Console.log(output);\n        }),\n      {\n        quietLogs: flags.json,\n      },\n    ),\n  ),\n);\n\nconst pairingListCommand = Command.make(\"list\", {\n  ...authLocationFlags,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"List active client pairing tokens without revealing their secrets.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const pairingLinks = yield* environmentAuth.listPairingLinks({\n            excludeSubjects: [EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT],\n          });\n          yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));\n        }),\n      {\n        quietLogs: flags.json,\n      },\n    ),\n  ),\n);\n\nconst pairingRevokeCommand = Command.make(\"revoke\", {\n  ...authLocationFlags,\n  id: Argument.string(\"id\").pipe(Argument.withDescription(\"Pairing credential id to revoke.\")),\n}).pipe(\n  Command.withDescription(\"Revoke an active client pairing token.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(flags, (environmentAuth) =>\n      Effect.gen(function* () {\n        const revoked = yield* environmentAuth.revokePairingLink(flags.id);\n        yield* Console.log(\n          revoked\n            ? `Revoked pairing credential ${flags.id}.\\n`\n            : `No active pairing credential found for ${flags.id}.\\n`,\n        );\n      }),\n    ),\n  ),\n);\n\nconst pairingCommand = Command.make(\"pairing\").pipe(\n  Command.withDescription(\"Manage one-time client pairing tokens.\"),\n  Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),\n);\n\nconst sessionIssueCommand = Command.make(\"issue\", {\n  ...authLocationFlags,\n  ttl: ttlFlag,\n  label: labelFlag,\n  subject: subjectFlag,\n  tokenOnly: tokenOnlyFlag,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"Issue a scoped bearer access token for headless or remote clients.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const issued = yield* environmentAuth.issueSession({\n            scopes: AuthAdministrativeScopes,\n            ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),\n            ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),\n            ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),\n          });\n          yield* Console.log(\n            formatIssuedSession(issued, {\n              json: flags.json,\n              tokenOnly: flags.tokenOnly,\n            }),\n          );\n        }),\n      {\n        quietLogs: flags.json || flags.tokenOnly,\n      },\n    ),\n  ),\n);\n\nconst sessionListCommand = Command.make(\"list\", {\n  ...authLocationFlags,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"List active sessions without revealing bearer tokens.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const sessions = yield* environmentAuth.listSessions();\n          yield* Console.log(formatSessionList(sessions, { json: flags.json }));\n        }),\n      {\n        quietLogs: flags.json,\n      },\n    ),\n  ),\n);\n\nconst sessionRevokeCommand = Command.make(\"revoke\", {\n  ...authLocationFlags,\n  sessionId: Argument.string(\"session-id\").pipe(\n    Argument.withDescription(\"Session id to revoke.\"),\n    Argument.withSchema(AuthSessionId),\n  ),\n}).pipe(\n  Command.withDescription(\"Revoke an active session.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(flags, (environmentAuth) =>\n      Effect.gen(function* () {\n        const revoked = yield* environmentAuth.revokeSession(flags.sessionId);\n        yield* Console.log(\n          revoked\n            ? `Revoked session ${flags.sessionId}.\\n`\n            : `No active session found for ${flags.sessionId}.\\n`,\n        );\n      }),\n    ),\n  ),\n);\n\nconst sessionCommand = Command.make(\"session\").pipe(\n  Command.withDescription(\"Manage bearer sessions.\"),\n  Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),\n);\n\nexport const authCommand = Command.make(\"auth\").pipe(\n  Command.withDescription(\"Manage the local auth control plane for headless deployments.\"),\n  Command.withSubcommands([pairingCommand, sessionCommand]),\n);\n","/**\n * Where development state lives, and how to keep it away from the shared\n * `~/.t3` that a user's installed T3 Code runs against.\n *\n * A linked git worktree gets its own (gitignored) `.t3`: feature work in a\n * throwaway branch must not share a database with the real app, and an ambient\n * `T3CODE_HOME` counts as an explicit base dir — flipping the state directory\n * from `<base>/dev` to `<base>/userdata`, the live production database.\n */\n\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\n\n/**\n * A `.git` file points at the real git directory. A linked worktree's lives at\n * `<common-dir>/worktrees/<name>`; a submodule's at\n * `<super-git-dir>/modules/<name>`. Both are files, so the pointer — not the\n * file-vs-directory distinction alone — is what identifies a worktree.\n *\n * The common dir is not necessarily named `.git`: a worktree of a bare repo\n * points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be\n * anything. So match on the `worktrees/<name>` tail, which git always uses,\n * rather than on the name of the directory containing it.\n */\nconst pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {\n  const gitdir = gitFileContents\n    .split(/\\r?\\n/)\n    .map((line) => line.trim())\n    .find((line) => line.startsWith(\"gitdir:\"))\n    ?.slice(\"gitdir:\".length)\n    .trim();\n  if (gitdir === undefined || gitdir.length === 0) {\n    return false;\n  }\n  // Compare as path segments so a directory merely named `…worktrees…` cannot\n  // match as a substring. Trailing separators normalize away first.\n  const segments = path\n    .normalize(gitdir.replaceAll(\"\\\\\", \"/\"))\n    .split(/[/\\\\]/)\n    .filter((segment) => segment.length > 0);\n  // `<common-dir>/worktrees/<name>`: `worktrees` is the penultimate segment,\n  // and something must precede it. This excludes `<git-dir>/modules/<name>`.\n  return segments.length >= 3 && segments.at(-2) === \"worktrees\";\n};\n\n/**\n * The path of the linked git worktree containing `cwd`, or undefined when\n * `cwd` is not inside one. Git marks a linked worktree by making `.git` a file\n * whose `gitdir:` points into the repository's `.git/worktrees`.\n *\n * Walks up to the repository root, so running from a subdirectory resolves the\n * same worktree as running from the top.\n */\nexport const resolveGitWorktreePath = (\n  cwd: string,\n): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>\n  Effect.gen(function* () {\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n\n    let directory = path.resolve(cwd);\n    for (;;) {\n      const gitPath = path.join(directory, \".git\");\n      const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);\n      if (Option.isSome(info)) {\n        // A directory means the main checkout. Stop either way: nesting one\n        // repository inside another does not make the outer one this root.\n        if (info.value.type !== \"File\") {\n          return undefined;\n        }\n        // A submodule also has a `.git` file, but it is not a worktree of this\n        // repository and gets no worktree-local home.\n        const contents = yield* fileSystem\n          .readFileString(gitPath)\n          .pipe(Effect.orElseSucceed(() => \"\"));\n        return pointsAtLinkedWorktree(contents, path) ? directory : undefined;\n      }\n      const parent = path.dirname(directory);\n      if (parent === directory) {\n        return undefined;\n      }\n      directory = parent;\n    }\n  });\n\n/**\n * The worktree-local data directory for `cwd`, or undefined outside a linked\n * worktree. Deliberately does not require the directory to exist yet: falling\n * back because it is missing would send callers at the shared home.\n */\nexport const resolveWorktreeT3Home = (\n  cwd: string,\n): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>\n  Effect.gen(function* () {\n    const worktreePath = yield* resolveGitWorktreePath(cwd);\n    if (worktreePath === undefined) {\n      return undefined;\n    }\n    const path = yield* Path.Path;\n    return path.join(worktreePath, \".t3\");\n  });\n","import { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nexport const DEFAULT_TAILSCALE_SERVE_PORT = 443;\nexport const TAILSCALE_STATUS_TIMEOUT = Duration.millis(1_500);\nexport const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);\nexport const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);\n\n// tailscale is a real executable everywhere (`tailscale.exe` on Windows), so\n// it is always spawned directly rather than through cmd.exe shell mode.\nconst tailscaleCommandForPlatform = (platform: NodeJS.Platform): \"tailscale\" | \"tailscale.exe\" =>\n  platform === \"win32\" ? \"tailscale.exe\" : \"tailscale\";\n\nconst TailscaleCommandContext = {\n  executable: Schema.Literals([\"tailscale\", \"tailscale.exe\"]),\n  subcommand: Schema.Literals([\"status\", \"serve\"]),\n  argumentCount: Schema.Number,\n};\n\n/**\n * Failure kinds we can name without quoting the CLI. Anything unrecognized\n * becomes \"unknown\" rather than falling back to raw text — stderr can contain\n * auth keys (`tskey-…`) and node names, and these labels are logged.\n */\nexport const TailscaleStderrDiagnostic = Schema.Literals([\n  \"no-existing-handler\",\n  \"not-logged-in\",\n  \"permission-denied\",\n  \"unknown\",\n]);\nexport type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;\n\n// Matched against stderr, most specific first. Patterns are deliberately short\n// and anchored on tailscale's own wording.\nconst STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<\n  readonly [RegExp, Exclude<TailscaleStderrDiagnostic, \"unknown\">]\n> = [\n  [/handler does not exist/i, \"no-existing-handler\"],\n  [/not logged in|logged out|needs? login/i, \"not-logged-in\"],\n  [/permission denied|access denied|must be root|operation not permitted/i, \"permission-denied\"],\n];\n\n/** Classifies stderr into a safe label, dropping the text itself. */\nexport const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {\n  if (stderr.trim().length === 0) {\n    return undefined;\n  }\n  return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? \"unknown\";\n};\n\nexport class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(\n  \"TailscaleCommandSpawnError\",\n  {\n    ...TailscaleCommandContext,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to spawn tailscale ${this.subcommand}.`;\n  }\n}\n\nexport class TailscaleCommandOutputError extends Schema.TaggedErrorClass<TailscaleCommandOutputError>()(\n  \"TailscaleCommandOutputError\",\n  {\n    ...TailscaleCommandContext,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read output from tailscale ${this.subcommand}.`;\n  }\n}\n\nexport class TailscaleCommandExitError extends Schema.TaggedErrorClass<TailscaleCommandExitError>()(\n  \"TailscaleCommandExitError\",\n  {\n    ...TailscaleCommandContext,\n    exitCode: Schema.Number,\n    stdoutLength: Schema.optional(Schema.Number),\n    stderrLength: Schema.Number,\n    // A classified diagnostic, never raw CLI output. `tailscale` prints auth\n    // keys and node identifiers into stderr, and this field is surfaced in\n    // dev-runner logs — so it carries only a known-safe label from the closed\n    // set below. Callers that need to recognize a specific failure (e.g.\n    // `serve off` on a port with no mapping) match on the label.\n    stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),\n  },\n) {\n  override get message(): string {\n    return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;\n  }\n}\n\nexport class TailscaleCommandTimeoutError extends Schema.TaggedErrorClass<TailscaleCommandTimeoutError>()(\n  \"TailscaleCommandTimeoutError\",\n  {\n    ...TailscaleCommandContext,\n    timeoutMs: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;\n  }\n}\n\nexport const TailscaleCommandError = Schema.Union([\n  TailscaleCommandSpawnError,\n  TailscaleCommandOutputError,\n  TailscaleCommandExitError,\n  TailscaleCommandTimeoutError,\n]);\nexport type TailscaleCommandError = typeof TailscaleCommandError.Type;\n\nexport class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(\n  \"TailscaleStatusParseError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Failed to decode tailscale status JSON.\";\n  }\n}\n\nconst TailscaleStatusSelf = Schema.Struct({\n  DNSName: Schema.optional(Schema.Unknown),\n  TailscaleIPs: Schema.optional(Schema.Unknown),\n});\n\nconst TailscaleStatusJson = Schema.Struct({\n  Self: Schema.optional(TailscaleStatusSelf),\n});\n\nexport type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;\nexport type TailscaleStatusJson = typeof TailscaleStatusJson.Type;\n\nexport interface TailscaleStatus {\n  readonly magicDnsName: string | null;\n  readonly tailnetIpv4Addresses: readonly string[];\n}\n\nconst collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>\n  stream.pipe(\n    Stream.decodeText(),\n    Stream.runFold(\n      () => \"\",\n      (acc, chunk) => acc + chunk,\n    ),\n  );\n\nconst collectStderr = collectStdout;\n\nconst decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));\n\nfunction normalizeMagicDnsName(status: TailscaleStatusJson): string | null {\n  const dnsName = status.Self?.DNSName;\n  if (typeof dnsName !== \"string\") {\n    return null;\n  }\n\n  const normalized = dnsName.trim().replace(/\\.$/u, \"\");\n  return normalized.length > 0 ? normalized : null;\n}\n\nexport const parseTailscaleMagicDnsName = (\n  rawStatusJson: string,\n): Effect.Effect<string | null, TailscaleStatusParseError> =>\n  decodeTailscaleStatusJson(rawStatusJson).pipe(\n    Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),\n    Effect.map(normalizeMagicDnsName),\n  );\n\nexport function isTailscaleIpv4Address(address: string): boolean {\n  const parts = address.split(\".\");\n  if (parts.length !== 4) {\n    return false;\n  }\n  const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));\n  if (\n    first === undefined ||\n    second === undefined ||\n    third === undefined ||\n    fourth === undefined ||\n    [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n  ) {\n    return false;\n  }\n  return first === 100 && second >= 64 && second <= 127;\n}\n\nexport const parseTailscaleStatus = (\n  rawStatusJson: string,\n): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>\n  decodeTailscaleStatusJson(rawStatusJson).pipe(\n    Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),\n    Effect.map((parsed) => {\n      const rawIps = parsed.Self?.TailscaleIPs;\n      const tailnetIpv4Addresses: Array<string> = [];\n      if (Array.isArray(rawIps)) {\n        for (const address of rawIps) {\n          if (typeof address === \"string\" && isTailscaleIpv4Address(address)) {\n            tailnetIpv4Addresses.push(address);\n          }\n        }\n      }\n\n      return {\n        magicDnsName: normalizeMagicDnsName(parsed),\n        tailnetIpv4Addresses,\n      };\n    }),\n  );\n\nexport const readTailscaleStatus = Effect.gen(function* () {\n  const args = [\"status\", \"--json\"];\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const hostPlatform = yield* HostProcessPlatform;\n  const executable = tailscaleCommandForPlatform(hostPlatform);\n  const commandContext = {\n    executable,\n    subcommand: \"status\" as const,\n    argumentCount: args.length,\n  };\n  return yield* Effect.gen(function* () {\n    const child = yield* spawner\n      .spawn(ChildProcess.make(executable, args))\n      .pipe(\n        Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),\n      );\n    const [stdout, stderr, exitCode] = yield* Effect.all(\n      [\n        collectStdout(child.stdout),\n        collectStderr(child.stderr),\n        child.exitCode.pipe(Effect.map(Number)),\n      ],\n      { concurrency: \"unbounded\" },\n    ).pipe(\n      Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),\n    );\n    if (exitCode !== 0) {\n      return yield* new TailscaleCommandExitError({\n        ...commandContext,\n        exitCode,\n        stdoutLength: stdout.length,\n        stderrLength: stderr.length,\n        ...(stderrDiagnosticOf(stderr) !== undefined\n          ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }\n          : {}),\n      });\n    }\n    return yield* parseTailscaleStatus(stdout);\n  }).pipe(\n    Effect.scoped,\n    Effect.timeout(TAILSCALE_STATUS_TIMEOUT),\n    Effect.catchTags({\n      TimeoutError: (cause) =>\n        Effect.fail(\n          new TailscaleCommandTimeoutError({\n            ...commandContext,\n            timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),\n            cause,\n          }),\n        ),\n    }),\n  );\n});\n\nexport function buildTailscaleHttpsBaseUrl(input: {\n  readonly magicDnsName: string;\n  readonly servePort?: number;\n}): string {\n  const url = new URL(`https://${input.magicDnsName}`);\n  const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;\n  if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {\n    url.port = String(servePort);\n  }\n  url.pathname = \"/\";\n  return url.toString();\n}\n\nconst runTailscaleCommand = (\n  args: readonly string[],\n  timeoutInput: Duration.Input,\n): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const hostPlatform = yield* HostProcessPlatform;\n    const executable = tailscaleCommandForPlatform(hostPlatform);\n    const commandContext = {\n      executable,\n      subcommand: \"serve\" as const,\n      argumentCount: args.length,\n    };\n    const timeout = Duration.fromInputUnsafe(timeoutInput);\n    return yield* Effect.gen(function* () {\n      const child = yield* spawner\n        .spawn(ChildProcess.make(executable, args))\n        .pipe(\n          Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),\n        );\n      const [stderr, exitCode] = yield* Effect.all(\n        [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],\n        { concurrency: \"unbounded\" },\n      ).pipe(\n        Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),\n      );\n      if (exitCode !== 0) {\n        return yield* new TailscaleCommandExitError({\n          ...commandContext,\n          exitCode,\n          stderrLength: stderr.length,\n          ...(stderrDiagnosticOf(stderr) !== undefined\n            ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }\n            : {}),\n        });\n      }\n    }).pipe(\n      Effect.scoped,\n      Effect.timeout(timeout),\n      Effect.catchTags({\n        TimeoutError: (cause) =>\n          Effect.fail(\n            new TailscaleCommandTimeoutError({\n              ...commandContext,\n              timeoutMs: Duration.toMillis(timeout),\n              cause,\n            }),\n          ),\n      }),\n    );\n  });\n\nexport const ensureTailscaleServe = (input: {\n  readonly localPort: number;\n  readonly servePort?: number;\n  readonly localHost?: string;\n}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {\n  const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;\n  const localHost = input.localHost ?? \"127.0.0.1\";\n  const args = [\"serve\", \"--bg\", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];\n  return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);\n};\n\nexport const disableTailscaleServe = (\n  input: {\n    readonly servePort?: number;\n  } = {},\n): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>\n  Effect.gen(function* () {\n    const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;\n    return yield* runTailscaleCommand(\n      [\"serve\", `--https=${servePort}`, \"off\"],\n      TAILSCALE_SERVE_TIMEOUT,\n    );\n  });\n\nexport const probeTailscaleHttpsEndpoint = (input: {\n  readonly baseUrl: string;\n  readonly timeout?: Duration.Input;\n}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient;\n    const response = yield* Effect.gen(function* () {\n      const url = new URL(\"/.well-known/t3/environment\", input.baseUrl);\n      const request = HttpClientRequest.get(url.toString());\n      return yield* client.execute(request);\n    }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));\n\n    return Option.match(response, {\n      onNone: () => false,\n      onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,\n    });\n  }).pipe(Effect.orElseSucceed(() => false));\n\nexport const resolveTailscaleHttpsBaseUrl = (\n  input: {\n    readonly servePort?: number;\n  } = {},\n): Effect.Effect<\n  string | null,\n  TailscaleCommandError | TailscaleStatusParseError,\n  ChildProcessSpawner.ChildProcessSpawner\n> =>\n  readTailscaleStatus.pipe(\n    Effect.map((status) =>\n      status.magicDnsName\n        ? buildTailscaleHttpsBaseUrl({\n            magicDnsName: status.magicDnsName,\n            ...(input.servePort === undefined ? {} : { servePort: input.servePort }),\n          })\n        : null,\n    ),\n  );\n","import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\n\nexport const writeFileStringAtomically = (input: {\n  readonly filePath: string;\n  readonly contents: string;\n}) =>\n  Effect.scoped(\n    Effect.gen(function* () {\n      const fs = yield* FileSystem.FileSystem;\n      const path = yield* Path.Path;\n      const targetDirectory = path.dirname(input.filePath);\n\n      yield* fs.makeDirectory(targetDirectory, { recursive: true });\n      const tempDirectory = yield* fs.makeTempDirectoryScoped({\n        directory: targetDirectory,\n        prefix: `${path.basename(input.filePath)}.`,\n      });\n      const tempPath = path.join(tempDirectory, \"contents.tmp\");\n\n      yield* fs.writeFileString(tempPath, input.contents);\n      yield* fs.rename(tempPath, input.filePath);\n    }),\n  );\n","/* oxlint-disable eslint/no-useless-escape */\n/*\n * QR Code generator library (TypeScript)\n *\n * Copyright (c) Project Nayuki. (MIT License)\n * https://www.nayuki.io/page/qr-code-generator-library\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n * - The above copyright notice and this permission notice shall be included in\n *   all copies or substantial portions of the Software.\n * - The Software is provided \"as is\", without warranty of any kind, express or\n *   implied, including but not limited to the warranties of merchantability,\n *   fitness for a particular purpose and noninfringement. In no event shall the\n *   authors or copyright holders be liable for any claim, damages or other\n *   liability, whether in an action of contract, tort or otherwise, arising from,\n *   out of or in connection with the Software or the use or other dealings in the\n *   Software.\n */\n\n\"use strict\";\n\ntype bit = number;\ntype byte = number;\ntype int = number;\n\n/*---- QR Code symbol class ----*/\n\n/*\n * A QR Code symbol, which is a type of two-dimension barcode.\n * Invented by Denso Wave and described in the ISO/IEC 18004 standard.\n * Instances of this class represent an immutable square grid of dark and light cells.\n * The class provides static factory functions to create a QR Code from text or binary data.\n * The class covers the QR Code Model 2 specification, supporting all versions (sizes)\n * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.\n *\n * Ways to create a QR Code object:\n * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().\n * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().\n * - Low level: Custom-make the array of data codeword bytes (including\n *   segment headers and final padding, excluding error correction codewords),\n *   supply the appropriate version number, and call the QrCode() constructor.\n * (Note that all ways require supplying the desired error correction level.)\n */\nexport class QrCode {\n  public static Ecc: typeof QrCodeEcc;\n\n  /*-- Static factory functions (high level) --*/\n\n  // Returns a QR Code representing the given Unicode text string at the given error correction level.\n  // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer\n  // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible\n  // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the\n  // ecl argument if it can be done without increasing the version.\n  public static encodeText(text: string, ecl: QrCodeEcc): QrCode {\n    const segs: Array<QrSegment> = QrSegment.makeSegments(text);\n    return QrCode.encodeSegments(segs, ecl);\n  }\n\n  // Returns a QR Code representing the given binary data at the given error correction level.\n  // This function always encodes using the binary segment mode, not any text mode. The maximum number of\n  // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.\n  // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.\n  public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCodeEcc): QrCode {\n    const seg: QrSegment = QrSegment.makeBytes(data);\n    return QrCode.encodeSegments([seg], ecl);\n  }\n\n  /*-- Static factory functions (mid level) --*/\n\n  // Returns a QR Code representing the given segments with the given encoding parameters.\n  // The smallest possible QR Code version within the given range is automatically\n  // chosen for the output. Iff boostEcl is true, then the ECC level of the result\n  // may be higher than the ecl argument if it can be done without increasing the\n  // version. The mask number is either between 0 to 7 (inclusive) to force that\n  // mask, or -1 to automatically choose an appropriate mask (which may be slow).\n  // This function allows the user to create a custom sequence of segments that switches\n  // between modes (such as alphanumeric and byte) to encode text in less space.\n  // This is a mid-level API; the high-level API is encodeText() and encodeBinary().\n  public static encodeSegments(\n    segs: Readonly<Array<QrSegment>>,\n    ecl: QrCodeEcc,\n    minVersion: int = 1,\n    maxVersion: int = 40,\n    mask: int = -1,\n    boostEcl: boolean = true,\n  ): QrCode {\n    if (\n      !(\n        QrCode.MIN_VERSION <= minVersion &&\n        minVersion <= maxVersion &&\n        maxVersion <= QrCode.MAX_VERSION\n      ) ||\n      mask < -1 ||\n      mask > 7\n    )\n      throw new RangeError(\"Invalid value\");\n\n    // Find the minimal version number to use\n    let version: int;\n    let dataUsedBits: int;\n    for (version = minVersion; ; version++) {\n      const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available\n      const usedBits: number = QrSegment.getTotalBits(segs, version);\n      if (usedBits <= dataCapacityBits) {\n        dataUsedBits = usedBits;\n        break; // This version number is found to be suitable\n      }\n      if (version >= maxVersion)\n        // All versions in the range could not fit the given data\n        throw new RangeError(\"Data too long\");\n    }\n\n    // Increase the error correction level while the data still fits in the current version number\n    for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {\n      // From low to high\n      if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) ecl = newEcl;\n    }\n\n    // Concatenate all segments to create the data bit string\n    let bb: Array<bit> = [];\n    for (const seg of segs) {\n      appendBits(seg.mode.modeBits, 4, bb);\n      appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);\n      for (const b of seg.getData()) bb.push(b);\n    }\n    assert(bb.length == dataUsedBits);\n\n    // Add terminator and pad up to a byte if applicable\n    const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;\n    assert(bb.length <= dataCapacityBits);\n    appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);\n    appendBits(0, (8 - (bb.length % 8)) % 8, bb);\n    assert(bb.length % 8 == 0);\n\n    // Pad with alternating bytes until data capacity is reached\n    for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)\n      appendBits(padByte, 8, bb);\n\n    // Pack bits into bytes in big endian\n    let dataCodewords: Array<byte> = [];\n    while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);\n    bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3]! |= b << (7 - (i & 7))));\n\n    // Create the QR Code object\n    return new QrCode(version, ecl, dataCodewords, mask);\n  }\n\n  /*-- Fields --*/\n\n  // The width and height of this QR Code, measured in modules, between\n  // 21 and 177 (inclusive). This is equal to version * 4 + 17.\n  public readonly version: int;\n  public readonly errorCorrectionLevel: QrCodeEcc;\n  public readonly size: int;\n\n  // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).\n  // Even if a QR Code is created with automatic masking requested (mask = -1),\n  // the resulting object still has a mask value between 0 and 7.\n  public readonly mask: int;\n\n  // The modules of this QR Code (false = light, true = dark).\n  // Immutable after constructor finishes. Accessed through getModule().\n  private readonly modules: Array<Array<boolean>> = [];\n\n  // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.\n  private readonly isFunction: Array<Array<boolean>> = [];\n\n  /*-- Constructor (low level) and fields --*/\n\n  // Creates a new QR Code with the given version number,\n  // error correction level, data codeword bytes, and mask number.\n  // This is a low-level API that most users should not use directly.\n  // A mid-level API is the encodeSegments() function.\n  public constructor(\n    // The version number of this QR Code, which is between 1 and 40 (inclusive).\n    // This determines the size of this barcode.\n    version: int,\n\n    // The error correction level used in this QR Code.\n    errorCorrectionLevel: QrCodeEcc,\n\n    dataCodewords: Readonly<Array<byte>>,\n\n    msk: int,\n  ) {\n    this.version = version;\n    this.errorCorrectionLevel = errorCorrectionLevel;\n\n    // Check scalar arguments\n    if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)\n      throw new RangeError(\"Version value out of range\");\n    if (msk < -1 || msk > 7) throw new RangeError(\"Mask value out of range\");\n    this.size = version * 4 + 17;\n\n    // Initialize both grids to be size*size arrays of Boolean false\n    let row: Array<boolean> = [];\n    for (let i = 0; i < this.size; i++) row.push(false);\n    for (let i = 0; i < this.size; i++) {\n      this.modules.push(row.slice()); // Initially all light\n      this.isFunction.push(row.slice());\n    }\n\n    // Compute ECC, draw modules\n    this.drawFunctionPatterns();\n    const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);\n    this.drawCodewords(allCodewords);\n\n    // Do masking\n    if (msk == -1) {\n      // Automatically choose best mask\n      let minPenalty: int = 1000000000;\n      for (let i = 0; i < 8; i++) {\n        this.applyMask(i);\n        this.drawFormatBits(i);\n        const penalty: int = this.getPenaltyScore();\n        if (penalty < minPenalty) {\n          msk = i;\n          minPenalty = penalty;\n        }\n        this.applyMask(i); // Undoes the mask due to XOR\n      }\n    }\n    assert(0 <= msk && msk <= 7);\n    this.mask = msk;\n    this.applyMask(msk); // Apply the final choice of mask\n    this.drawFormatBits(msk); // Overwrite old format bits\n\n    this.isFunction = [];\n  }\n\n  /*-- Accessor methods --*/\n\n  // Returns the color of the module (pixel) at the given coordinates, which is false\n  // for light or true for dark. The top left corner has the coordinates (x=0, y=0).\n  // If the given coordinates are out of bounds, then false (light) is returned.\n  public getModule(x: int, y: int): boolean {\n    return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y]![x]!;\n  }\n\n  /*-- Private helper methods for constructor: Drawing function modules --*/\n\n  // Reads this object's version field, and draws and marks all function modules.\n  private drawFunctionPatterns(): void {\n    // Draw horizontal and vertical timing patterns\n    for (let i = 0; i < this.size; i++) {\n      this.setFunctionModule(6, i, i % 2 == 0);\n      this.setFunctionModule(i, 6, i % 2 == 0);\n    }\n\n    // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)\n    this.drawFinderPattern(3, 3);\n    this.drawFinderPattern(this.size - 4, 3);\n    this.drawFinderPattern(3, this.size - 4);\n\n    // Draw numerous alignment patterns\n    const alignPatPos: Array<int> = this.getAlignmentPatternPositions();\n    const numAlign: int = alignPatPos.length;\n    for (let i = 0; i < numAlign; i++) {\n      for (let j = 0; j < numAlign; j++) {\n        // Don't draw on the three finder corners\n        if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))\n          this.drawAlignmentPattern(alignPatPos[i]!, alignPatPos[j]!);\n      }\n    }\n\n    // Draw configuration data\n    this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor\n    this.drawVersion();\n  }\n\n  // Draws two copies of the format bits (with its own error correction code)\n  // based on the given mask and this object's error correction level field.\n  private drawFormatBits(mask: int): void {\n    // Calculate error correction code and pack bits\n    const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3\n    let rem: int = data;\n    for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);\n    const bits = ((data << 10) | rem) ^ 0x5412; // uint15\n    assert(bits >>> 15 == 0);\n\n    // Draw first copy\n    for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));\n    this.setFunctionModule(8, 7, getBit(bits, 6));\n    this.setFunctionModule(8, 8, getBit(bits, 7));\n    this.setFunctionModule(7, 8, getBit(bits, 8));\n    for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));\n\n    // Draw second copy\n    for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));\n    for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));\n    this.setFunctionModule(8, this.size - 8, true); // Always dark\n  }\n\n  // Draws two copies of the version bits (with its own error correction code),\n  // based on this object's version field, iff 7 <= version <= 40.\n  private drawVersion(): void {\n    if (this.version < 7) return;\n\n    // Calculate error correction code and pack bits\n    let rem: int = this.version; // version is uint6, in the range [7, 40]\n    for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);\n    const bits: int = (this.version << 12) | rem; // uint18\n    assert(bits >>> 18 == 0);\n\n    // Draw two copies\n    for (let i = 0; i < 18; i++) {\n      const color: boolean = getBit(bits, i);\n      const a: int = this.size - 11 + (i % 3);\n      const b: int = Math.floor(i / 3);\n      this.setFunctionModule(a, b, color);\n      this.setFunctionModule(b, a, color);\n    }\n  }\n\n  // Draws a 9*9 finder pattern including the border separator,\n  // with the center module at (x, y). Modules can be out of bounds.\n  private drawFinderPattern(x: int, y: int): void {\n    for (let dy = -4; dy <= 4; dy++) {\n      for (let dx = -4; dx <= 4; dx++) {\n        const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm\n        const xx: int = x + dx;\n        const yy: int = y + dy;\n        if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)\n          this.setFunctionModule(xx, yy, dist != 2 && dist != 4);\n      }\n    }\n  }\n\n  // Draws a 5*5 alignment pattern, with the center module\n  // at (x, y). All modules must be in bounds.\n  private drawAlignmentPattern(x: int, y: int): void {\n    for (let dy = -2; dy <= 2; dy++) {\n      for (let dx = -2; dx <= 2; dx++)\n        this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);\n    }\n  }\n\n  // Sets the color of a module and marks it as a function module.\n  // Only used by the constructor. Coordinates must be in bounds.\n  private setFunctionModule(x: int, y: int, isDark: boolean): void {\n    this.modules[y]![x] = isDark;\n    this.isFunction[y]![x] = true;\n  }\n\n  /*-- Private helper methods for constructor: Codewords and masking --*/\n\n  // Returns a new byte string representing the given data with the appropriate error correction\n  // codewords appended to it, based on this object's version and error correction level.\n  private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {\n    const ver: int = this.version;\n    const ecl: QrCodeEcc = this.errorCorrectionLevel;\n    if (data.length != QrCode.getNumDataCodewords(ver, ecl))\n      throw new RangeError(\"Invalid argument\");\n\n    // Calculate parameter numbers\n    const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal]![ver]!;\n    const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal]![ver]!;\n    const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);\n    const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks);\n    const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);\n\n    // Split data into blocks and append ECC to each block\n    let blocks: Array<Array<byte>> = [];\n    const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);\n    for (let i = 0, k = 0; i < numBlocks; i++) {\n      let dat: Array<byte> = data.slice(\n        k,\n        k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1),\n      );\n      k += dat.length;\n      const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);\n      if (i < numShortBlocks) dat.push(0);\n      blocks.push(dat.concat(ecc));\n    }\n\n    // Interleave (not concatenate) the bytes from every block into a single sequence\n    let result: Array<byte> = [];\n    for (let i = 0; i < blocks[0]!.length; i++) {\n      blocks.forEach((block, j) => {\n        // Skip the padding byte in short blocks\n        if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]!);\n      });\n    }\n    assert(result.length == rawCodewords);\n    return result;\n  }\n\n  // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire\n  // data area of this QR Code. Function modules need to be marked off before this is called.\n  private drawCodewords(data: Readonly<Array<byte>>): void {\n    if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))\n      throw new RangeError(\"Invalid argument\");\n    let i: int = 0; // Bit index into the data\n    // Do the funny zigzag scan\n    for (let right = this.size - 1; right >= 1; right -= 2) {\n      // Index of right column in each column pair\n      if (right == 6) right = 5;\n      for (let vert = 0; vert < this.size; vert++) {\n        // Vertical counter\n        for (let j = 0; j < 2; j++) {\n          const x: int = right - j; // Actual x coordinate\n          const upward: boolean = ((right + 1) & 2) == 0;\n          const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate\n          if (!this.isFunction[y]![x]! && i < data.length * 8) {\n            this.modules[y]![x] = getBit(data[i >>> 3]!, 7 - (i & 7));\n            i++;\n          }\n          // If this QR Code has any remainder bits (0 to 7), they were assigned as\n          // 0/false/light by the constructor and are left unchanged by this method\n        }\n      }\n    }\n    assert(i == data.length * 8);\n  }\n\n  // XORs the codeword modules in this QR Code with the given mask pattern.\n  // The function modules must be marked and the codeword bits must be drawn\n  // before masking. Due to the arithmetic of XOR, calling applyMask() with\n  // the same mask value a second time will undo the mask. A final well-formed\n  // QR Code needs exactly one (not zero, two, etc.) mask applied.\n  private applyMask(mask: int): void {\n    if (mask < 0 || mask > 7) throw new RangeError(\"Mask value out of range\");\n    for (let y = 0; y < this.size; y++) {\n      for (let x = 0; x < this.size; x++) {\n        let invert: boolean;\n        switch (mask) {\n          case 0:\n            invert = (x + y) % 2 == 0;\n            break;\n          case 1:\n            invert = y % 2 == 0;\n            break;\n          case 2:\n            invert = x % 3 == 0;\n            break;\n          case 3:\n            invert = (x + y) % 3 == 0;\n            break;\n          case 4:\n            invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;\n            break;\n          case 5:\n            invert = ((x * y) % 2) + ((x * y) % 3) == 0;\n            break;\n          case 6:\n            invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;\n            break;\n          case 7:\n            invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;\n            break;\n          default:\n            throw new Error(\"Unreachable\");\n        }\n        if (!this.isFunction[y]![x]! && invert) this.modules[y]![x] = !this.modules[y]![x]!;\n      }\n    }\n  }\n\n  // Calculates and returns the penalty score based on state of this QR Code's current modules.\n  // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.\n  private getPenaltyScore(): int {\n    let result: int = 0;\n\n    // Adjacent modules in row having same color, and finder-like patterns\n    for (let y = 0; y < this.size; y++) {\n      let runColor = false;\n      let runX = 0;\n      let runHistory = [0, 0, 0, 0, 0, 0, 0];\n      for (let x = 0; x < this.size; x++) {\n        if (this.modules[y]![x] === runColor) {\n          runX++;\n          if (runX == 5) result += QrCode.PENALTY_N1;\n          else if (runX > 5) result++;\n        } else {\n          this.finderPenaltyAddHistory(runX, runHistory);\n          if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;\n          runColor = this.modules[y]![x]!;\n          runX = 1;\n        }\n      }\n      result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;\n    }\n    // Adjacent modules in column having same color, and finder-like patterns\n    for (let x = 0; x < this.size; x++) {\n      let runColor = false;\n      let runY = 0;\n      let runHistory = [0, 0, 0, 0, 0, 0, 0];\n      for (let y = 0; y < this.size; y++) {\n        if (this.modules[y]![x] === runColor) {\n          runY++;\n          if (runY == 5) result += QrCode.PENALTY_N1;\n          else if (runY > 5) result++;\n        } else {\n          this.finderPenaltyAddHistory(runY, runHistory);\n          if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;\n          runColor = this.modules[y]![x]!;\n          runY = 1;\n        }\n      }\n      result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;\n    }\n\n    // 2*2 blocks of modules having same color\n    for (let y = 0; y < this.size - 1; y++) {\n      for (let x = 0; x < this.size - 1; x++) {\n        const color: boolean = this.modules[y]![x]!;\n        if (\n          color == this.modules[y]![x + 1]! &&\n          color == this.modules[y + 1]![x]! &&\n          color == this.modules[y + 1]![x + 1]!\n        )\n          result += QrCode.PENALTY_N2;\n      }\n    }\n\n    // Balance of dark and light modules\n    let dark: int = 0;\n    for (const row of this.modules) dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);\n    const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2\n    // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%\n    const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;\n    assert(0 <= k && k <= 9);\n    result += k * QrCode.PENALTY_N4;\n    assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4\n    return result;\n  }\n\n  /*-- Private helper functions --*/\n\n  // Returns an ascending list of positions of alignment patterns for this version number.\n  // Each position is in the range [0,177), and are used on both the x and y axes.\n  // This could be implemented as lookup table of 40 variable-length lists of integers.\n  private getAlignmentPatternPositions(): Array<int> {\n    if (this.version == 1) return [];\n    else {\n      const numAlign: int = Math.floor(this.version / 7) + 2;\n      const step: int =\n        this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;\n      let result: Array<int> = [6];\n      for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);\n      return result;\n    }\n  }\n\n  // Returns the number of data bits that can be stored in a QR Code of the given version number, after\n  // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.\n  // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.\n  private static getNumRawDataModules(ver: int): int {\n    if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)\n      throw new RangeError(\"Version number out of range\");\n    let result: int = (16 * ver + 128) * ver + 64;\n    if (ver >= 2) {\n      const numAlign: int = Math.floor(ver / 7) + 2;\n      result -= (25 * numAlign - 10) * numAlign - 55;\n      if (ver >= 7) result -= 36;\n    }\n    assert(208 <= result && result <= 29648);\n    return result;\n  }\n\n  // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any\n  // QR Code of the given version number and error correction level, with remainder bits discarded.\n  // This stateless pure function could be implemented as a (40*4)-cell lookup table.\n  private static getNumDataCodewords(ver: int, ecl: QrCodeEcc): int {\n    return (\n      Math.floor(QrCode.getNumRawDataModules(ver) / 8) -\n      QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal]![ver]! *\n        QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal]![ver]!\n    );\n  }\n\n  // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be\n  // implemented as a lookup table over all possible parameter values, instead of as an algorithm.\n  private static reedSolomonComputeDivisor(degree: int): Array<byte> {\n    if (degree < 1 || degree > 255) throw new RangeError(\"Degree out of range\");\n    // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.\n    // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].\n    let result: Array<byte> = [];\n    for (let i = 0; i < degree - 1; i++) result.push(0);\n    result.push(1); // Start off with the monomial x^0\n\n    // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),\n    // and drop the highest monomial term which is always 1x^degree.\n    // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).\n    let root = 1;\n    for (let i = 0; i < degree; i++) {\n      // Multiply the current product by (x - r^i)\n      for (let j = 0; j < result.length; j++) {\n        result[j] = QrCode.reedSolomonMultiply(result[j]!, root);\n        if (j + 1 < result.length) result[j]! ^= result[j + 1]!;\n      }\n      root = QrCode.reedSolomonMultiply(root, 0x02);\n    }\n    return result;\n  }\n\n  // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.\n  private static reedSolomonComputeRemainder(\n    data: Readonly<Array<byte>>,\n    divisor: Readonly<Array<byte>>,\n  ): Array<byte> {\n    let result: Array<byte> = divisor.map((_) => 0);\n    for (const b of data) {\n      // Polynomial division\n      const factor: byte = b ^ (result.shift() as byte);\n      result.push(0);\n      divisor.forEach((coef, i) => (result[i]! ^= QrCode.reedSolomonMultiply(coef, factor)));\n    }\n    return result;\n  }\n\n  // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result\n  // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.\n  private static reedSolomonMultiply(x: byte, y: byte): byte {\n    if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError(\"Byte out of range\");\n    // Russian peasant multiplication\n    let z: int = 0;\n    for (let i = 7; i >= 0; i--) {\n      z = (z << 1) ^ ((z >>> 7) * 0x11d);\n      z ^= ((y >>> i) & 1) * x;\n    }\n    assert(z >>> 8 == 0);\n    return z as byte;\n  }\n\n  // Can only be called immediately after a light run is added, and\n  // returns either 0, 1, or 2. A helper function for getPenaltyScore().\n  private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {\n    const n: int = runHistory[1]!;\n    assert(n <= this.size * 3);\n    const core: boolean =\n      n > 0 &&\n      runHistory[2] === n &&\n      runHistory[3] === n * 3 &&\n      runHistory[4] === n &&\n      runHistory[5] === n;\n    return (\n      (core && runHistory[0]! >= n * 4 && runHistory[6]! >= n ? 1 : 0) +\n      (core && runHistory[6]! >= n * 4 && runHistory[0]! >= n ? 1 : 0)\n    );\n  }\n\n  // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().\n  private finderPenaltyTerminateAndCount(\n    currentRunColor: boolean,\n    currentRunLength: int,\n    runHistory: Array<int>,\n  ): int {\n    if (currentRunColor) {\n      // Terminate dark run\n      this.finderPenaltyAddHistory(currentRunLength, runHistory);\n      currentRunLength = 0;\n    }\n    currentRunLength += this.size; // Add light border to final run\n    this.finderPenaltyAddHistory(currentRunLength, runHistory);\n    return this.finderPenaltyCountPatterns(runHistory);\n  }\n\n  // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().\n  private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {\n    if (runHistory[0] === 0) currentRunLength += this.size; // Add light border to initial run\n    runHistory.pop();\n    runHistory.unshift(currentRunLength);\n  }\n\n  /*-- Constants and tables --*/\n\n  // The minimum version number supported in the QR Code Model 2 standard.\n  public static readonly MIN_VERSION: int = 1;\n  // The maximum version number supported in the QR Code Model 2 standard.\n  public static readonly MAX_VERSION: int = 40;\n\n  // For use in getPenaltyScore(), when evaluating which mask is best.\n  private static readonly PENALTY_N1: int = 3;\n  private static readonly PENALTY_N2: int = 3;\n  private static readonly PENALTY_N3: int = 40;\n  private static readonly PENALTY_N4: int = 10;\n\n  private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [\n    // Version: (note that index 0 is for padding, and is set to an illegal value)\n    //0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level\n    [\n      -1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30,\n      30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n    ], // Low\n    [\n      -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28,\n      28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n    ], // Medium\n    [\n      -1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30,\n      30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n    ], // Quartile\n    [\n      -1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24,\n      30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n    ], // High\n  ];\n\n  private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [\n    // Version: (note that index 0 is for padding, and is set to an illegal value)\n    //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level\n    [\n      -1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13,\n      14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25,\n    ], // Low\n    [\n      -1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23,\n      25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,\n    ], // Medium\n    [\n      -1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29,\n      34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,\n    ], // Quartile\n    [\n      -1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35,\n      37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,\n    ], // High\n  ];\n}\n\n// Appends the given number of low-order bits of the given value\n// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.\nfunction appendBits(val: int, len: int, bb: Array<bit>): void {\n  if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError(\"Value out of range\");\n  for (\n    let i = len - 1;\n    i >= 0;\n    i-- // Append bit by bit\n  )\n    bb.push((val >>> i) & 1);\n}\n\n// Returns true iff the i'th bit of x is set to 1.\nfunction getBit(x: int, i: int): boolean {\n  return ((x >>> i) & 1) != 0;\n}\n\n// Throws an exception if the given condition is false.\nfunction assert(cond: boolean): void {\n  if (!cond) throw new Error(\"Assertion error\");\n}\n\n/*---- Data segment class ----*/\n\n/*\n * A segment of character/binary/control data in a QR Code symbol.\n * Instances of this class are immutable.\n * The mid-level way to create a segment is to take the payload data\n * and call a static factory function such as QrSegment.makeNumeric().\n * The low-level way to create a segment is to custom-make the bit buffer\n * and call the QrSegment() constructor with appropriate values.\n * This segment class imposes no length restrictions, but QR Codes have restrictions.\n * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.\n * Any segment longer than this is meaningless for the purpose of generating QR Codes.\n */\nexport class QrSegment {\n  public static Mode: typeof QrSegmentMode;\n\n  /*-- Static factory functions (mid level) --*/\n\n  // Returns a segment representing the given binary data encoded in\n  // byte mode. All input byte arrays are acceptable. Any text string\n  // can be converted to UTF-8 bytes and encoded as a byte mode segment.\n  public static makeBytes(data: Readonly<Array<byte>>): QrSegment {\n    let bb: Array<bit> = [];\n    for (const b of data) appendBits(b, 8, bb);\n    return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);\n  }\n\n  // Returns a segment representing the given string of decimal digits encoded in numeric mode.\n  public static makeNumeric(digits: string): QrSegment {\n    if (!QrSegment.isNumeric(digits))\n      throw new RangeError(\"String contains non-numeric characters\");\n    let bb: Array<bit> = [];\n    for (let i = 0; i < digits.length; ) {\n      // Consume up to 3 digits per iteration\n      const n: int = Math.min(digits.length - i, 3);\n      appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);\n      i += n;\n    }\n    return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);\n  }\n\n  // Returns a segment representing the given text string encoded in alphanumeric mode.\n  // The characters allowed are: 0 to 9, A to Z (uppercase only), space,\n  // dollar, percent, asterisk, plus, hyphen, period, slash, colon.\n  public static makeAlphanumeric(text: string): QrSegment {\n    if (!QrSegment.isAlphanumeric(text))\n      throw new RangeError(\"String contains unencodable characters in alphanumeric mode\");\n    let bb: Array<bit> = [];\n    let i: int;\n    for (i = 0; i + 2 <= text.length; i += 2) {\n      // Process groups of 2\n      let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;\n      temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));\n      appendBits(temp, 11, bb);\n    }\n    if (i < text.length)\n      // 1 character remaining\n      appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);\n    return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);\n  }\n\n  // Returns a new mutable list of zero or more segments to represent the given Unicode text string.\n  // The result may use various segment modes and switch modes to optimize the length of the bit stream.\n  public static makeSegments(text: string): Array<QrSegment> {\n    // Select the most efficient segment encoding automatically\n    if (text == \"\") return [];\n    else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];\n    else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];\n    else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];\n  }\n\n  // Returns a segment representing an Extended Channel Interpretation\n  // (ECI) designator with the given assignment value.\n  public static makeEci(assignVal: int): QrSegment {\n    let bb: Array<bit> = [];\n    if (assignVal < 0) throw new RangeError(\"ECI assignment value out of range\");\n    else if (assignVal < 1 << 7) appendBits(assignVal, 8, bb);\n    else if (assignVal < 1 << 14) {\n      appendBits(0b10, 2, bb);\n      appendBits(assignVal, 14, bb);\n    } else if (assignVal < 1000000) {\n      appendBits(0b110, 3, bb);\n      appendBits(assignVal, 21, bb);\n    } else throw new RangeError(\"ECI assignment value out of range\");\n    return new QrSegment(QrSegment.Mode.ECI, 0, bb);\n  }\n\n  // Tests whether the given string can be encoded as a segment in numeric mode.\n  // A string is encodable iff each character is in the range 0 to 9.\n  public static isNumeric(text: string): boolean {\n    return QrSegment.NUMERIC_REGEX.test(text);\n  }\n\n  // Tests whether the given string can be encoded as a segment in alphanumeric mode.\n  // A string is encodable iff each character is in the following set: 0 to 9, A to Z\n  // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.\n  public static isAlphanumeric(text: string): boolean {\n    return QrSegment.ALPHANUMERIC_REGEX.test(text);\n  }\n\n  /*-- Constructor (low level) and fields --*/\n\n  public readonly mode: QrSegmentMode;\n  public readonly numChars: int;\n  private readonly bitData: Array<bit>;\n\n  // Creates a new QR Code segment with the given attributes and data.\n  // The character count (numChars) must agree with the mode and the bit buffer length,\n  // but the constraint isn't checked. The given bit buffer is cloned and stored.\n  public constructor(\n    // The mode indicator of this segment.\n    mode: QrSegmentMode,\n\n    // The length of this segment's unencoded data. Measured in characters for\n    // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.\n    // Always zero or positive. Not the same as the data's bit length.\n    numChars: int,\n\n    // The data bits of this segment. Accessed through getData().\n    bitData: Array<bit>,\n  ) {\n    this.mode = mode;\n    this.numChars = numChars;\n    if (numChars < 0) throw new RangeError(\"Invalid argument\");\n    this.bitData = bitData.slice(); // Make defensive copy\n  }\n\n  /*-- Methods --*/\n\n  // Returns a new copy of the data bits of this segment.\n  public getData(): Array<bit> {\n    return this.bitData.slice(); // Make defensive copy\n  }\n\n  // (Package-private) Calculates and returns the number of bits needed to encode the given segments at\n  // the given version. The result is infinity if a segment has too many characters to fit its length field.\n  public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {\n    let result: number = 0;\n    for (const seg of segs) {\n      const ccbits: int = seg.mode.numCharCountBits(version);\n      if (seg.numChars >= 1 << ccbits) return Infinity; // The segment's length doesn't fit the field's bit width\n      result += 4 + ccbits + seg.bitData.length;\n    }\n    return result;\n  }\n\n  // Returns a new array of bytes representing the given string encoded in UTF-8.\n  private static toUtf8ByteArray(str: string): Array<byte> {\n    str = encodeURI(str);\n    let result: Array<byte> = [];\n    for (let i = 0; i < str.length; i++) {\n      if (str.charAt(i) != \"%\") result.push(str.charCodeAt(i));\n      else {\n        result.push(parseInt(str.substring(i + 1, i + 3), 16));\n        i += 2;\n      }\n    }\n    return result;\n  }\n\n  /*-- Constants --*/\n\n  // Describes precisely all strings that are encodable in numeric mode.\n  private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;\n\n  // Describes precisely all strings that are encodable in alphanumeric mode.\n  private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\\/:-]*$/;\n\n  // The set of all legal characters in alphanumeric mode,\n  // where each character value maps to the index in the string.\n  private static readonly ALPHANUMERIC_CHARSET: string =\n    \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:\";\n}\n\n/*---- Public helper enumeration ----*/\n\nclass QrCodeEcc {\n  /*-- Constants --*/\n\n  public static readonly LOW = new QrCodeEcc(0, 1); // The QR Code can tolerate about  7% erroneous codewords\n  public static readonly MEDIUM = new QrCodeEcc(1, 0); // The QR Code can tolerate about 15% erroneous codewords\n  public static readonly QUARTILE = new QrCodeEcc(2, 3); // The QR Code can tolerate about 25% erroneous codewords\n  public static readonly HIGH = new QrCodeEcc(3, 2); // The QR Code can tolerate about 30% erroneous codewords\n\n  public readonly ordinal: int;\n  public readonly formatBits: int;\n\n  /*-- Constructor and fields --*/\n\n  private constructor(\n    // In the range 0 to 3 (unsigned 2-bit integer).\n    ordinal: int,\n    // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).\n    formatBits: int,\n  ) {\n    this.ordinal = ordinal;\n    this.formatBits = formatBits;\n  }\n}\n\n/*---- Public helper enumeration ----*/\n\nclass QrSegmentMode {\n  /*-- Constants --*/\n\n  public static readonly NUMERIC = new QrSegmentMode(0x1, [10, 12, 14]);\n  public static readonly ALPHANUMERIC = new QrSegmentMode(0x2, [9, 11, 13]);\n  public static readonly BYTE = new QrSegmentMode(0x4, [8, 16, 16]);\n  public static readonly KANJI = new QrSegmentMode(0x8, [8, 10, 12]);\n  public static readonly ECI = new QrSegmentMode(0x7, [0, 0, 0]);\n\n  public readonly modeBits: int;\n  private readonly numBitsCharCount: [int, int, int];\n\n  /*-- Constructor and fields --*/\n\n  private constructor(\n    // The mode indicator bits, which is a uint4 value (range 0 to 15).\n    modeBits: int,\n    // Number of character count bits for three different version ranges.\n    numBitsCharCount: [int, int, int],\n  ) {\n    this.modeBits = modeBits;\n    this.numBitsCharCount = numBitsCharCount;\n  }\n\n  /*-- Method --*/\n\n  // (Package-private) Returns the bit width of the character count field for a segment in\n  // this mode in a QR Code at the given version number. The result is in the range [0, 16].\n  public numCharCountBits(ver: int): int {\n    return this.numBitsCharCount[Math.floor((ver + 7) / 17)]!;\n  }\n}\n\nQrCode.Ecc = QrCodeEcc;\nQrSegment.Mode = QrSegmentMode;\n","import * as NodeOS from \"node:os\";\n\nimport { QrCode } from \"@t3tools/shared/qrCode\";\nimport * as Effect from \"effect/Effect\";\nimport { HttpServer } from \"effect/unstable/http\";\n\nimport { ServerConfig } from \"./config.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\n\nexport interface HeadlessServeAccessInfo {\n  readonly connectionString: string;\n  readonly token: string;\n  readonly pairingUrl: string;\n}\n\ntype NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;\n\nexport const isLoopbackHost = (host: string | undefined): boolean => {\n  if (!host || host.length === 0) {\n    return true;\n  }\n\n  return (\n    host === \"localhost\" ||\n    host === \"127.0.0.1\" ||\n    host === \"::1\" ||\n    host === \"[::1]\" ||\n    host.startsWith(\"127.\")\n  );\n};\n\nexport const isWildcardHost = (host: string | undefined): boolean =>\n  host === \"0.0.0.0\" || host === \"::\" || host === \"[::]\";\n\nexport const formatHostForUrl = (host: string): string =>\n  host.includes(\":\") && !host.startsWith(\"[\") ? `[${host}]` : host;\n\nconst normalizeHost = (host: string): string =>\n  host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n\nconst isIpv4Family = (family: string | number): boolean => family === \"IPv4\" || family === 4;\n\nconst isIpv6Family = (family: string | number): boolean => family === \"IPv6\" || family === 6;\n\nexport const resolveHeadlessConnectionHost = (\n  host: string | undefined,\n  interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),\n): string => {\n  if (!host) {\n    return \"localhost\";\n  }\n\n  if (!isWildcardHost(host)) {\n    return normalizeHost(host);\n  }\n\n  const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []);\n  const externalIpv4 = interfaceEntries.find(\n    (entry) => !entry.internal && isIpv4Family(entry.family),\n  );\n  if (externalIpv4) {\n    return externalIpv4.address;\n  }\n\n  const externalIpv6 = interfaceEntries.find(\n    (entry) => !entry.internal && isIpv6Family(entry.family),\n  );\n  return externalIpv6 ? normalizeHost(externalIpv6.address) : \"localhost\";\n};\n\nexport const resolveHeadlessConnectionString = (\n  host: string | undefined,\n  port: number,\n  interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),\n): string => {\n  const connectionHost = resolveHeadlessConnectionHost(host, interfaces);\n  return `http://${formatHostForUrl(connectionHost)}:${port}`;\n};\n\nexport const resolveListeningPort = (address: unknown, fallbackPort: number): number => {\n  if (\n    typeof address === \"object\" &&\n    address !== null &&\n    \"port\" in address &&\n    typeof address.port === \"number\"\n  ) {\n    return address.port;\n  }\n  return fallbackPort;\n};\n\nexport const buildPairingUrl = (connectionString: string, token: string): string => {\n  const url = new URL(connectionString);\n  url.pathname = \"/pair\";\n  url.searchParams.delete(\"token\");\n  url.hash = new URLSearchParams([[\"token\", token]]).toString();\n  return url.toString();\n};\n\nexport const renderTerminalQrCode = (value: string, margin = 2): string => {\n  const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);\n  const rows: Array<string> = [];\n  const isDark = (x: number, y: number): boolean =>\n    x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);\n\n  for (let y = -margin; y < qrCode.size + margin; y += 2) {\n    let row = \"\";\n\n    for (let x = -margin; x < qrCode.size + margin; x += 1) {\n      const topDark = isDark(x, y);\n      const bottomDark = isDark(x, y + 1);\n\n      row += topDark ? (bottomDark ? \"█\" : \"▀\") : bottomDark ? \"▄\" : \" \";\n    }\n\n    rows.push(row);\n  }\n\n  return rows.join(\"\\n\");\n};\n\nexport const formatHeadlessServeOutput = (_accessInfo: HeadlessServeAccessInfo): string =>\n  \"AgentLink server is ready.\\n\";\n\nexport const issueHeadlessServeAccessInfo = Effect.fn(\"issueHeadlessServeAccessInfo\")(function* () {\n  const serverConfig = yield* ServerConfig;\n  const httpServer = yield* HttpServer.HttpServer;\n  const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n  const connectionString = resolveHeadlessConnectionString(\n    serverConfig.host,\n    resolveListeningPort(httpServer.address, serverConfig.port),\n  );\n  const issued = yield* serverAuth.issueStartupPairingCredential();\n\n  return {\n    connectionString,\n    token: issued.credential,\n    pairingUrl: buildPairingUrl(connectionString, issued.credential),\n  } satisfies HeadlessServeAccessInfo;\n});\n","import * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport { writeFileStringAtomically } from \"./atomicWrite.ts\";\nimport type * as ServerConfig from \"./config.ts\";\nimport { formatHostForUrl, isWildcardHost } from \"./startupAccess.ts\";\n\nexport const PersistedServerRuntimeState = Schema.Struct({\n  version: Schema.Literal(1),\n  pid: Schema.Int,\n  host: Schema.optional(Schema.String),\n  port: Schema.Int,\n  origin: Schema.String,\n  // Present when the server fronts a dev web server (VITE_DEV_SERVER_URL).\n  // Dev is single-origin: browsers must pair through this URL, not `origin`.\n  devUrl: Schema.optional(Schema.String),\n  startedAt: Schema.String,\n});\nexport type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;\n\nexport class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(\n  \"ServerRuntimeStateError\",\n  {\n    operation: Schema.Literals([\"persist\", \"read\", \"decode\", \"clear\"]),\n    statePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;\n  }\n}\n\nconst decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(\n  Schema.fromJsonString(PersistedServerRuntimeState),\n);\n\nconst runtimeOriginForConfig = (\n  config: Pick<ServerConfig.ServerConfig[\"Service\"], \"host\">,\n  port: number,\n): PersistedServerRuntimeState[\"origin\"] => {\n  const hostname =\n    config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : \"127.0.0.1\";\n  return `http://${hostname}:${port}`;\n};\n\nexport const makePersistedServerRuntimeState = (input: {\n  readonly config: Pick<ServerConfig.ServerConfig[\"Service\"], \"host\" | \"devUrl\">;\n  readonly port: number;\n}): Effect.Effect<PersistedServerRuntimeState> =>\n  Effect.map(DateTime.now, (now) => ({\n    version: 1,\n    pid: process.pid,\n    ...(input.config.host ? { host: input.config.host } : {}),\n    port: input.port,\n    origin: runtimeOriginForConfig(input.config, input.port),\n    ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),\n    startedAt: DateTime.formatIso(now),\n  }));\n\nexport const persistServerRuntimeState = (input: {\n  readonly path: string;\n  readonly state: PersistedServerRuntimeState;\n}) =>\n  writeFileStringAtomically({\n    filePath: input.path,\n    contents: `${JSON.stringify(input.state)}\\n`,\n  }).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerRuntimeStateError({\n          operation: \"persist\",\n          statePath: input.path,\n          cause,\n        }),\n    ),\n  );\n\nexport const clearPersistedServerRuntimeState = (path: string) =>\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem;\n    yield* fs.remove(path, { force: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerRuntimeStateError({\n            operation: \"clear\",\n            statePath: path,\n            cause,\n          }),\n      ),\n      Effect.catchTags({\n        ServerRuntimeStateError: (error) =>\n          Effect.logWarning(error.message).pipe(\n            Effect.annotateLogs({\n              operation: error.operation,\n              statePath: error.statePath,\n              cause: error,\n            }),\n          ),\n      }),\n    );\n  });\n\nexport const readPersistedServerRuntimeState = (path: string) =>\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem;\n    const raw = yield* fs.readFileString(path).pipe(\n      Effect.matchEffect({\n        onFailure: (cause) =>\n          cause.reason._tag === \"NotFound\"\n            ? Effect.succeed(Option.none<string>())\n            : Effect.fail(\n                new ServerRuntimeStateError({\n                  operation: \"read\",\n                  statePath: path,\n                  cause,\n                }),\n              ),\n        onSuccess: (contents) => Effect.succeed(Option.some(contents)),\n      }),\n    );\n    if (Option.isNone(raw)) {\n      return Option.none<PersistedServerRuntimeState>();\n    }\n\n    const trimmed = raw.value.trim();\n    if (trimmed.length === 0) {\n      return Option.none<PersistedServerRuntimeState>();\n    }\n\n    return yield* decodePersistedServerRuntimeState(trimmed).pipe(\n      Effect.map(Option.some),\n      Effect.mapError(\n        (cause) =>\n          new ServerRuntimeStateError({\n            operation: \"decode\",\n            statePath: path,\n            cause,\n          }),\n      ),\n    );\n  }).pipe(\n    Effect.catchTags({\n      ServerRuntimeStateError: (error) =>\n        Effect.logWarning(error.message).pipe(\n          Effect.annotateLogs({\n            operation: error.operation,\n            statePath: error.statePath,\n            cause: error,\n          }),\n          Effect.as(Option.none<PersistedServerRuntimeState>()),\n        ),\n    }),\n  );\n","/**\n * `t3 pair` - mint a pairing token for an already-running server and print it\n * as a QR code, without restarting anything.\n *\n * Discovery reads the `server-runtime.json` a live server persists next to its\n * database, then confirms the process is actually answering by fetching its\n * public environment descriptor. Inside a linked git worktree the worktree's\n * own `.t3` is checked first (matching dev-runner precedence); otherwise the\n * shared T3 home. `--tailscale` publishes the server over Tailscale Serve\n * HTTPS and pairs through the tailnet URL instead.\n */\nimport {\n  AuthStandardClientScopes,\n  ExecutionEnvironmentDescriptor,\n  PortSchema,\n} from \"@t3tools/contracts\";\nimport { resolveWorktreeT3Home } from \"@t3tools/shared/devHome\";\nimport {\n  buildTailscaleHttpsBaseUrl,\n  DEFAULT_TAILSCALE_SERVE_PORT,\n  ensureTailscaleServe,\n  readTailscaleStatus,\n} from \"@t3tools/tailscale\";\nimport * as Config from \"effect/Config\";\nimport * as Console from \"effect/Console\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport { Command, Flag, GlobalFlag } from \"effect/unstable/cli\";\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientRequest,\n  HttpClientResponse,\n} from \"effect/unstable/http\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { resolveBaseDir } from \"../os-jank.ts\";\nimport {\n  type PersistedServerRuntimeState,\n  readPersistedServerRuntimeState,\n} from \"../serverRuntimeState.ts\";\nimport {\n  buildPairingUrl,\n  formatHostForUrl,\n  isLoopbackHost,\n  isWildcardHost,\n  renderTerminalQrCode,\n  resolveHeadlessConnectionString,\n} from \"../startupAccess.ts\";\nimport { baseDirFlag, DurationFromString } from \"./config.ts\";\n\nconst WELL_KNOWN_ENVIRONMENT_PATH = \"/.well-known/t3/environment\";\nconst PAIR_PROBE_TIMEOUT = Duration.millis(2_500);\n// Tailscale provisions an HTTPS certificate on the first request to a fresh\n// serve mapping, which can take a few seconds.\nconst TAILSCALE_PROBE_ATTEMPTS = 5;\nconst TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);\n\nexport type PairStateVariant = \"userdata\" | \"dev\";\n\n// deriveServerPaths only checks devUrl for undefined-ness when picking the\n// dev-vs-userdata state directory; the value itself is not used.\nconst DEV_VARIANT_PLACEHOLDER_URL = new URL(\"http://localhost\");\n\nexport class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(\n  \"NoRunningServerError\",\n  {\n    checkedStatePaths: Schema.Array(Schema.String),\n  },\n) {\n  override get message(): string {\n    return [\n      \"No running T3 Code server found.\",\n      ...this.checkedStatePaths.map((statePath) => `  checked ${statePath}`),\n      \"Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.\",\n    ].join(\"\\n\");\n  }\n}\n\n// Each tailscale failure gets its own class (same reasoning as\n// scripts/lib/dev-share.ts): distinct caller-visible message, distinct remedy.\nexport class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(\n  \"TailscaleUnavailableError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.\";\n  }\n}\n\nexport class MagicDnsNameMissingError extends Schema.TaggedErrorClass<MagicDnsNameMissingError>()(\n  \"MagicDnsNameMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.\";\n  }\n}\n\nexport class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesOtherEnvironmentError>()(\n  \"ServesOtherEnvironmentError\",\n  { servePort: Schema.Number },\n) {\n  override get message(): string {\n    return `Tailscale Serve on HTTPS port ${String(this.servePort)} already fronts a different T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;\n  }\n}\n\nexport class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(\n  \"TailscaleServeFailedError\",\n  { servePort: Schema.Number, cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \\`tailscale serve --https=${String(this.servePort)} --bg <local-url>\\` by hand to see why.`;\n  }\n}\n\nexport class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(\n  \"ServePortOccupiedError\",\n  { servePort: Schema.Number },\n) {\n  override get message(): string {\n    return `HTTPS port ${String(this.servePort)} on the tailnet already serves something that is not a T3 Code server. Pass --tailscale-serve-port to publish this one on another port.`;\n  }\n}\n\n/** The URL a browser or phone should pair through, absent Tailscale. */\nexport const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>\n  state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);\n\nexport class DevServerNotProxiableError extends Schema.TaggedErrorClass<DevServerNotProxiableError>()(\n  \"DevServerNotProxiableError\",\n  { devUrl: Schema.String },\n) {\n  override get message(): string {\n    return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;\n  }\n}\n\nconst isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);\n\n/**\n * The local endpoint Tailscale Serve should proxy to. Dev servers are\n * single-origin, so the web dev server's port is the one to publish; the\n * backend rides along behind Vite's proxy. Serve targets are always plain\n * HTTP, so an HTTPS dev URL cannot be proxied and is rejected.\n */\nexport const resolveTailscaleLocalTarget = (\n  state: PersistedServerRuntimeState,\n): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {\n  if (state.devUrl !== undefined) {\n    const devUrl = new URL(state.devUrl);\n    if (devUrl.protocol !== \"http:\") {\n      return new DevServerNotProxiableError({ devUrl: state.devUrl });\n    }\n    const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;\n    return isLoopbackHost(devUrl.hostname)\n      ? { localPort }\n      : { localPort, localHost: devUrl.hostname };\n  }\n  // A server bound to one specific interface does not answer on loopback, so\n  // the proxy has to target that interface directly.\n  if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {\n    return { localPort: state.port, localHost: formatHostForUrl(state.host) };\n  }\n  return { localPort: state.port };\n};\n\nexport const formatPairOutput = (input: {\n  readonly serverLabel: string;\n  readonly origin: string;\n  readonly pairingUrl: string;\n  readonly token: string;\n  readonly expiresAt: DateTime.Utc;\n  readonly notes: ReadonlyArray<string>;\n}): string =>\n  [\n    `Pairing with ${input.serverLabel} (${input.origin}).`,\n    \"\",\n    renderTerminalQrCode(input.pairingUrl),\n    \"\",\n    `Pairing URL: ${input.pairingUrl}`,\n    `Token: ${input.token}`,\n    `Expires: ${DateTime.formatIso(input.expiresAt)}`,\n    ...input.notes.flatMap((note) => [\"\", `Note: ${note}`]),\n    \"\",\n  ].join(\"\\n\");\n\n/**\n * Three outcomes, because they drive different decisions: a T3 descriptor\n * (pair with it), nothing answering (safe to configure Tailscale Serve), or\n * something answering that is not a T3 server (do NOT overwrite its mapping).\n */\ntype EnvironmentProbeResult =\n  | { readonly _tag: \"descriptor\"; readonly descriptor: ExecutionEnvironmentDescriptor }\n  | { readonly _tag: \"unreachable\" }\n  | { readonly _tag: \"not-a-t3-server\" };\n\nconst probeEnvironmentDescriptor = (\n  baseUrl: string,\n): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient;\n    const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());\n    const response = yield* client.execute(request).pipe(\n      Effect.timeout(PAIR_PROBE_TIMEOUT),\n      // Transport failure or timeout: nothing (reachable) is listening there.\n      Effect.mapError(() => ({ _tag: \"unreachable\" }) as const),\n    );\n    // Bad-gateway family means a proxy (Tailscale Serve) answered for a\n    // backend that is gone — a stale mapping, not a live occupant. Treating\n    // it as unreachable lets `t3 pair --tailscale` repair its own mapping\n    // after the server's port changed.\n    if (response.status === 502 || response.status === 503 || response.status === 504) {\n      return { _tag: \"unreachable\" } as const;\n    }\n    // Anything else that answered HTTP but not with a valid descriptor is\n    // some other service.\n    const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(\n      Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),\n      Effect.mapError(() => ({ _tag: \"not-a-t3-server\" }) as const),\n    );\n    return { _tag: \"descriptor\", descriptor } as const;\n  }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));\n\n// signal 0 delivers nothing; it only reports whether the pid exists. EPERM\n// means it exists but belongs to another user, which still counts as alive.\nconst isProcessAlive = (pid: number): boolean => {\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return error instanceof Error && \"code\" in error && error.code === \"EPERM\";\n  }\n};\n\ninterface DiscoveredPairTarget {\n  readonly baseDir: string;\n  readonly variant: PairStateVariant;\n  readonly state: PersistedServerRuntimeState;\n  readonly descriptor: ExecutionEnvironmentDescriptor;\n}\n\nconst discoverPairTarget = Effect.fn(\"pair.discoverPairTarget\")(function* (\n  explicitBaseDir: string | undefined,\n) {\n  const bases: Array<string> = [];\n  if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {\n    bases.push(yield* resolveBaseDir(explicitBaseDir));\n  } else {\n    // Same precedence as dev-runner: inside a linked worktree its own `.t3`\n    // outranks the shared home, so `t3 pair` in a worktree pairs with the dev\n    // server under test rather than the daily-driver install.\n    const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());\n    if (worktreeHome !== undefined) {\n      bases.push(worktreeHome);\n    }\n    const envHome = yield* Config.string(\"T3CODE_HOME\").pipe(Config.option);\n    bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));\n  }\n\n  const checkedStatePaths: Array<string> = [];\n  for (const baseDir of new Set(bases)) {\n    for (const variant of [\"userdata\", \"dev\"] as const) {\n      const derivedPaths = yield* ServerConfig.deriveServerPaths(\n        baseDir,\n        variant === \"dev\" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,\n        {},\n      );\n      const statePath = derivedPaths.serverRuntimeStatePath;\n      checkedStatePaths.push(statePath);\n      const state = yield* readPersistedServerRuntimeState(statePath);\n      if (Option.isNone(state)) {\n        continue;\n      }\n      // The pid check guards against a dead server's state file whose port\n      // was since reused by a different server: pairing would then mint a\n      // token in the old database while the QR code points at the new server.\n      if (!isProcessAlive(state.value.pid)) {\n        continue;\n      }\n      const probed = yield* probeEnvironmentDescriptor(state.value.origin);\n      if (probed._tag !== \"descriptor\") {\n        continue;\n      }\n      return {\n        baseDir,\n        variant,\n        state: state.value,\n        descriptor: probed.descriptor,\n      } satisfies DiscoveredPairTarget;\n    }\n  }\n  return yield* new NoRunningServerError({ checkedStatePaths });\n});\n\n/**\n * Server config pointed at the discovered server's state directory, so the\n * minted token lands in the database the running server reads from. Built by\n * hand rather than through `resolveServerConfig` to keep the dev-vs-userdata\n * choice pinned to where the runtime state was actually found, independent of\n * ambient environment variables.\n */\nconst makePairServerConfig = Effect.fn(function* (input: {\n  readonly target: DiscoveredPairTarget;\n  readonly logLevel: ServerConfig.ServerConfig[\"Service\"][\"logLevel\"];\n}) {\n  const { baseDir, variant, state } = input.target;\n  // The state-dir variant does not imply dev-ness: a worktree dev server uses\n  // an explicit home and therefore lands in `userdata`. The recorded devUrl is\n  // what actually marks a dev server.\n  const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;\n  const derivedPaths = yield* ServerConfig.deriveServerPaths(\n    baseDir,\n    variant === \"dev\" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,\n    {},\n  );\n  return ServerConfig.make({\n    logLevel: input.logLevel,\n    traceMinLevel: \"Info\",\n    traceTimingEnabled: false,\n    traceBatchWindowMs: 1_000,\n    traceMaxBytes: 10 * 1024 * 1024,\n    traceMaxFiles: 10,\n    otlpTracesUrl: undefined,\n    otlpMetricsUrl: undefined,\n    otlpExportIntervalMs: 10_000,\n    otlpServiceName: \"t3-server\",\n    mode: \"web\",\n    port: state.port,\n    host: state.host,\n    cwd: process.cwd(),\n    baseDir,\n    ...derivedPaths,\n    staticDir: undefined,\n    devUrl,\n    devAllowedOrigins: [],\n    noBrowser: true,\n    startupPresentation: \"headless\",\n    desktopBootstrapToken: undefined,\n    desktopTelemetryFd: undefined,\n    desktopTelemetryControlFd: undefined,\n    resourceMonitorPath: undefined,\n    autoBootstrapProjectFromCwd: false,\n    logWebSocketEvents: false,\n    tailscaleServeEnabled: false,\n    tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,\n  });\n});\n\nconst awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {\n  let last: EnvironmentProbeResult = { _tag: \"unreachable\" };\n  for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {\n    last = yield* probeEnvironmentDescriptor(baseUrl);\n    if (last._tag === \"descriptor\") {\n      return last;\n    }\n    yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);\n  }\n  return last;\n});\n\nconst resolveTailscalePairingBase = Effect.fn(\"pair.resolveTailscalePairingBase\")(\n  function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {\n    const notes: Array<string> = [];\n    const status = yield* readTailscaleStatus.pipe(\n      Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),\n    );\n    if (status.magicDnsName === null) {\n      return yield* new MagicDnsNameMissingError();\n    }\n    const baseUrl = buildTailscaleHttpsBaseUrl({\n      magicDnsName: status.magicDnsName,\n      servePort: input.servePort,\n    });\n\n    // Only an unreachable port, or a mapping already fronting this exact\n    // environment, is safe to (re)configure. Any other responder — T3 or not\n    // — must not have its mapping silently replaced.\n    const existing = yield* probeEnvironmentDescriptor(baseUrl);\n    if (existing._tag === \"descriptor\") {\n      if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {\n        return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });\n      }\n      // Matching environment id proves the mapping reaches this server, but\n      // not through which port: for a dev server it may front the backend\n      // (whose /.well-known also answers) while /pair only renders through\n      // the web origin. Reuse as-is for regular servers; fall through and\n      // repoint our own mapping at the web port for dev servers.\n      if (input.target.state.devUrl === undefined) {\n        return { baseUrl, notes };\n      }\n    }\n    if (existing._tag === \"not-a-t3-server\") {\n      return yield* new ServePortOccupiedError({ servePort: input.servePort });\n    }\n\n    const localTarget = resolveTailscaleLocalTarget(input.target.state);\n    if (isDevServerNotProxiableError(localTarget)) {\n      return yield* localTarget;\n    }\n    yield* ensureTailscaleServe({\n      localPort: localTarget.localPort,\n      servePort: input.servePort,\n      ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),\n    }).pipe(\n      Effect.mapError(\n        (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),\n      ),\n    );\n    notes.push(\n      `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \\`tailscale serve --https=${String(input.servePort)} off\\`.`,\n    );\n\n    const probed = yield* awaitEnvironmentDescriptor(baseUrl);\n    if (probed._tag === \"descriptor\") {\n      if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {\n        return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });\n      }\n    } else {\n      notes.push(\n        \"The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.\",\n      );\n    }\n    return { baseUrl, notes };\n  },\n);\n\nconst mintPairingLink = Effect.fn(\"pair.mintPairingLink\")(function* (input: {\n  readonly config: ServerConfig.ServerConfig[\"Service\"];\n  readonly ttl: Option.Option<Duration.Duration>;\n  readonly label: Option.Option<string>;\n}) {\n  return yield* Effect.gen(function* () {\n    const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    return yield* environmentAuth.createPairingLink({\n      scopes: AuthStandardClientScopes,\n      subject: \"one-time-token\",\n      label: Option.getOrElse(input.label, () => \"t3 pair\"),\n      ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),\n    });\n  }).pipe(\n    Effect.provide(\n      EnvironmentAuth.runtimeLayer.pipe(\n        Layer.provide(ServerConfig.layer(input.config)),\n        Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),\n      ),\n    ),\n  );\n});\n\nconst ttlFlag = Flag.string(\"ttl\").pipe(\n  Flag.withSchema(DurationFromString),\n  Flag.withDescription(\n    \"Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.\",\n  ),\n  Flag.optional,\n);\n\nconst labelFlag = Flag.string(\"label\").pipe(\n  Flag.withDescription(\"Optional label shown in the server's connections list.\"),\n  Flag.optional,\n);\n\nconst tailscaleFlag = Flag.boolean(\"tailscale\").pipe(\n  Flag.withDescription(\n    \"Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.\",\n  ),\n  Flag.withDefault(false),\n);\n\nconst tailscaleServePortFlag = Flag.integer(\"tailscale-serve-port\").pipe(\n  Flag.withSchema(PortSchema),\n  Flag.withDescription(\"HTTPS port for Tailscale Serve when --tailscale is enabled.\"),\n  Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),\n);\n\nexport const pairCommand = Command.make(\"pair\", {\n  baseDir: baseDirFlag,\n  ttl: ttlFlag,\n  label: labelFlag,\n  tailscale: tailscaleFlag,\n  tailscaleServePort: tailscaleServePortFlag,\n}).pipe(\n  Command.withDescription(\n    \"Mint a pairing token for a running T3 Code server and print it as a QR code.\",\n  ),\n  Command.withHandler((flags) =>\n    Effect.gen(function* () {\n      const cliLogLevel = yield* GlobalFlag.LogLevel;\n      // Default to Warn so storage/migration chatter cannot bury the QR code;\n      // an explicit --log-level still wins.\n      const logLevel = Option.getOrElse(cliLogLevel, () => \"Warn\" as const);\n\n      const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));\n\n      const notes: Array<string> = [];\n      let pairingBaseUrl: string;\n      if (flags.tailscale) {\n        const resolved = yield* resolveTailscalePairingBase({\n          target,\n          servePort: flags.tailscaleServePort,\n        });\n        pairingBaseUrl = resolved.baseUrl;\n        notes.push(...resolved.notes);\n      } else {\n        pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);\n        if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {\n          notes.push(\n            \"This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.\",\n          );\n        }\n        if (target.variant === \"dev\" && target.state.devUrl === undefined) {\n          notes.push(\n            \"This dev server did not record its web URL; restart it so pairing can go through the web origin.\",\n          );\n        }\n      }\n\n      const config = yield* makePairServerConfig({ target, logLevel });\n      const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });\n      const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);\n\n      yield* Console.log(\n        formatPairOutput({\n          serverLabel: target.descriptor.label,\n          origin: target.state.origin,\n          pairingUrl,\n          token: issued.credential,\n          expiresAt: issued.expiresAt,\n          notes,\n        }),\n      );\n    }).pipe(Effect.provide(FetchHttpClient.layer)),\n  ),\n);\n","import * as Arr from \"../../Array.js\";\nimport * as Cause from \"../../Cause.js\";\nimport * as Channel from \"../../Channel.js\";\nimport * as ChannelSchema from \"../../ChannelSchema.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Duration from \"../../Duration.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Pull from \"../../Pull.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nconst SseErrorTypeId = \"~effect/encoding/Sse/SseError\";\n/**\n * Error reason raised when pending Server-Sent Events state exceeds the\n * configured maximum size.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class EventTooLarge extends /*#__PURE__*/Data.TaggedError(\"EventTooLarge\") {\n  get message() {\n    return `Pending SSE event exceeded the maximum size of ${this.maxEventSize}`;\n  }\n}\n/**\n * Error raised when decoding a Server-Sent Events stream fails.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class SseError extends /*#__PURE__*/Data.TaggedError(\"SseError\") {\n  /**\n   * Marks this value as an SSE decoding error.\n   *\n   * @since 4.0.0\n   */\n  [SseErrorTypeId] = SseErrorTypeId;\n  /**\n   * Delegates the public message to the underlying SSE error reason.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return this.reason.message;\n  }\n}\nconst defaultMaxEventSize = 10 * 1024 * 1024;\n/**\n * Creates a channel that parses Server-Sent Events text chunks into `Event` values.\n *\n * **Details**\n *\n * SSE `retry` directives are emitted as `Retry` failures so callers can\n * reconnect with the requested delay.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decode = options => Channel.fromTransform((upstream, _scope) => Effect.sync(() => {\n  let buffer = [];\n  let retry;\n  const parser = makeParser(event => {\n    if (event._tag === \"Retry\") {\n      retry = event;\n    } else {\n      buffer.push(event);\n    }\n  }, options);\n  const pump = Effect.flatMap(upstream, arr => {\n    for (let i = 0; i < arr.length; i++) {\n      const error = parser.feed(arr[i]);\n      if (error !== undefined) {\n        return Effect.fail(error);\n      }\n    }\n    return Effect.void;\n  });\n  return Effect.suspend(function loop() {\n    if (Arr.isArrayNonEmpty(buffer)) {\n      const out = buffer;\n      buffer = [];\n      return Effect.succeed(out);\n    } else if (retry) {\n      return Effect.fail(retry);\n    }\n    return Effect.flatMap(pump, loop);\n  });\n}));\n/**\n * Creates an SSE decoder channel that decodes each parsed event with a schema.\n *\n * **Details**\n *\n * The schema receives the untagged event shape containing `id`, `event`, and\n * string `data`.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeSchema = (schema, options) => Channel.pipeTo(decode(options), ChannelSchema.decode(EventEncoded.pipe(Schema.decodeTo(schema)))());\n/**\n * Creates an SSE decoder channel that JSON-decodes each event `data` field with a schema.\n *\n * **Details**\n *\n * The output preserves the SSE `event` name and optional `id` while replacing\n * `data` with the decoded value.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport const decodeDataSchema = (schema, options) => {\n  const eventSchema = Schema.Struct({\n    ...EventEncoded.fields,\n    data: Schema.fromJsonString(schema)\n  });\n  return Channel.pipeTo(decode(options), Channel.map(ChannelSchema.decode(eventSchema)(), Arr.map(event => ({\n    ...event,\n    id: event.id\n  }))));\n};\n/**\n * Creates a stateful Server-Sent Events parser.\n *\n * **Details**\n *\n * Call `feed` with text chunks to parse `Event` and `Retry` values through the\n * callback, and call `reset` to clear any buffered event state. `feed` returns\n * an `SseError` if the pending event exceeds `maxEventSize`.\n *\n * @category decoding\n * @since 4.0.0\n */\nexport function makeParser(onParse, options) {\n  const maxEventSize = options?.maxEventSize ?? defaultMaxEventSize;\n  // Processing state\n  let isFirstChunk;\n  let buffer;\n  let startingPosition;\n  let startingFieldLength;\n  // Event state\n  let eventId;\n  let lastEventId;\n  let eventName;\n  let data;\n  reset();\n  return {\n    feed,\n    reset\n  };\n  function reset() {\n    isFirstChunk = true;\n    buffer = \"\";\n    startingPosition = 0;\n    startingFieldLength = -1;\n    eventId = undefined;\n    eventName = undefined;\n    data = \"\";\n  }\n  function feed(chunk) {\n    buffer = buffer ? buffer + chunk : chunk;\n    // Strip any UTF8 byte order mark (BOM) at the start of the stream.\n    // Note that we do not strip any non - UTF8 BOM, as eventsource streams are\n    // always decoded as UTF8 as per the specification.\n    if (isFirstChunk && hasBom(buffer)) {\n      buffer = buffer.slice(BOM.length);\n    }\n    isFirstChunk = false;\n    // Set up chunk-specific processing state\n    const length = buffer.length;\n    let position = 0;\n    let discardTrailingNewline = false;\n    // Read the current buffer byte by byte\n    while (position < length) {\n      // EventSource allows for carriage return + line feed, which means we\n      // need to ignore a linefeed character if the previous character was a\n      // carriage return\n      // @todo refactor to reduce nesting, consider checking previous byte?\n      // @todo but consider multiple chunks etc\n      if (discardTrailingNewline) {\n        if (buffer[position] === \"\\n\") {\n          ++position;\n        }\n        discardTrailingNewline = false;\n      }\n      let lineLength = -1;\n      let fieldLength = startingFieldLength;\n      let character;\n      for (let index = startingPosition; lineLength < 0 && index < length; ++index) {\n        character = buffer[index];\n        if (character === \":\" && fieldLength < 0) {\n          fieldLength = index - position;\n        } else if (character === \"\\r\") {\n          discardTrailingNewline = true;\n          lineLength = index - position;\n        } else if (character === \"\\n\") {\n          lineLength = index - position;\n        }\n      }\n      if (lineLength < 0) {\n        startingPosition = length - position;\n        startingFieldLength = fieldLength;\n        break;\n      } else {\n        startingPosition = 0;\n        startingFieldLength = -1;\n      }\n      parseEventStreamLine(buffer, position, fieldLength, lineLength);\n      position += lineLength + 1;\n    }\n    if (position === length) {\n      // If we consumed the entire buffer to read the event, reset the buffer\n      buffer = \"\";\n    } else if (position > 0) {\n      // If there are bytes left to process, set the buffer to the unprocessed\n      // portion of the buffer only\n      buffer = buffer.slice(position);\n    }\n    if (buffer.length + data.length > maxEventSize) {\n      const error = new SseError({\n        reason: new EventTooLarge({\n          maxEventSize\n        })\n      });\n      reset();\n      return error;\n    }\n  }\n  function parseEventStreamLine(lineBuffer, index, fieldLength, lineLength) {\n    if (lineLength === 0) {\n      // We reached the last line of this event\n      if (data.length > 0) {\n        onParse({\n          _tag: \"Event\",\n          id: eventId,\n          event: eventName ?? \"message\",\n          data: data.slice(0, -1) // remove trailing newline\n        });\n        data = \"\";\n        eventId = undefined;\n      }\n      eventName = undefined;\n      return;\n    }\n    const noValue = fieldLength < 0;\n    const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength));\n    let step = 0;\n    if (noValue) {\n      step = lineLength;\n    } else if (lineBuffer[index + fieldLength + 1] === \" \") {\n      step = fieldLength + 2;\n    } else {\n      step = fieldLength + 1;\n    }\n    const position = index + step;\n    const valueLength = lineLength - step;\n    const value = lineBuffer.slice(position, position + valueLength).toString();\n    if (field === \"data\") {\n      data += value ? `${value}\\n` : \"\\n\";\n    } else if (field === \"event\") {\n      eventName = value;\n    } else if (field === \"id\" && !value.includes(\"\\u0000\")) {\n      eventId = value;\n      lastEventId = value;\n    } else if (field === \"retry\") {\n      const retry = parseInt(value, 10);\n      if (!Number.isNaN(retry)) {\n        onParse(new Retry({\n          duration: Duration.millis(retry),\n          lastEventId\n        }));\n      }\n    }\n  }\n}\nconst BOM = [239, 187, 191];\nfunction hasBom(buffer) {\n  return BOM.every((charCode, index) => buffer.charCodeAt(index) === charCode);\n}\n/**\n * Creates a channel that encodes `Event` values as Server-Sent Events text.\n *\n * **Details**\n *\n * If the upstream channel fails with `Retry`, the retry directive is written and\n * the encoder completes.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encode = () => Channel.fromTransform((upstream, _scope) => Effect.sync(() => {\n  let done = false;\n  const pull = upstream.pipe(Effect.map(Arr.map(encoder.write)), Effect.catchFilter(Retry.filter, retry => {\n    done = true;\n    return Effect.succeed(Arr.of(encoder.write(retry)));\n  }), Pull.catchDone(() => Cause.done()));\n  return Effect.suspend(() => done ? Cause.done() : pull);\n}));\n/**\n * Creates an SSE encoder channel for values accepted by a schema.\n *\n * **Details**\n *\n * Values are schema-encoded to the untagged SSE event shape, transformed to\n * `Event`, and then written as Server-Sent Events text.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encodeSchema = schema => ChannelSchema.encode(Event.pipe(Schema.decodeTo(schema, transformEvent)))().pipe(Channel.pipeTo(encode()));\n/**\n * Schema for the untagged Server-Sent Events payload shape containing an optional `id`, `event`, and string `data` fields.\n *\n * @category models\n * @since 4.0.0\n */\nexport const EventEncoded = /*#__PURE__*/Schema.Struct({\n  id: /*#__PURE__*/Schema.optional(Schema.String),\n  event: Schema.String,\n  data: Schema.String\n});\n/**\n * Schema for the tagged Server-Sent Events message model that adds `_tag: \"Event\"` to the event name, optional event ID, and string data payload.\n *\n * @category models\n * @since 4.0.0\n */\nexport const Event = /*#__PURE__*/Schema.Struct({\n  _tag: /*#__PURE__*/Schema.tag(\"Event\"),\n  id: /*#__PURE__*/Schema.UndefinedOr(Schema.String),\n  event: Schema.String,\n  data: Schema.String\n});\n/**\n * Schema for transforming untagged SSE event payloads into tagged `Event`\n * models.\n *\n * @category models\n * @since 4.0.0\n */\nexport const transformEvent = /*#__PURE__*/SchemaTransformation.transform({\n  decode: event => event,\n  encode: event => ({\n    _tag: \"Event\",\n    id: event.id,\n    event: event.event ?? \"message\",\n    data: event.data\n  })\n});\nconst RetryTypeId = \"~effect/encoding/Sse/Retry\";\n/**\n * Represents a Server-Sent Events retry directive.\n *\n * **Details**\n *\n * Decoders surface this value as a failure to request reconnection after\n * `duration`; encoders serialize an upstream `Retry` failure as a `retry:` line.\n *\n * @category models\n * @since 4.0.0\n */\nexport class Retry extends /*#__PURE__*/Data.TaggedClass(\"Retry\") {\n  /**\n   * Marks this value as an SSE retry directive for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [RetryTypeId] = RetryTypeId;\n  /**\n   * Returns `true` when the value is an SSE retry directive.\n   *\n   * @since 4.0.0\n   */\n  static is(u) {\n    return hasProperty(u, RetryTypeId);\n  }\n  /**\n   * Separates SSE retry directives from regular event values.\n   *\n   * @since 4.0.0\n   */\n  static filter(u) {\n    return Retry.is(u) ? Result.succeed(u) : Result.fail(u);\n  }\n}\n/**\n * Default Server-Sent Events encoder.\n *\n * **Details**\n *\n * It renders `Event` values as `id`, `event`, and `data` lines and renders\n * `Retry` values as `retry:` directives.\n *\n * @category encoding\n * @since 4.0.0\n */\nexport const encoder = {\n  write(event) {\n    switch (event._tag) {\n      case \"Event\":\n        {\n          let data = \"\";\n          if (event.id !== undefined) {\n            data += `id: ${event.id}\\n`;\n          }\n          if (event.event !== \"message\") {\n            data += `event: ${event.event}\\n`;\n          }\n          if (event.data !== \"\") {\n            data += `data: ${event.data.replace(/\\n/g, \"\\ndata: \")}\\n`;\n          }\n          return data + \"\\n\";\n        }\n      case \"Retry\":\n        {\n          return `retry: ${Duration.toMillis(event.duration)}\\n\\n`;\n        }\n    }\n  }\n};\n//# sourceMappingURL=Sse.js.map","/**\n * Builds HTTP clients from `HttpApi` declarations.\n *\n * The client methods are derived from the groups and endpoints in an `HttpApi`\n * and run through an `HttpClient`. They use the same schema-driven contract as\n * the server: request parts are encoded from endpoint schemas, client\n * middleware is applied, the HTTP request is executed, and declared success or\n * error responses are decoded. This module also includes helpers for building a\n * client for only one group, one endpoint, or only the encoded URL.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Cause from \"../../Cause.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { identity } from \"../../Function.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\nimport * as SchemaIssue from \"../../SchemaIssue.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as UndefinedOr from \"../../UndefinedOr.js\";\nimport * as Sse from \"../encoding/Sse.js\";\nimport * as HttpBody from \"../http/HttpBody.js\";\nimport * as HttpClient from \"../http/HttpClient.js\";\nimport * as HttpClientError from \"../http/HttpClientError.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as HttpClientResponse from \"../http/HttpClientResponse.js\";\nimport * as HttpMethod from \"../http/HttpMethod.js\";\nimport * as UrlParams from \"../http/UrlParams.js\";\nimport * as HttpApi from \"./HttpApi.js\";\nimport * as HttpApiEndpoint from \"./HttpApiEndpoint.js\";\nimport * as HttpApiSchema from \"./HttpApiSchema.js\";\nimport * as MediaType from \"./internal/mediaType.js\";\n/** @internal */\nexport const makeClient = (api, options) => Effect.gen(function* () {\n  const services = yield* Effect.context();\n  const httpClient = options.httpClient.pipe(options?.baseUrl === undefined ? identity : HttpClient.mapRequest(HttpClientRequest.prependUrl(options.baseUrl.toString())));\n  function executeMiddleware(group, endpoint, request, middlewareKeys, index) {\n    if (index === -1) {\n      return httpClient.execute(request);\n    }\n    const middleware = services.mapUnsafe.get(middlewareKeys[index]);\n    if (middleware === undefined) {\n      return executeMiddleware(group, endpoint, request, middlewareKeys, index - 1);\n    }\n    return middleware({\n      endpoint,\n      group,\n      request,\n      next(request) {\n        return executeMiddleware(group, endpoint, request, middlewareKeys, index - 1);\n      }\n    });\n  }\n  HttpApi.reflect(api, {\n    predicate: options?.predicate,\n    onGroup(onGroupOptions) {\n      options.onGroup?.(onGroupOptions);\n    },\n    onEndpoint(onEndpointOptions) {\n      const {\n        group,\n        endpoint,\n        errors,\n        successes\n      } = onEndpointOptions;\n      const makeUrl = compilePath(endpoint.path);\n      const decodeMap = {\n        orElse: statusOrElse\n      };\n      const decodeResponse = HttpClientResponse.matchStatus(decodeMap);\n      const errorAlternatives = new Map();\n      for (const [status, schemas] of errors.entries()) {\n        const grouped = groupSchemasByContentType(schemas);\n        for (const [contentType, schemas] of grouped.entries()) {\n          addResponseAlternative(errorAlternatives, status, contentType, schemasToResponse(schemas));\n        }\n      }\n      for (const [status, alternatives] of errorAlternatives.entries()) {\n        const decode = makeResponseDecoder(alternatives);\n        decodeMap[status] = response => Effect.flatMap(Effect.catchCause(decode(response), cause => Effect.failCause(Cause.combine(Cause.fail(new HttpClientError.HttpClientError({\n          reason: new HttpClientError.StatusCodeError({\n            request: response.request,\n            response\n          })\n        })), cause))), Effect.fail);\n      }\n      const successAlternatives = new Map();\n      for (const [status, schemas] of successes.entries()) {\n        const grouped = groupSchemasByContentType(schemas);\n        for (const [contentType, schemas] of grouped.entries()) {\n          addResponseAlternative(successAlternatives, status, contentType, schemasToResponse(schemas));\n        }\n      }\n      for (const streamSuccess of getStreamSuccessSchemas(endpoint)) {\n        addResponseAlternative(successAlternatives, HttpApiSchema.getStatusStream(streamSuccess), streamSuccess.contentType, streamToResponse(streamSuccess));\n      }\n      for (const [status, alternatives] of successAlternatives.entries()) {\n        decodeMap[status] = makeResponseDecoder(alternatives);\n      }\n      // encoders\n      const encodeParams = UndefinedOr.map(endpoint.params, Schema.encodeUnknownEffect);\n      const payloadSchemas = HttpApiEndpoint.getPayloadSchemas(endpoint);\n      const encodePayload = Arr.isArrayNonEmpty(payloadSchemas) ? HttpMethod.hasBody(endpoint.method) ? Schema.encodeUnknownEffect(getEncodePayloadSchema(payloadSchemas, endpoint.method)) : Schema.encodeUnknownEffect(Schema.Union(payloadSchemas)) : undefined;\n      const encodeHeaders = UndefinedOr.map(endpoint.headers, Schema.encodeUnknownEffect);\n      const encodeQuery = UndefinedOr.map(endpoint.query, Schema.encodeUnknownEffect);\n      const middlewareKeys = Array.from(onEndpointOptions.middleware, tag => `${tag.key}/Client`);\n      const endpointFn = Effect.fnUntraced(function* (request) {\n        let httpRequest = HttpClientRequest.make(endpoint.method)(endpoint.path);\n        if (request !== undefined) {\n          // params\n          if (encodeParams !== undefined) {\n            const params = yield* encodeParams(request.params);\n            httpRequest = HttpClientRequest.setUrl(httpRequest, makeUrl(params));\n          }\n          // payload\n          if (encodePayload !== undefined) {\n            if (HttpMethod.hasBody(endpoint.method)) {\n              if (request.payload instanceof FormData) {\n                httpRequest = HttpClientRequest.bodyFormData(httpRequest, request.payload);\n              } else {\n                const body = yield* encodePayload(request.payload);\n                httpRequest = HttpClientRequest.setBody(httpRequest, body);\n              }\n            } else {\n              const urlParams = yield* encodePayload(request.payload);\n              httpRequest = HttpClientRequest.appendUrlParams(httpRequest, urlParams);\n            }\n          }\n          // headers\n          if (encodeHeaders !== undefined) {\n            const headers = yield* encodeHeaders(request.headers);\n            httpRequest = HttpClientRequest.setHeaders(httpRequest, headers);\n          }\n          // query\n          if (encodeQuery !== undefined) {\n            const query = yield* encodeQuery(request.query);\n            httpRequest = HttpClientRequest.appendUrlParams(httpRequest, query);\n          }\n        }\n        const response = yield* executeMiddleware(group, endpoint, httpRequest, middlewareKeys, middlewareKeys.length - 1);\n        if (request?.responseMode === \"response-only\") {\n          return response;\n        }\n        const value = yield* options.transformResponse === undefined ? decodeResponse(response) : options.transformResponse(decodeResponse(response));\n        return request?.responseMode === \"decoded-and-response\" ? [value, response] : value;\n      });\n      options.onEndpoint({\n        ...onEndpointOptions,\n        endpointFn\n      });\n    }\n  });\n});\n/**\n * Constructs a type-safe client for an HTTP API using the `HttpClient` service,\n * endpoint schemas, middleware, and optional client or response transformations.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (api, options) => Effect.flatMap(HttpClient.HttpClient, httpClient => makeWith(api, {\n  ...options,\n  httpClient: options?.transformClient ? options.transformClient(httpClient) : httpClient\n}));\n/**\n * Constructs a type-safe client for an HTTP API from the supplied `HttpClient`,\n * using the API metadata to encode requests, execute middleware, and decode\n * responses.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWith = (api, options) => {\n  const client = {};\n  return makeClient(api, {\n    ...options,\n    onGroup({\n      group\n    }) {\n      if (group.topLevel) return;\n      InternalRecord.assignProperty(client, group.identifier, {});\n    },\n    onEndpoint({\n      endpoint,\n      endpointFn,\n      group\n    }) {\n      InternalRecord.assignProperty(group.topLevel ? client : client[group.identifier], endpoint.identifier, endpointFn);\n    }\n  }).pipe(Effect.as(client));\n};\n/**\n * Builds a typed client object for a single API group from the supplied\n * `HttpClient`, filtering the API to that group.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const group = (api, options) => {\n  const client = {};\n  return makeClient(api, {\n    ...options,\n    predicate: ({\n      group\n    }) => group.identifier === options.group,\n    onEndpoint({\n      endpoint,\n      endpointFn\n    }) {\n      InternalRecord.assignProperty(client, endpoint.identifier, endpointFn);\n    }\n  }).pipe(Effect.map(() => client));\n};\n/**\n * Builds the typed client method for one endpoint in one API group, using the\n * supplied `HttpClient` and endpoint metadata.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const endpoint = (api, options) => {\n  let client = undefined;\n  return makeClient(api, {\n    ...options,\n    httpClient: options.transformClient ? options.transformClient(options.httpClient) : options.httpClient,\n    predicate: ({\n      endpoint,\n      group\n    }) => group.identifier === options.group && endpoint.identifier === options.endpoint,\n    onEndpoint({\n      endpointFn\n    }) {\n      client = endpointFn;\n    }\n  }).pipe(Effect.map(() => client));\n};\n/**\n * Creates a type-safe URL builder that mirrors `HttpApiClient.make`.\n *\n * **Example** (Building typed URLs)\n *\n * ```ts import.meta.vitest\n * import { Schema } from \"effect\"\n * import { HttpApi, HttpApiClient, HttpApiEndpoint, HttpApiGroup } from \"effect/unstable/httpapi\"\n *\n * const Api = HttpApi.make(\"Api\").add(\n *   HttpApiGroup.make(\"users\").add(\n *     HttpApiEndpoint.get(\"getUser\", \"/users/:id\", {\n *       params: { id: Schema.String }\n *     })\n *   )\n * )\n *\n * const buildUrl = HttpApiClient.urlBuilder(Api, {\n *   baseUrl: \"https://api.example.com\"\n * })\n *\n * buildUrl.users.getUser({\n *   params: { id: \"123\" }\n * }) // => \"https://api.example.com/users/123\"\n * ```\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const urlBuilder = (api, options) => {\n  const builder = {};\n  HttpApi.reflect(api, {\n    onGroup({\n      group\n    }) {\n      if (group.topLevel) return;\n      InternalRecord.assignProperty(builder, group.identifier, {});\n    },\n    onEndpoint({\n      group,\n      endpoint\n    }) {\n      const makeUrl = compilePath(endpoint.path);\n      const encodeParams = endpoint.params === undefined ? undefined : Schema.encodeSync(endpoint.params);\n      const encodeQuery = endpoint.query === undefined ? undefined : Schema.encodeSync(endpoint.query);\n      const endpointBuilder = request => {\n        const params = request?.params;\n        const path = params === undefined ? endpoint.path : makeUrl(encodeParams === undefined ? params : encodeParams(params));\n        const queryInput = request?.query === undefined ? undefined : encodeQuery === undefined ? request.query : encodeQuery(request.query);\n        const query = queryInput === undefined ? \"\" : UrlParams.toString(UrlParams.fromInput(queryInput));\n        const url = query === \"\" ? path : `${path}?${query}`;\n        return options?.baseUrl === undefined ? url : new URL(url, options.baseUrl.toString()).toString();\n      };\n      InternalRecord.assignProperty(group.topLevel ? builder : builder[group.identifier], endpoint.identifier, endpointBuilder);\n    }\n  });\n  return builder;\n};\n// ----------------------------------------------------------------------------\nconst paramsRegExp = /(\\/?):(\\w+)(\\?)?/g;\nconst compilePath = path => {\n  if (!paramsRegExp.test(path)) {\n    return _ => path;\n  }\n  paramsRegExp.lastIndex = 0;\n  return params => {\n    paramsRegExp.lastIndex = 0;\n    return path.replace(paramsRegExp, (_, slash, key, optional) => {\n      const value = params[key];\n      if (value === undefined) {\n        if (optional !== undefined) {\n          return \"\";\n        }\n        throw new Error(`Missing path parameter: ${key}`);\n      }\n      return `${slash}${encodeURIComponent(value)}`;\n    });\n  };\n};\nfunction schemasToResponse(schemas) {\n  const codec = toCodecArrayBuffer(schemas);\n  const decode = Schema.decodeEffect(codec);\n  return response => Effect.flatMap(response.arrayBuffer, decode);\n}\nfunction addResponseAlternative(map, status, contentType, decode) {\n  const normalizedContentType = MediaType.normalize(contentType);\n  const alternatives = map.get(status);\n  if (alternatives === undefined) {\n    map.set(status, [{\n      contentType: normalizedContentType,\n      decode\n    }]);\n  } else {\n    alternatives.push({\n      contentType: normalizedContentType,\n      decode\n    });\n  }\n}\nfunction makeResponseDecoder(alternatives) {\n  const first = alternatives[0];\n  if (alternatives.length === 1 && first !== undefined) {\n    return first.decode;\n  }\n  return response => {\n    const contentType = MediaType.normalize(response.headers[\"content-type\"] ?? \"\");\n    const alternative = alternatives.find(alternative => alternative.contentType === contentType);\n    return alternative === undefined ? failUnsupportedContentType(response, contentType, alternatives) : alternative.decode(response);\n  };\n}\nfunction groupSchemasByContentType(schemas) {\n  const grouped = new Map();\n  for (const schema of schemas) {\n    const contentType = HttpApiSchema.isNoContent(schema.ast) ? \"\" : MediaType.normalize(HttpApiSchema.getResponseEncoding(schema.ast).contentType);\n    const existing = grouped.get(contentType);\n    if (existing === undefined) {\n      grouped.set(contentType, [schema]);\n    } else {\n      existing.push(schema);\n    }\n  }\n  return grouped;\n}\nfunction failUnsupportedContentType(response, contentType, alternatives) {\n  const expected = Array.from(new Set(alternatives.map(alternative => alternative.contentType))).join(\", \");\n  return Effect.fail(new HttpClientError.HttpClientError({\n    reason: new HttpClientError.DecodeError({\n      request: response.request,\n      response,\n      description: `Unsupported response content-type for status ${response.status}: ${contentType || \"<missing>\"}. Expected one of: ${expected}`\n    })\n  }));\n}\nconst reservedStreamFailureEvent = \"effect/httpapi/stream/failure\";\nfunction getStreamSuccessSchemas(endpoint) {\n  const schemas = [];\n  for (const schema of endpoint.success) {\n    if (HttpApiSchema.isStreamSchema(schema)) {\n      schemas.push(schema);\n    }\n  }\n  return schemas;\n}\nfunction streamToResponse(streamSchema) {\n  const sse = HttpApiSchema.isStreamUint8Array(streamSchema) ? undefined : {\n    declaration: streamSchema,\n    decoder: makeSseDecoder(streamSchema)\n  };\n  return response => Effect.map(Effect.context(), context => Stream.provideContext(sse === undefined ? response.stream : decodeSseStream(response.stream, sse.declaration, sse.decoder), context));\n}\nfunction makeSseDecoder(declaration) {\n  const Event = Schema.Union([Schema.Struct({\n    event: Schema.Literal(reservedStreamFailureEvent),\n    data: Schema.fromJsonString(Schema.toCodecJson(Schema.Cause(declaration.error, Schema.Defect())))\n  }), declaration.events]);\n  return Sse.decodeSchema(Event);\n}\nfunction decodeSseStream(stream, declaration, decoder) {\n  const events = Stream.transformPull(stream.pipe(Stream.decodeText, Stream.pipeThroughChannel(decoder)), pull => Effect.sync(() => {\n    let pendingFailureCause = undefined;\n    return Effect.suspend(() => {\n      if (pendingFailureCause !== undefined) {\n        return Effect.failCause(pendingFailureCause);\n      }\n      return Effect.flatMap(pull, events => {\n        for (let i = 0; i < events.length; i++) {\n          const event = events[i];\n          if (event.event === reservedStreamFailureEvent && Cause.isCause(event.data)) {\n            if (i === 0) {\n              return Effect.failCause(event.data);\n            }\n            pendingFailureCause = event.data;\n            events = events.slice(0, i);\n            break;\n          }\n        }\n        return Effect.succeed(events);\n      });\n    });\n  }));\n  if (declaration.sseMode === \"data\") {\n    return Stream.map(events, event => event.data);\n  }\n  return events;\n}\nconst ArrayBuffer = /*#__PURE__*/Schema.instanceOf(globalThis.ArrayBuffer, {\n  expected: \"ArrayBuffer\"\n});\n// _tag: Uint8Array\nconst Uint8ArrayFromArrayBuffer = /*#__PURE__*/ArrayBuffer.pipe(/*#__PURE__*/Schema.decodeTo(Schema.Uint8Array, /*#__PURE__*/SchemaTransformation.transform({\n  decode(fromA) {\n    return new Uint8Array(fromA);\n  },\n  encode(arr) {\n    return arr.byteLength === arr.buffer.byteLength ? arr.buffer : arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);\n  }\n})));\n// _tag: Text\nconst StringFromArrayBuffer = /*#__PURE__*/ArrayBuffer.pipe(/*#__PURE__*/Schema.decodeTo(Schema.String, /*#__PURE__*/SchemaTransformation.transform({\n  decode(fromA) {\n    return new TextDecoder().decode(fromA);\n  },\n  encode(toI) {\n    const arr = new TextEncoder().encode(toI);\n    return arr.byteLength === arr.buffer.byteLength ? arr.buffer : arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);\n  }\n})));\n// _tag: Json\nconst UnknownFromArrayBuffer = /*#__PURE__*/StringFromArrayBuffer.pipe(/*#__PURE__*/Schema.decodeTo(/*#__PURE__*/Schema.Union([\n/*#__PURE__*/\n// Handle No Content\nSchema.Literal(\"\").pipe(/*#__PURE__*/Schema.decodeTo(Schema.Undefined, /*#__PURE__*/SchemaTransformation.transform({\n  decode: () => undefined,\n  encode: () => \"\"\n}))), Schema.UnknownFromJsonString])));\nfunction toCodecArrayBuffer(schemas) {\n  return Schema.Union(schemas.map(onSchema));\n  function onSchema(schema) {\n    const encoding = HttpApiSchema.getResponseEncoding(schema.ast);\n    switch (encoding._tag) {\n      case \"Json\":\n        {\n          // handle json codecs that transform void schemas to null\n          const encodedIsNull = SchemaAST.isNull(SchemaAST.toEncoded(schema.ast));\n          return UnknownFromArrayBuffer.pipe(Schema.decodeTo(schema, encodedIsNull ? SchemaTransformation.transform({\n            decode: a => a === undefined ? null : a,\n            encode: a => a === null ? undefined : a\n          }) : undefined));\n        }\n      case \"FormUrlEncoded\":\n        return StringFromArrayBuffer.pipe(Schema.decodeTo(UrlParams.schemaRecord), Schema.decodeTo(schema));\n      case \"Uint8Array\":\n        return Uint8ArrayFromArrayBuffer.pipe(Schema.decodeTo(schema));\n      case \"Text\":\n        return StringFromArrayBuffer.pipe(Schema.decodeTo(schema));\n    }\n  }\n}\nconst statusOrElse = response => Effect.fail(new HttpClientError.HttpClientError({\n  reason: new HttpClientError.DecodeError({\n    request: response.request,\n    response\n  })\n}));\nconst $HttpBody = /*#__PURE__*/Schema.declare(HttpBody.isHttpBody);\nfunction getEncodePayloadSchema(schemas, method) {\n  return Schema.Union(schemas.map(s => getEncodePayloadSchemaFromBody(s, method)));\n}\nconst bodyFromPayloadCache = /*#__PURE__*/new WeakMap();\nfunction getEncodePayloadSchemaFromBody(schema, method) {\n  const ast = schema.ast;\n  const cached = bodyFromPayloadCache.get(ast);\n  if (cached !== undefined) {\n    return cached;\n  }\n  const encoding = HttpApiSchema.getPayloadEncoding(ast, method);\n  const out = $HttpBody.pipe(Schema.decodeTo(schema, SchemaTransformation.transformOrFail({\n    decode() {\n      return Effect.fail(new SchemaIssue.Forbidden({\n        message: \"Encode only schema\"\n      }));\n    },\n    encode(t) {\n      switch (encoding._tag) {\n        case \"Multipart\":\n          return Effect.fail(new SchemaIssue.Forbidden({\n            message: \"Payload must be a FormData\"\n          }));\n        case \"Json\":\n          {\n            try {\n              const body = JSON.stringify(t);\n              return Effect.succeed(HttpBody.text(body, encoding.contentType));\n            } catch {\n              return Effect.fail(new SchemaIssue.InvalidValue({\n                message: \"Expected a JSON-serializable request body\"\n              }));\n            }\n          }\n        case \"Text\":\n          {\n            if (typeof t !== \"string\") {\n              return Effect.fail(new SchemaIssue.InvalidValue({\n                message: \"Expected a string\"\n              }));\n            }\n            return Effect.succeed(HttpBody.text(t, encoding.contentType));\n          }\n        case \"FormUrlEncoded\":\n          {\n            if (!Predicate.isObject(t)) {\n              return Effect.fail(new SchemaIssue.InvalidValue({\n                message: \"Expected a record\"\n              }));\n            }\n            return Effect.succeed(HttpBody.urlParams(UrlParams.fromInput(t), encoding.contentType));\n          }\n        case \"Uint8Array\":\n          {\n            if (!(t instanceof Uint8Array)) {\n              return Effect.fail(new SchemaIssue.InvalidValue({\n                message: \"Expected a Uint8Array\"\n              }));\n            }\n            return Effect.succeed(HttpBody.uint8Array(t, encoding.contentType));\n          }\n      }\n    }\n  })));\n  bodyFromPayloadCache.set(ast, out);\n  return out;\n}\n//# sourceMappingURL=HttpApiClient.js.map","/**\n * OrchestrationEngineService - Service interface for orchestration command handling.\n *\n * Owns command validation/dispatch and in-memory read-model updates backed by\n * `OrchestrationEventStore` persistence. It does not own provider process\n * management or transport concerns (e.g. websocket request parsing).\n *\n * Uses Effect `Context.Service` for dependency injection. Command dispatch,\n * replay, and unknown-input decoding all return typed domain errors.\n *\n * @module OrchestrationEngineService\n */\nimport type { OrchestrationCommand, OrchestrationEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { OrchestrationDispatchError } from \"../Errors.ts\";\nimport type { OrchestrationEventStoreError } from \"../../persistence/Errors.ts\";\n\n/**\n * OrchestrationEngineShape - Service API for orchestration command and event flow.\n */\nexport interface OrchestrationEngineShape {\n  /**\n   * Replay persisted orchestration events from an exclusive sequence cursor.\n   *\n   * @param fromSequenceExclusive - Sequence cursor (exclusive).\n   * @param limit - Maximum number of events to read. Defaults to the event\n   *   store's page-bounded default; pass a higher value when the caller must\n   *   read every event after the cursor (e.g. per-thread catch-up that filters\n   *   a small subset out of a potentially larger global range).\n   * @returns Stream containing ordered events.\n   */\n  readonly readEvents: (\n    fromSequenceExclusive: number,\n    limit?: number,\n  ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;\n\n  /**\n   * Dispatch a validated orchestration command.\n   *\n   * @param command - Valid orchestration command.\n   * @returns Effect containing the sequence of the persisted event.\n   *\n   * Dispatch is serialized through an internal queue and deduplicated via\n   * command receipts.\n   */\n  readonly dispatch: (\n    command: OrchestrationCommand,\n  ) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;\n\n  /**\n   * Stream persisted domain events in dispatch order.\n   *\n   * This is a hot runtime stream (new events only), not a historical replay.\n   */\n  readonly streamDomainEvents: Stream.Stream<OrchestrationEvent>;\n\n  /**\n   * The latest sequence reflected in the engine's authoritative command read\n   * model (0 if none). Used to gauge how far behind a resuming client is before\n   * choosing between an incremental replay and a fresh projected snapshot.\n   */\n  readonly latestSequence: Effect.Effect<number, never, never>;\n}\n\n/**\n * OrchestrationEngineService - Service tag for orchestration engine access.\n *\n * @example\n * ```ts\n * const program = Effect.gen(function* () {\n *   const engine = yield* OrchestrationEngineService\n *   return yield* engine.dispatch(command)\n * })\n * ```\n */\nexport class OrchestrationEngineService extends Context.Service<\n  OrchestrationEngineService,\n  OrchestrationEngineShape\n>()(\"t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService\") {}\n","/**\n * ProjectionSnapshotQuery - Read-model snapshot query service interface.\n *\n * Exposes the current orchestration projection snapshot for read-only API\n * access.\n *\n * @module ProjectionSnapshotQuery\n */\nimport type {\n  CheckpointRef,\n  OrchestrationCheckpointSummary,\n  OrchestrationProject,\n  OrchestrationProjectShell,\n  OrchestrationReadModel,\n  OrchestrationSearchThreadsInput,\n  OrchestrationSearchThreadsResult,\n  OrchestrationShellSnapshot,\n  OrchestrationThread,\n  OrchestrationThreadDetailSnapshot,\n  OrchestrationThreadShell,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Option from \"effect/Option\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../../persistence/Errors.ts\";\n\nexport interface ProjectionSnapshotCounts {\n  readonly projectCount: number;\n  readonly threadCount: number;\n}\n\nexport interface ProjectionSnapshotSequence {\n  readonly snapshotSequence: number;\n}\n\nexport interface ProjectionThreadCheckpointContext {\n  readonly threadId: ThreadId;\n  readonly projectId: ProjectId;\n  readonly workspaceRoot: string;\n  readonly worktreePath: string | null;\n  readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;\n}\n\nexport interface ProjectionFullThreadDiffContext {\n  readonly threadId: ThreadId;\n  readonly projectId: ProjectId;\n  readonly workspaceRoot: string;\n  readonly worktreePath: string | null;\n  readonly latestCheckpointTurnCount: number;\n  readonly toCheckpointRef: CheckpointRef | null;\n}\n\n/**\n * ProjectionSnapshotQueryShape - Service API for read-model snapshots.\n */\nexport interface ProjectionSnapshotQueryShape {\n  /**\n   * Read the lightweight command snapshot used to bootstrap the in-memory\n   * orchestration engine without hydrating message/activity/checkpoint bodies.\n   */\n  readonly getCommandReadModel: () => Effect.Effect<\n    OrchestrationReadModel,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Read the latest orchestration projection snapshot.\n   *\n   * Rehydrates from projection tables and derives snapshot sequence from\n   * projector cursor state.\n   */\n  readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;\n\n  /**\n   * Read the latest orchestration shell snapshot.\n   *\n   * Returns only projects and thread shell summaries so clients can bootstrap\n   * lightweight navigation state without hydrating every thread body.\n   */\n  readonly getShellSnapshot: () => Effect.Effect<\n    OrchestrationShellSnapshot,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Read archived thread shell summaries for the archive page.\n   *\n   * This query is separate from the main shell snapshot so archived threads\n   * are never bootstrapped into normal navigation state.\n   */\n  readonly getArchivedShellSnapshot: () => Effect.Effect<\n    OrchestrationShellSnapshot,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Search active thread navigation metadata, user messages, and canonical\n   * assistant outputs without hydrating thread detail snapshots.\n   */\n  readonly searchThreads: (\n    input: OrchestrationSearchThreadsInput,\n  ) => Effect.Effect<OrchestrationSearchThreadsResult, ProjectionRepositoryError>;\n\n  /**\n   * Read the latest projection snapshot sequence without hydrating read-model\n   * entities.\n   */\n  readonly getSnapshotSequence: () => Effect.Effect<\n    ProjectionSnapshotSequence,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Read aggregate projection counts without hydrating the full read model.\n   */\n  readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;\n\n  /**\n   * Read the active project for an exact workspace root match.\n   */\n  readonly getActiveProjectByWorkspaceRoot: (\n    workspaceRoot: string,\n  ) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active project shell row by id.\n   */\n  readonly getProjectShellById: (\n    projectId: ProjectId,\n  ) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;\n\n  /**\n   * Read the earliest active thread for a project.\n   */\n  readonly getFirstActiveThreadIdByProjectId: (\n    projectId: ProjectId,\n  ) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;\n\n  /**\n   * Read the checkpoint context needed to resolve a single thread diff.\n   */\n  readonly getThreadCheckpointContext: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;\n\n  /**\n   * Read only the narrow context needed to compute a full-thread diff from\n   * checkpoint 0 to a specific turn count.\n   */\n  readonly getFullThreadDiffContext: (\n    threadId: ThreadId,\n    toTurnCount: number,\n  ) => Effect.Effect<Option.Option<ProjectionFullThreadDiffContext>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active thread shell row by id.\n   */\n  readonly getThreadShellById: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active thread detail snapshot by id.\n   */\n  readonly getThreadDetailById: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active thread detail together with the projection snapshot\n   * sequence in one consistent transaction, so the returned `snapshotSequence`\n   * exactly matches the state reflected in `thread` (no interleaving projector\n   * update between the two reads).\n   */\n  readonly getThreadDetailSnapshot: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionSnapshotQuery - Service tag for projection snapshot queries.\n */\nexport class ProjectionSnapshotQuery extends Context.Service<\n  ProjectionSnapshotQuery,\n  ProjectionSnapshotQueryShape\n>()(\"t3/orchestration/Services/ProjectionSnapshotQuery\") {}\n","/**\n * OrchestrationCommandReceiptRepository - Repository interface for command receipts.\n *\n * Owns persistence operations for deduplication and status tracking of\n * orchestration command handling.\n *\n * @module OrchestrationCommandReceiptRepository\n */\nimport {\n  CommandId,\n  IsoDateTime,\n  NonNegativeInt,\n  OrchestrationAggregateKind,\n  OrchestrationCommandReceiptStatus,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { OrchestrationCommandReceiptRepositoryError } from \"../Errors.ts\";\n\nexport const OrchestrationCommandReceipt = Schema.Struct({\n  commandId: CommandId,\n  aggregateKind: OrchestrationAggregateKind,\n  aggregateId: Schema.Union([ProjectId, ThreadId]),\n  acceptedAt: IsoDateTime,\n  resultSequence: NonNegativeInt,\n  status: OrchestrationCommandReceiptStatus,\n  error: Schema.NullOr(Schema.String),\n});\nexport type OrchestrationCommandReceipt = typeof OrchestrationCommandReceipt.Type;\n\nexport const GetByCommandIdInput = Schema.Struct({\n  commandId: CommandId,\n});\nexport type GetByCommandIdInput = typeof GetByCommandIdInput.Type;\n\n/**\n * OrchestrationCommandReceiptRepositoryShape - Service API for command receipts.\n */\nexport interface OrchestrationCommandReceiptRepositoryShape {\n  /**\n   * Insert or replace a command receipt row.\n   *\n   * Upserts by `commandId` for idempotent command-result tracking.\n   */\n  readonly upsert: (\n    receipt: OrchestrationCommandReceipt,\n  ) => Effect.Effect<void, OrchestrationCommandReceiptRepositoryError>;\n\n  /**\n   * Read a command receipt by command id.\n   */\n  readonly getByCommandId: (\n    input: GetByCommandIdInput,\n  ) => Effect.Effect<\n    Option.Option<OrchestrationCommandReceipt>,\n    OrchestrationCommandReceiptRepositoryError\n  >;\n}\n\n/**\n * OrchestrationCommandReceiptRepository - Service tag for command receipt persistence.\n */\nexport class OrchestrationCommandReceiptRepository extends Context.Service<\n  OrchestrationCommandReceiptRepository,\n  OrchestrationCommandReceiptRepositoryShape\n>()(\"t3/persistence/Services/OrchestrationCommandReceipts/OrchestrationCommandReceiptRepository\") {}\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  GetByCommandIdInput,\n  OrchestrationCommandReceipt,\n  OrchestrationCommandReceiptRepository,\n  type OrchestrationCommandReceiptRepositoryShape,\n} from \"../Services/OrchestrationCommandReceipts.ts\";\n\nconst makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertReceiptRow = SqlSchema.void({\n    Request: OrchestrationCommandReceipt,\n    execute: (receipt) =>\n      sql`\n        INSERT INTO orchestration_command_receipts (\n          command_id,\n          aggregate_kind,\n          aggregate_id,\n          accepted_at,\n          result_sequence,\n          status,\n          error\n        )\n        VALUES (\n          ${receipt.commandId},\n          ${receipt.aggregateKind},\n          ${receipt.aggregateId},\n          ${receipt.acceptedAt},\n          ${receipt.resultSequence},\n          ${receipt.status},\n          ${receipt.error}\n        )\n        ON CONFLICT (command_id)\n        DO UPDATE SET\n          aggregate_kind = excluded.aggregate_kind,\n          aggregate_id = excluded.aggregate_id,\n          accepted_at = excluded.accepted_at,\n          result_sequence = excluded.result_sequence,\n          status = excluded.status,\n          error = excluded.error\n      `,\n  });\n\n  const findReceiptByCommandId = SqlSchema.findOneOption({\n    Request: GetByCommandIdInput,\n    Result: OrchestrationCommandReceipt,\n    execute: ({ commandId }) =>\n      sql`\n        SELECT\n          command_id AS \"commandId\",\n          aggregate_kind AS \"aggregateKind\",\n          aggregate_id AS \"aggregateId\",\n          accepted_at AS \"acceptedAt\",\n          result_sequence AS \"resultSequence\",\n          status,\n          error\n        FROM orchestration_command_receipts\n        WHERE command_id = ${commandId}\n      `,\n  });\n\n  const upsert: OrchestrationCommandReceiptRepositoryShape[\"upsert\"] = (receipt) =>\n    upsertReceiptRow(receipt).pipe(\n      Effect.mapError(toPersistenceSqlError(\"OrchestrationCommandReceiptRepository.upsert:query\")),\n    );\n\n  const getByCommandId: OrchestrationCommandReceiptRepositoryShape[\"getByCommandId\"] = (input) =>\n    findReceiptByCommandId(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"OrchestrationCommandReceiptRepository.getByCommandId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    getByCommandId,\n  } satisfies OrchestrationCommandReceiptRepositoryShape;\n});\n\nexport const OrchestrationCommandReceiptRepositoryLive = Layer.effect(\n  OrchestrationCommandReceiptRepository,\n  makeOrchestrationCommandReceiptRepository,\n);\n","/**\n * OrchestrationEventStore - Event store interface for orchestration events.\n *\n * Owns durable append/replay access to the orchestration event stream. It does\n * not reduce events into read models or apply command validation rules.\n *\n * Uses Effect `Context.Service` for dependency injection and exposes typed\n * persistence/decode errors for event append and replay operations.\n *\n * @module OrchestrationEventStore\n */\nimport { OrchestrationEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { OrchestrationEventStoreError } from \"../Errors.ts\";\n\n/**\n * OrchestrationEventStoreShape - Service API for orchestration event persistence.\n */\nexport interface OrchestrationEventStoreShape {\n  /**\n   * Persist a new orchestration event.\n   *\n   * @param event - Event payload without sequence (assigned by storage).\n   * @returns Effect containing the stored event with assigned sequence.\n   *\n   * Actor kind is inferred from command/metadata before persistence.\n   */\n  readonly append: (\n    event: Omit<OrchestrationEvent, \"sequence\">,\n  ) => Effect.Effect<OrchestrationEvent, OrchestrationEventStoreError>;\n\n  /**\n   * Replay events after the provided sequence.\n   *\n   * @param sequenceExclusive - Sequence cursor (exclusive).\n   * @param limit - Maximum number of events to emit.\n   * @returns Stream containing ordered events.\n   *\n   * Reads in fixed-size pages and normalizes non-integer/negative limits.\n   */\n  readonly readFromSequence: (\n    sequenceExclusive: number,\n    limit?: number,\n  ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;\n\n  /**\n   * Read all events from the beginning of the stream.\n   *\n   * @returns Stream containing all stored events.\n   */\n  readonly readAll: () => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;\n}\n\n/**\n * OrchestrationEventStore - Service tag for orchestration event persistence.\n *\n * @example\n * ```ts\n * const program = Effect.gen(function* () {\n *   const events = yield* OrchestrationEventStore\n *   return yield* Stream.runCollect(events.readAll())\n * })\n * ```\n */\nexport class OrchestrationEventStore extends Context.Service<\n  OrchestrationEventStore,\n  OrchestrationEventStoreShape\n>()(\"t3/persistence/Services/OrchestrationEventStore\") {}\n","import {\n  CommandId,\n  EventId,\n  IsoDateTime,\n  NonNegativeInt,\n  OrchestrationActorKind,\n  OrchestrationAggregateKind,\n  OrchestrationEvent,\n  OrchestrationEventMetadata,\n  OrchestrationEventType,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n  toPersistenceDecodeError,\n  toPersistenceSqlError,\n  type OrchestrationEventStoreError,\n} from \"../Errors.ts\";\nimport {\n  OrchestrationEventStore,\n  type OrchestrationEventStoreShape,\n} from \"../Services/OrchestrationEventStore.ts\";\n\nconst decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent);\nconst UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);\nconst EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata);\n\nconst AppendEventRequestSchema = Schema.Struct({\n  eventId: EventId,\n  aggregateKind: OrchestrationAggregateKind,\n  streamId: Schema.Union([ProjectId, ThreadId]),\n  type: OrchestrationEventType,\n  causationEventId: Schema.NullOr(EventId),\n  correlationId: Schema.NullOr(CommandId),\n  actorKind: OrchestrationActorKind,\n  occurredAt: IsoDateTime,\n  commandId: Schema.NullOr(CommandId),\n  payloadJson: UnknownFromJsonString,\n  metadataJson: EventMetadataFromJsonString,\n});\n\nconst OrchestrationEventPersistedRowSchema = Schema.Struct({\n  sequence: NonNegativeInt,\n  eventId: EventId,\n  type: OrchestrationEventType,\n  aggregateKind: OrchestrationAggregateKind,\n  aggregateId: Schema.Union([ProjectId, ThreadId]),\n  occurredAt: IsoDateTime,\n  commandId: Schema.NullOr(CommandId),\n  causationEventId: Schema.NullOr(EventId),\n  correlationId: Schema.NullOr(CommandId),\n  payload: UnknownFromJsonString,\n  metadata: EventMetadataFromJsonString,\n});\n\nconst ReadFromSequenceRequestSchema = Schema.Struct({\n  sequenceExclusive: NonNegativeInt,\n  limit: Schema.Number,\n});\nconst DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;\nconst READ_PAGE_SIZE = 500;\n\nfunction inferActorKind(\n  event: Omit<OrchestrationEvent, \"sequence\">,\n): Schema.Schema.Type<typeof OrchestrationActorKind> {\n  if (event.commandId !== null && event.commandId.startsWith(\"provider:\")) {\n    return \"provider\";\n  }\n  if (event.commandId !== null && event.commandId.startsWith(\"server:\")) {\n    return \"server\";\n  }\n  if (\n    event.metadata.providerTurnId !== undefined ||\n    event.metadata.providerItemId !== undefined ||\n    event.metadata.adapterKey !== undefined\n  ) {\n    return \"provider\";\n  }\n  if (event.commandId === null) {\n    return \"server\";\n  }\n  return \"client\";\n}\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown): OrchestrationEventStoreError =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeEventStore = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const appendEventRow = SqlSchema.findOne({\n    Request: AppendEventRequestSchema,\n    Result: OrchestrationEventPersistedRowSchema,\n    execute: (request) =>\n      sql`\n        INSERT INTO orchestration_events (\n          event_id,\n          aggregate_kind,\n          stream_id,\n          stream_version,\n          event_type,\n          occurred_at,\n          command_id,\n          causation_event_id,\n          correlation_id,\n          actor_kind,\n          payload_json,\n          metadata_json\n        )\n        VALUES (\n          ${request.eventId},\n          ${request.aggregateKind},\n          ${request.streamId},\n          COALESCE(\n            (\n              SELECT stream_version + 1\n              FROM orchestration_events\n              WHERE aggregate_kind = ${request.aggregateKind}\n                AND stream_id = ${request.streamId}\n              ORDER BY stream_version DESC\n              LIMIT 1\n            ),\n            0\n          ),\n          ${request.type},\n          ${request.occurredAt},\n          ${request.commandId},\n          ${request.causationEventId},\n          ${request.correlationId},\n          ${request.actorKind},\n          ${request.payloadJson},\n          ${request.metadataJson}\n        )\n        RETURNING\n          sequence,\n          event_id AS \"eventId\",\n          event_type AS \"type\",\n          aggregate_kind AS \"aggregateKind\",\n          stream_id AS \"aggregateId\",\n          occurred_at AS \"occurredAt\",\n          command_id AS \"commandId\",\n          causation_event_id AS \"causationEventId\",\n          correlation_id AS \"correlationId\",\n          payload_json AS \"payload\",\n          metadata_json AS \"metadata\"\n      `,\n  });\n\n  const readEventRowsFromSequence = SqlSchema.findAll({\n    Request: ReadFromSequenceRequestSchema,\n    Result: OrchestrationEventPersistedRowSchema,\n    execute: (request) =>\n      sql`\n        SELECT\n          sequence,\n          event_id AS \"eventId\",\n          event_type AS \"type\",\n          aggregate_kind AS \"aggregateKind\",\n          stream_id AS \"aggregateId\",\n          occurred_at AS \"occurredAt\",\n          command_id AS \"commandId\",\n          causation_event_id AS \"causationEventId\",\n          correlation_id AS \"correlationId\",\n          payload_json AS \"payload\",\n          metadata_json AS \"metadata\"\n        FROM orchestration_events\n        WHERE sequence > ${request.sequenceExclusive}\n        ORDER BY sequence ASC\n        LIMIT ${request.limit}\n      `,\n  });\n\n  const append: OrchestrationEventStoreShape[\"append\"] = (event) =>\n    appendEventRow({\n      eventId: event.eventId,\n      aggregateKind: event.aggregateKind,\n      streamId: event.aggregateId,\n      type: event.type,\n      causationEventId: event.causationEventId,\n      correlationId: event.correlationId,\n      actorKind: inferActorKind(event),\n      occurredAt: event.occurredAt,\n      commandId: event.commandId,\n      payloadJson: event.payload,\n      metadataJson: event.metadata,\n    }).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"OrchestrationEventStore.append:insert\",\n          \"OrchestrationEventStore.append:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((row) =>\n        decodeEvent(row).pipe(\n          Effect.mapError(toPersistenceDecodeError(\"OrchestrationEventStore.append:rowToEvent\")),\n        ),\n      ),\n    );\n\n  const readFromSequence: OrchestrationEventStoreShape[\"readFromSequence\"] = (\n    sequenceExclusive,\n    limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,\n  ) => {\n    const normalizedLimit = Math.max(0, Math.floor(limit));\n    if (normalizedLimit === 0) {\n      return Stream.empty;\n    }\n    const readPage = (\n      cursor: number,\n      remaining: number,\n    ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>\n      Stream.fromEffect(\n        readEventRowsFromSequence({\n          sequenceExclusive: cursor,\n          limit: Math.min(remaining, READ_PAGE_SIZE),\n        }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"OrchestrationEventStore.readFromSequence:query\",\n              \"OrchestrationEventStore.readFromSequence:decodeRows\",\n            ),\n          ),\n          Effect.flatMap((rows) =>\n            Effect.forEach(rows, (row) =>\n              decodeEvent(row).pipe(\n                Effect.mapError(\n                  toPersistenceDecodeError(\"OrchestrationEventStore.readFromSequence:rowToEvent\"),\n                ),\n              ),\n            ),\n          ),\n        ),\n      ).pipe(\n        Stream.flatMap((events) => {\n          if (events.length === 0) {\n            return Stream.empty;\n          }\n          const nextRemaining = remaining - events.length;\n          if (nextRemaining <= 0) {\n            return Stream.fromIterable(events);\n          }\n          return Stream.concat(\n            Stream.fromIterable(events),\n            readPage(events[events.length - 1]!.sequence, nextRemaining),\n          );\n        }),\n      );\n\n    return readPage(sequenceExclusive, normalizedLimit);\n  };\n\n  return {\n    append,\n    readFromSequence,\n    readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),\n  } satisfies OrchestrationEventStoreShape;\n});\n\nexport const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);\n","import * as Cause from \"effect/Cause\";\nimport * as Exit from \"effect/Exit\";\n\nexport type MetricAttributeValue = string;\nexport type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;\nexport type ObservabilityOutcome = \"success\" | \"failure\" | \"interrupt\";\n\nexport function compactMetricAttributes(\n  attributes: Readonly<Record<string, unknown>>,\n): MetricAttributes {\n  return Object.fromEntries(\n    Object.entries(attributes).flatMap(([key, value]) => {\n      if (value === undefined || value === null) {\n        return [];\n      }\n      if (typeof value === \"string\") {\n        return [[key, value]];\n      }\n      if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n        return [[key, String(value)]];\n      }\n      return [];\n    }),\n  );\n}\n\nexport function outcomeFromExit(exit: Exit.Exit<unknown, unknown>): ObservabilityOutcome {\n  if (Exit.isSuccess(exit)) {\n    return \"success\";\n  }\n  return Cause.hasInterruptsOnly(exit.cause) ? \"interrupt\" : \"failure\";\n}\n\nexport function normalizeModelMetricLabel(model: string | null | undefined): string | undefined {\n  const normalized = model?.trim().toLowerCase();\n  if (!normalized) {\n    return undefined;\n  }\n  if (normalized.includes(\"gpt\")) {\n    return \"gpt\";\n  }\n  if (normalized.includes(\"claude\")) {\n    return \"claude\";\n  }\n  if (normalized.includes(\"gemini\")) {\n    return \"gemini\";\n  }\n  return \"other\";\n}\n","import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Metric from \"effect/Metric\";\nimport { dual } from \"effect/Function\";\n\nimport {\n  compactMetricAttributes,\n  normalizeModelMetricLabel,\n  outcomeFromExit,\n} from \"./Attributes.ts\";\n\nexport const rpcRequestsTotal = Metric.counter(\"t3_rpc_requests_total\", {\n  description: \"Total RPC requests handled by the websocket RPC server.\",\n});\n\nexport const rpcRequestDuration = Metric.timer(\"t3_rpc_request_duration\", {\n  description: \"RPC request handling duration.\",\n});\n\nexport const orchestrationCommandsTotal = Metric.counter(\"t3_orchestration_commands_total\", {\n  description: \"Total orchestration commands dispatched.\",\n});\n\nexport const orchestrationCommandDuration = Metric.timer(\"t3_orchestration_command_duration\", {\n  description: \"Orchestration command dispatch duration.\",\n});\n\nexport const orchestrationCommandAckDuration = Metric.timer(\n  \"t3_orchestration_command_ack_duration\",\n  {\n    description:\n      \"Time from orchestration command dispatch to the first committed domain event emitted for that command.\",\n  },\n);\n\nexport const orchestrationEventsProcessedTotal = Metric.counter(\n  \"t3_orchestration_events_processed_total\",\n  {\n    description: \"Total orchestration intent events processed by runtime reactors.\",\n  },\n);\n\nexport const providerSessionsTotal = Metric.counter(\"t3_provider_sessions_total\", {\n  description: \"Total provider session lifecycle operations.\",\n});\n\nexport const providerTurnsTotal = Metric.counter(\"t3_provider_turns_total\", {\n  description: \"Total provider turn lifecycle operations.\",\n});\n\nexport const providerTurnDuration = Metric.timer(\"t3_provider_turn_duration\", {\n  description: \"Provider turn request duration.\",\n});\n\nexport const providerRuntimeEventsTotal = Metric.counter(\"t3_provider_runtime_events_total\", {\n  description: \"Total canonical provider runtime events processed.\",\n});\n\nexport const gitCommandsTotal = Metric.counter(\"t3_git_commands_total\", {\n  description: \"Total git commands executed by the server runtime.\",\n});\n\nexport const gitCommandDuration = Metric.timer(\"t3_git_command_duration\", {\n  description: \"Git command execution duration.\",\n});\n\nexport const terminalSessionsTotal = Metric.counter(\"t3_terminal_sessions_total\", {\n  description: \"Total terminal sessions started.\",\n});\n\nexport const terminalRestartsTotal = Metric.counter(\"t3_terminal_restarts_total\", {\n  description: \"Total terminal restart requests handled.\",\n});\n\nexport const metricAttributes = (\n  attributes: Readonly<Record<string, unknown>>,\n): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));\n\nexport const increment = (\n  metric: Metric.Metric<number, unknown>,\n  attributes: Readonly<Record<string, unknown>>,\n  amount = 1,\n) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);\n\nexport interface WithMetricsOptions {\n  readonly counter?: Metric.Metric<number, unknown>;\n  readonly timer?: Metric.Metric<Duration.Duration, unknown>;\n  readonly attributes?:\n    | Readonly<Record<string, unknown>>\n    | (() => Readonly<Record<string, unknown>>);\n  readonly outcomeAttributes?: (\n    outcome: ReturnType<typeof outcomeFromExit>,\n  ) => Readonly<Record<string, unknown>>;\n}\n\nconst withMetricsImpl = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n  options: WithMetricsOptions,\n): Effect.Effect<A, E, R> =>\n  Effect.gen(function* () {\n    const startedAt = yield* Clock.currentTimeNanos;\n    const exit = yield* Effect.exit(effect);\n    const endedAt = yield* Clock.currentTimeNanos;\n    const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;\n    const duration = Duration.nanos(elapsedNanos);\n    const baseAttributes =\n      typeof options.attributes === \"function\" ? options.attributes() : (options.attributes ?? {});\n\n    if (options.timer) {\n      yield* Metric.update(\n        Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),\n        duration,\n      );\n    }\n\n    if (options.counter) {\n      const outcome = outcomeFromExit(exit);\n      yield* Metric.update(\n        Metric.withAttributes(\n          options.counter,\n          metricAttributes({\n            ...baseAttributes,\n            outcome,\n            ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),\n          }),\n        ),\n        1,\n      );\n    }\n\n    if (Exit.isSuccess(exit)) {\n      return exit.value;\n    }\n    return yield* Effect.failCause(exit.cause);\n  });\n\nexport const withMetrics: {\n  <A, E, R>(\n    options: WithMetricsOptions,\n  ): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n  <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;\n} = dual(2, withMetricsImpl);\n\nexport const providerMetricAttributes = (\n  provider: string,\n  extra?: Readonly<Record<string, unknown>>,\n) =>\n  compactMetricAttributes({\n    provider,\n    ...extra,\n  });\n\nexport const providerTurnMetricAttributes = (input: {\n  readonly provider: string;\n  readonly model: string | null | undefined;\n  readonly extra?: Readonly<Record<string, unknown>>;\n}) => {\n  const modelFamily = normalizeModelMetricLabel(input.model);\n  return compactMetricAttributes({\n    provider: input.provider,\n    ...(modelFamily ? { modelFamily } : {}),\n    ...input.extra,\n  });\n};\n","import * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { ProjectionRepositoryError } from \"../persistence/Errors.ts\";\n\nexport class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass<OrchestrationCommandJsonParseError>()(\n  \"OrchestrationCommandJsonParseError\",\n  {\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Invalid orchestration command JSON: ${this.detail}`;\n  }\n}\n\nexport class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass<OrchestrationCommandDecodeError>()(\n  \"OrchestrationCommandDecodeError\",\n  {\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Invalid orchestration command payload: ${this.issue}`;\n  }\n}\n\nexport class OrchestrationCommandInvariantError extends Schema.TaggedErrorClass<OrchestrationCommandInvariantError>()(\n  \"OrchestrationCommandInvariantError\",\n  {\n    commandType: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Orchestration command invariant failed (${this.commandType}): ${this.detail}`;\n  }\n}\n\n/**\n * agentlink fork: raised for commands whose supporting subsystem was cut\n * from this build (e.g. `thread.checkpoint.revert` without checkpointing).\n * Kept as a distinct typed error so clients can tell \"unsupported in this\n * build\" apart from a genuine invariant violation.\n */\nexport class OrchestrationUnsupportedError extends Schema.TaggedErrorClass<OrchestrationUnsupportedError>()(\n  \"OrchestrationUnsupportedError\",\n  {\n    commandType: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Orchestration command unsupported in this build (${this.commandType}): ${this.detail}`;\n  }\n}\n\nexport class OrchestrationCommandPreviouslyRejectedError extends Schema.TaggedErrorClass<OrchestrationCommandPreviouslyRejectedError>()(\n  \"OrchestrationCommandPreviouslyRejectedError\",\n  {\n    commandId: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Command previously rejected (${this.commandId}): ${this.detail}`;\n  }\n}\n\nexport class OrchestrationProjectorDecodeError extends Schema.TaggedErrorClass<OrchestrationProjectorDecodeError>()(\n  \"OrchestrationProjectorDecodeError\",\n  {\n    eventType: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Projector decode failed for ${this.eventType}: ${this.issue}`;\n  }\n}\n\nexport class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass<OrchestrationListenerCallbackError>()(\n  \"OrchestrationListenerCallbackError\",\n  {\n    listener: Schema.Literals([\"read-model\", \"domain-event\"]),\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Orchestration ${this.listener} listener failed: ${this.detail}`;\n  }\n}\n\nexport type OrchestrationDispatchError =\n  | ProjectionRepositoryError\n  | OrchestrationCommandInvariantError\n  | OrchestrationCommandPreviouslyRejectedError\n  | OrchestrationProjectorDecodeError\n  | OrchestrationListenerCallbackError;\n\nexport type OrchestrationEngineError =\n  | OrchestrationDispatchError\n  | OrchestrationCommandJsonParseError\n  | OrchestrationCommandDecodeError;\n\nexport function toOrchestrationCommandDecodeError(error: Schema.SchemaError) {\n  return new OrchestrationCommandDecodeError({\n    issue: SchemaIssue.makeFormatterDefault()(error.issue),\n    cause: error,\n  });\n}\n\nexport function toProjectorDecodeError(eventType: string) {\n  return (error: Schema.SchemaError): OrchestrationProjectorDecodeError =>\n    new OrchestrationProjectorDecodeError({\n      eventType,\n      issue: SchemaIssue.makeFormatterDefault()(error.issue),\n      cause: error,\n    });\n}\n\nexport function toOrchestrationJsonParseError(cause: unknown) {\n  return new OrchestrationCommandJsonParseError({\n    detail: `Failed to parse orchestration command JSON`,\n    cause,\n  });\n}\n\nexport function toListenerCallbackError(listener: \"read-model\" | \"domain-event\") {\n  return (cause: unknown): OrchestrationListenerCallbackError =>\n    new OrchestrationListenerCallbackError({\n      listener,\n      detail: `Failed to invoke orchestration ${listener} listener`,\n      cause,\n    });\n}\n","export function isWindowsDrivePath(value: string): boolean {\n  return /^[a-zA-Z]:([/\\\\]|$)/.test(value);\n}\n\nexport function isUncPath(value: string): boolean {\n  return value.startsWith(\"\\\\\\\\\");\n}\n\nexport function isWindowsAbsolutePath(value: string): boolean {\n  return isUncPath(value) || isWindowsDrivePath(value);\n}\n\nexport function isExplicitRelativePath(value: string): boolean {\n  return (\n    value === \".\" ||\n    value === \"..\" ||\n    value.startsWith(\"./\") ||\n    value.startsWith(\"../\") ||\n    value.startsWith(\".\\\\\") ||\n    value.startsWith(\"..\\\\\")\n  );\n}\n\nfunction isRootPath(value: string): boolean {\n  return value === \"/\" || value === \"\\\\\" || /^[a-zA-Z]:[/\\\\]?$/.test(value);\n}\n\nfunction trimTrailingPathSeparators(value: string): string {\n  if (value.length === 0 || isRootPath(value)) {\n    return value;\n  }\n  const trimmed = value.startsWith(\"/\")\n    ? value.replace(/\\/+$/g, \"\")\n    : value.replace(/[\\\\/]+$/g, \"\");\n  if (trimmed.length === 0) {\n    return value;\n  }\n  return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\\\` : trimmed;\n}\n\nexport function normalizeProjectPathForDispatch(value: string): string {\n  return trimTrailingPathSeparators(value.trim());\n}\n\nexport function normalizeProjectPathForComparison(value: string): string {\n  const normalized = normalizeProjectPathForDispatch(value);\n  if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {\n    return normalized.replaceAll(\"/\", \"\\\\\").toLowerCase();\n  }\n  return normalized;\n}\n","import type {\n  OrchestrationCommand,\n  OrchestrationProject,\n  OrchestrationReadModel,\n  OrchestrationThread,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport { normalizeProjectPathForComparison } from \"@t3tools/shared/path\";\nimport * as Effect from \"effect/Effect\";\n\nimport { OrchestrationCommandInvariantError } from \"./Errors.ts\";\n\nfunction invariantError(commandType: string, detail: string): OrchestrationCommandInvariantError {\n  return new OrchestrationCommandInvariantError({\n    commandType,\n    detail,\n  });\n}\n\nexport function findThreadById(\n  readModel: OrchestrationReadModel,\n  threadId: ThreadId,\n): OrchestrationThread | undefined {\n  return readModel.threads.find((thread) => thread.id === threadId);\n}\n\nexport function findProjectById(\n  readModel: OrchestrationReadModel,\n  projectId: ProjectId,\n): OrchestrationProject | undefined {\n  return readModel.projects.find((project) => project.id === projectId);\n}\n\nexport function listThreadsByProjectId(\n  readModel: OrchestrationReadModel,\n  projectId: ProjectId,\n): ReadonlyArray<OrchestrationThread> {\n  return readModel.threads.filter((thread) => thread.projectId === projectId);\n}\n\nexport function requireProject(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly projectId: ProjectId;\n}): Effect.Effect<OrchestrationProject, OrchestrationCommandInvariantError> {\n  const project = findProjectById(input.readModel, input.projectId);\n  if (project) {\n    return Effect.succeed(project);\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Project '${input.projectId}' does not exist for command '${input.command.type}'.`,\n    ),\n  );\n}\n\nexport function requireProjectAbsent(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly projectId: ProjectId;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  if (!findProjectById(input.readModel, input.projectId)) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Project '${input.projectId}' already exists and cannot be created twice.`,\n    ),\n  );\n}\n\nexport function requireActiveProjectWorkspaceRootAbsent(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly workspaceRoot: string;\n  readonly exceptProjectId?: ProjectId;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);\n  const existingProject = input.readModel.projects.find(\n    (project) =>\n      project.deletedAt === null &&\n      normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&\n      project.id !== input.exceptProjectId,\n  );\n  if (existingProject === undefined) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,\n    ),\n  );\n}\n\nexport function requireThread(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {\n  const thread = findThreadById(input.readModel, input.threadId);\n  if (thread) {\n    return Effect.succeed(thread);\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Thread '${input.threadId}' does not exist for command '${input.command.type}'.`,\n    ),\n  );\n}\n\nexport function requireThreadArchived(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {\n  return requireThread(input).pipe(\n    Effect.flatMap((thread) =>\n      thread.archivedAt !== null\n        ? Effect.succeed(thread)\n        : Effect.fail(\n            invariantError(\n              input.command.type,\n              `Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,\n            ),\n          ),\n    ),\n  );\n}\n\nexport function requireThreadNotArchived(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {\n  return requireThread(input).pipe(\n    Effect.flatMap((thread) =>\n      thread.archivedAt === null\n        ? Effect.succeed(thread)\n        : Effect.fail(\n            invariantError(\n              input.command.type,\n              `Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,\n            ),\n          ),\n    ),\n  );\n}\n\nexport function requireThreadAbsent(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  if (!findThreadById(input.readModel, input.threadId)) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Thread '${input.threadId}' already exists and cannot be created twice.`,\n    ),\n  );\n}\n\nexport function requireNonNegativeInteger(input: {\n  readonly commandType: OrchestrationCommand[\"type\"];\n  readonly field: string;\n  readonly value: number;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  if (Number.isInteger(input.value) && input.value >= 0) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.commandType,\n      `${input.field} must be an integer greater than or equal to 0.`,\n    ),\n  );\n}\n","import {\n  ProjectCreatedPayload as ContractsProjectCreatedPayloadSchema,\n  ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,\n  ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,\n  ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,\n  ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,\n  ThreadSettledPayload as ContractsThreadSettledPayloadSchema,\n  ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,\n  ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,\n  ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,\n  ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,\n  ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,\n  ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,\n  ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,\n  ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,\n  ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,\n  ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,\n  ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,\n  ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,\n  ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,\n  ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,\n  ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,\n  ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,\n  ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,\n  ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,\n  ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,\n  ThreadCheckpointRevertRequestedPayload as ContractsThreadCheckpointRevertRequestedPayloadSchema,\n  ThreadSessionStopRequestedPayload as ContractsThreadSessionStopRequestedPayloadSchema,\n} from \"@t3tools/contracts\";\n\n// Server-internal alias surface, backed by contract schemas as the source of truth.\nexport const ProjectCreatedPayload = ContractsProjectCreatedPayloadSchema;\nexport const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchema;\nexport const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;\n\nexport const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;\nexport const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;\nexport const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;\nexport const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;\nexport const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;\nexport const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;\nexport const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;\nexport const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;\nexport const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;\nexport const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;\nexport const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;\nexport const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;\nexport const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;\n\nexport const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;\nexport const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;\nexport const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;\nexport const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;\nexport const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;\nexport const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;\n\nexport const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;\nexport const ThreadTurnInterruptRequestedPayload =\n  ContractsThreadTurnInterruptRequestedPayloadSchema;\nexport const ThreadApprovalResponseRequestedPayload =\n  ContractsThreadApprovalResponseRequestedPayloadSchema;\nexport const ThreadCheckpointRevertRequestedPayload =\n  ContractsThreadCheckpointRevertRequestedPayloadSchema;\nexport const ThreadSessionStopRequestedPayload = ContractsThreadSessionStopRequestedPayloadSchema;\n","import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from \"@t3tools/contracts\";\nimport {\n  OrchestrationCheckpointSummary,\n  OrchestrationMessage,\n  OrchestrationSession,\n  OrchestrationThread,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from \"./Errors.ts\";\nimport {\n  MessageSentPayloadSchema,\n  ProjectCreatedPayload,\n  ProjectDeletedPayload,\n  ProjectMetaUpdatedPayload,\n  ThreadActivityAppendedPayload,\n  ThreadArchivedPayload,\n  ThreadCreatedPayload,\n  ThreadDeletedPayload,\n  ThreadInteractionModeSetPayload,\n  ThreadMetaUpdatedPayload,\n  ThreadProposedPlanUpsertedPayload,\n  ThreadRuntimeModeSetPayload,\n  ThreadSettledPayload,\n  ThreadPinnedPayload,\n  ThreadSnoozedPayload,\n  ThreadUnpinnedPayload,\n  ThreadUnarchivedPayload,\n  ThreadUnsettledPayload,\n  ThreadUnsnoozedPayload,\n  ThreadRevertedPayload,\n  ThreadSessionSetPayload,\n  ThreadTurnDiffCompletedPayload,\n} from \"./Schemas.ts\";\n\ntype ThreadPatch = Partial<Omit<OrchestrationThread, \"id\" | \"projectId\">>;\nconst MAX_THREAD_MESSAGES = 2_000;\nconst MAX_THREAD_CHECKPOINTS = 500;\n\nfunction checkpointStatusToLatestTurnState(status: \"ready\" | \"missing\" | \"error\") {\n  if (status === \"error\") return \"error\" as const;\n  if (status === \"missing\") return \"interrupted\" as const;\n  return \"completed\" as const;\n}\n\n/**\n * Turn state to settle a still-running latest turn with when its session\n * leaves the \"running\" status, or null while the session is (re)starting or\n * running and the turn must stay unsettled.\n */\nfunction settledTurnStateForSessionStatus(\n  status: OrchestrationSession[\"status\"],\n): \"completed\" | \"interrupted\" | \"error\" | null {\n  switch (status) {\n    case \"idle\":\n    case \"ready\":\n      return \"completed\";\n    case \"error\":\n      return \"error\";\n    case \"interrupted\":\n    case \"stopped\":\n      return \"interrupted\";\n    case \"starting\":\n    case \"running\":\n      return null;\n  }\n}\n\nfunction updateThread(\n  threads: ReadonlyArray<OrchestrationThread>,\n  threadId: ThreadId,\n  patch: ThreadPatch,\n): OrchestrationThread[] {\n  return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));\n}\n\nfunction decodeForEvent<A>(\n  schema: Schema.Decoder<A, never>,\n  value: unknown,\n  eventType: OrchestrationEvent[\"type\"],\n  field: string,\n): Effect.Effect<A, OrchestrationProjectorDecodeError> {\n  return Schema.decodeUnknownEffect(schema)(value).pipe(\n    Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),\n  );\n}\n\nfunction retainThreadMessagesAfterRevert(\n  messages: ReadonlyArray<OrchestrationMessage>,\n  retainedTurnIds: ReadonlySet<string>,\n  turnCount: number,\n): ReadonlyArray<OrchestrationMessage> {\n  const retainedMessageIds = new Set<string>();\n  for (const message of messages) {\n    if (message.role === \"system\") {\n      retainedMessageIds.add(message.id);\n      continue;\n    }\n    if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {\n      retainedMessageIds.add(message.id);\n    }\n  }\n\n  const retainedUserCount = messages.filter(\n    (message) => message.role === \"user\" && retainedMessageIds.has(message.id),\n  ).length;\n  const missingUserCount = Math.max(0, turnCount - retainedUserCount);\n  if (missingUserCount > 0) {\n    const fallbackUserMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"user\" &&\n          !retainedMessageIds.has(message.id) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n      )\n      .slice(0, missingUserCount);\n    for (const message of fallbackUserMessages) {\n      retainedMessageIds.add(message.id);\n    }\n  }\n\n  const retainedAssistantCount = messages.filter(\n    (message) => message.role === \"assistant\" && retainedMessageIds.has(message.id),\n  ).length;\n  const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);\n  if (missingAssistantCount > 0) {\n    const fallbackAssistantMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"assistant\" &&\n          !retainedMessageIds.has(message.id) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n      )\n      .slice(0, missingAssistantCount);\n    for (const message of fallbackAssistantMessages) {\n      retainedMessageIds.add(message.id);\n    }\n  }\n\n  return messages.filter((message) => retainedMessageIds.has(message.id));\n}\n\nfunction retainThreadActivitiesAfterRevert(\n  activities: ReadonlyArray<OrchestrationThread[\"activities\"][number]>,\n  retainedTurnIds: ReadonlySet<string>,\n): ReadonlyArray<OrchestrationThread[\"activities\"][number]> {\n  return activities.filter(\n    (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),\n  );\n}\n\nfunction retainThreadProposedPlansAfterRevert(\n  proposedPlans: ReadonlyArray<OrchestrationThread[\"proposedPlans\"][number]>,\n  retainedTurnIds: ReadonlySet<string>,\n): ReadonlyArray<OrchestrationThread[\"proposedPlans\"][number]> {\n  return proposedPlans.filter(\n    (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),\n  );\n}\n\nfunction compareThreadActivities(\n  left: OrchestrationThread[\"activities\"][number],\n  right: OrchestrationThread[\"activities\"][number],\n): number {\n  if (left.sequence !== undefined && right.sequence !== undefined) {\n    if (left.sequence !== right.sequence) {\n      return left.sequence - right.sequence;\n    }\n  } else if (left.sequence !== undefined) {\n    return 1;\n  } else if (right.sequence !== undefined) {\n    return -1;\n  }\n\n  return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);\n}\n\nexport function createEmptyReadModel(nowIso: string): OrchestrationReadModel {\n  return {\n    snapshotSequence: 0,\n    projects: [],\n    threads: [],\n    updatedAt: nowIso,\n  };\n}\n\nexport function projectEvent(\n  model: OrchestrationReadModel,\n  event: OrchestrationEvent,\n): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {\n  const nextBase: OrchestrationReadModel = {\n    ...model,\n    snapshotSequence: event.sequence,\n    updatedAt: event.occurredAt,\n  };\n\n  switch (event.type) {\n    case \"project.created\":\n      return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => {\n          const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);\n          const nextProject = {\n            id: payload.projectId,\n            title: payload.title,\n            workspaceRoot: payload.workspaceRoot,\n            defaultModelSelection: payload.defaultModelSelection,\n            scripts: payload.scripts,\n            createdAt: payload.createdAt,\n            updatedAt: payload.updatedAt,\n            deletedAt: null,\n          };\n\n          return {\n            ...nextBase,\n            projects: existing\n              ? nextBase.projects.map((entry) =>\n                  entry.id === payload.projectId ? nextProject : entry,\n                )\n              : [...nextBase.projects, nextProject],\n          };\n        }),\n      );\n\n    case \"project.meta-updated\":\n      return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          projects: nextBase.projects.map((project) =>\n            project.id === payload.projectId\n              ? {\n                  ...project,\n                  ...(payload.title !== undefined ? { title: payload.title } : {}),\n                  ...(payload.workspaceRoot !== undefined\n                    ? { workspaceRoot: payload.workspaceRoot }\n                    : {}),\n                  ...(payload.defaultModelSelection !== undefined\n                    ? { defaultModelSelection: payload.defaultModelSelection }\n                    : {}),\n                  ...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),\n                  updatedAt: payload.updatedAt,\n                }\n              : project,\n          ),\n        })),\n      );\n\n    case \"project.deleted\":\n      return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          projects: nextBase.projects.map((project) =>\n            project.id === payload.projectId\n              ? {\n                  ...project,\n                  deletedAt: payload.deletedAt,\n                  updatedAt: payload.deletedAt,\n                }\n              : project,\n          ),\n        })),\n      );\n\n    case \"thread.created\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadCreatedPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread: OrchestrationThread = yield* decodeForEvent(\n          OrchestrationThread,\n          {\n            id: payload.threadId,\n            projectId: payload.projectId,\n            title: payload.title,\n            modelSelection: payload.modelSelection,\n            runtimeMode: payload.runtimeMode,\n            interactionMode: payload.interactionMode,\n            branch: payload.branch,\n            worktreePath: payload.worktreePath,\n            latestTurn: null,\n            createdAt: payload.createdAt,\n            updatedAt: payload.updatedAt,\n            archivedAt: null,\n            settledOverride: null,\n            settledAt: null,\n            snoozedUntil: null,\n            snoozedAt: null,\n            deletedAt: null,\n            messages: [],\n            activities: [],\n            checkpoints: [],\n            session: null,\n          },\n          event.type,\n          \"thread\",\n        );\n        const existing = nextBase.threads.find((entry) => entry.id === thread.id);\n        return {\n          ...nextBase,\n          threads: existing\n            ? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))\n            : [...nextBase.threads, thread],\n        };\n      });\n\n    case \"thread.deleted\":\n      return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            deletedAt: payload.deletedAt,\n            updatedAt: payload.deletedAt,\n          }),\n        })),\n      );\n\n    case \"thread.archived\":\n      return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            archivedAt: payload.archivedAt,\n            titleRegeneration: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unarchived\":\n      return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            archivedAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.settled\":\n      return decodeForEvent(ThreadSettledPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            settledOverride: \"settled\",\n            settledAt: payload.settledAt,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unsettled\":\n      return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            settledOverride: payload.reason === \"user\" ? \"active\" : null,\n            settledAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.snoozed\":\n      return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            snoozedUntil: payload.snoozedUntil,\n            snoozedAt: payload.snoozedAt,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unsnoozed\":\n      return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            snoozedUntil: null,\n            snoozedAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.pinned\":\n      return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            pinnedAt: payload.pinnedAt,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unpinned\":\n      return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            pinnedAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.meta-updated\":\n      return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            ...(payload.title !== undefined ? { title: payload.title } : {}),\n            ...(payload.titleRegeneration !== undefined\n              ? { titleRegeneration: payload.titleRegeneration }\n              : {}),\n            ...(payload.modelSelection !== undefined\n              ? { modelSelection: payload.modelSelection }\n              : {}),\n            ...(payload.branch !== undefined ? { branch: payload.branch } : {}),\n            ...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.runtime-mode-set\":\n      return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            runtimeMode: payload.runtimeMode,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.interaction-mode-set\":\n      return decodeForEvent(\n        ThreadInteractionModeSetPayload,\n        event.payload,\n        event.type,\n        \"payload\",\n      ).pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            interactionMode: payload.interactionMode,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.message-sent\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          MessageSentPayloadSchema,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const message: OrchestrationMessage = yield* decodeForEvent(\n          OrchestrationMessage,\n          {\n            id: payload.messageId,\n            role: payload.role,\n            text: payload.text,\n            ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}),\n            turnId: payload.turnId,\n            streaming: payload.streaming,\n            createdAt: payload.createdAt,\n            updatedAt: payload.updatedAt,\n          },\n          event.type,\n          \"message\",\n        );\n\n        const existingMessage = thread.messages.find((entry) => entry.id === message.id);\n        const messages = existingMessage\n          ? thread.messages.map((entry) =>\n              entry.id === message.id\n                ? {\n                    ...entry,\n                    text: message.streaming\n                      ? `${entry.text}${message.text}`\n                      : message.text.length > 0\n                        ? message.text\n                        : entry.text,\n                    streaming: message.streaming,\n                    updatedAt: message.updatedAt,\n                    turnId: message.turnId,\n                    ...(message.attachments !== undefined\n                      ? { attachments: message.attachments }\n                      : {}),\n                  }\n                : entry,\n            )\n          : [...thread.messages, message];\n        const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);\n\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            messages: cappedMessages,\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.session-set\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadSessionSetPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const session: OrchestrationSession = yield* decodeForEvent(\n          OrchestrationSession,\n          payload.session,\n          event.type,\n          \"session\",\n        );\n\n        // Leaving the \"running\" session status is the turn-end signal: settle\n        // a still-running latest turn so its duration reflects the whole turn.\n        const settledTurnState = settledTurnStateForSessionStatus(session.status);\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            session,\n            latestTurn:\n              session.status === \"running\" && session.activeTurnId !== null\n                ? {\n                    turnId: session.activeTurnId,\n                    state: \"running\",\n                    requestedAt:\n                      thread.latestTurn?.turnId === session.activeTurnId\n                        ? thread.latestTurn.requestedAt\n                        : session.updatedAt,\n                    startedAt:\n                      thread.latestTurn?.turnId === session.activeTurnId\n                        ? (thread.latestTurn.startedAt ?? session.updatedAt)\n                        : session.updatedAt,\n                    completedAt: null,\n                    assistantMessageId:\n                      thread.latestTurn?.turnId === session.activeTurnId\n                        ? thread.latestTurn.assistantMessageId\n                        : null,\n                  }\n                : thread.latestTurn !== null &&\n                    thread.latestTurn.state === \"running\" &&\n                    settledTurnState !== null\n                  ? {\n                      ...thread.latestTurn,\n                      state: settledTurnState,\n                      // A running turn's completedAt can only hold a mid-turn\n                      // placeholder checkpoint timestamp — the session leaving\n                      // \"running\" is the authoritative turn end.\n                      completedAt: session.updatedAt,\n                    }\n                  : thread.latestTurn,\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.proposed-plan-upserted\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadProposedPlanUpsertedPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const proposedPlans = [\n          ...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),\n          payload.proposedPlan,\n        ]\n          .toSorted(\n            (left, right) =>\n              left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n          )\n          .slice(-200);\n\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            proposedPlans,\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.turn-diff-completed\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadTurnDiffCompletedPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const checkpoint = yield* decodeForEvent(\n          OrchestrationCheckpointSummary,\n          {\n            turnId: payload.turnId,\n            checkpointTurnCount: payload.checkpointTurnCount,\n            checkpointRef: payload.checkpointRef,\n            status: payload.status,\n            files: payload.files,\n            assistantMessageId: payload.assistantMessageId,\n            completedAt: payload.completedAt,\n          },\n          event.type,\n          \"checkpoint\",\n        );\n\n        // Do not let a placeholder (status \"missing\") overwrite a checkpoint\n        // that has already been captured with a real git ref (status \"ready\").\n        // ProviderRuntimeIngestion may fire multiple turn.diff.updated events\n        // per turn; without this guard later placeholders would clobber the\n        // real capture dispatched by CheckpointReactor.\n        const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);\n        if (existing && existing.status !== \"missing\" && checkpoint.status === \"missing\") {\n          return nextBase;\n        }\n\n        const checkpoints = [\n          ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),\n          checkpoint,\n        ]\n          .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)\n          .slice(-MAX_THREAD_CHECKPOINTS);\n\n        // Mid-turn diff updates produce placeholder checkpoints; record the\n        // checkpoint, but don't settle a turn its session is still running.\n        const turnStillRunning =\n          thread.session?.status === \"running\" && thread.session.activeTurnId === payload.turnId;\n\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            checkpoints,\n            latestTurn: turnStillRunning\n              ? thread.latestTurn\n              : {\n                  turnId: payload.turnId,\n                  state: checkpointStatusToLatestTurnState(payload.status),\n                  requestedAt:\n                    thread.latestTurn?.turnId === payload.turnId\n                      ? thread.latestTurn.requestedAt\n                      : payload.completedAt,\n                  startedAt:\n                    thread.latestTurn?.turnId === payload.turnId\n                      ? (thread.latestTurn.startedAt ?? payload.completedAt)\n                      : payload.completedAt,\n                  completedAt: payload.completedAt,\n                  assistantMessageId: payload.assistantMessageId,\n                },\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.reverted\":\n      return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => {\n          const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n          if (!thread) {\n            return nextBase;\n          }\n\n          const checkpoints = thread.checkpoints\n            .filter((entry) => entry.checkpointTurnCount <= payload.turnCount)\n            .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)\n            .slice(-MAX_THREAD_CHECKPOINTS);\n          const retainedTurnIds = new Set(checkpoints.map((checkpoint) => checkpoint.turnId));\n          const messages = retainThreadMessagesAfterRevert(\n            thread.messages,\n            retainedTurnIds,\n            payload.turnCount,\n          ).slice(-MAX_THREAD_MESSAGES);\n          const proposedPlans = retainThreadProposedPlansAfterRevert(\n            thread.proposedPlans,\n            retainedTurnIds,\n          ).slice(-200);\n          const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);\n\n          const latestCheckpoint = checkpoints.at(-1) ?? null;\n          const latestTurn =\n            latestCheckpoint === null\n              ? null\n              : {\n                  turnId: latestCheckpoint.turnId,\n                  state: checkpointStatusToLatestTurnState(latestCheckpoint.status),\n                  requestedAt: latestCheckpoint.completedAt,\n                  startedAt: latestCheckpoint.completedAt,\n                  completedAt: latestCheckpoint.completedAt,\n                  assistantMessageId: latestCheckpoint.assistantMessageId,\n                };\n\n          return {\n            ...nextBase,\n            threads: updateThread(nextBase.threads, payload.threadId, {\n              checkpoints,\n              messages,\n              proposedPlans,\n              activities,\n              latestTurn,\n              updatedAt: event.occurredAt,\n            }),\n          };\n        }),\n      );\n\n    case \"thread.activity-appended\":\n      return decodeForEvent(\n        ThreadActivityAppendedPayload,\n        event.payload,\n        event.type,\n        \"payload\",\n      ).pipe(\n        Effect.map((payload) => {\n          const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n          if (!thread) {\n            return nextBase;\n          }\n\n          const activities = [\n            ...thread.activities.filter((entry) => entry.id !== payload.activity.id),\n            payload.activity,\n          ]\n            .toSorted(compareThreadActivities)\n            .slice(-500);\n\n          return {\n            ...nextBase,\n            threads: updateThread(nextBase.threads, payload.threadId, {\n              activities,\n              updatedAt: event.occurredAt,\n            }),\n          };\n        }),\n      );\n\n    default:\n      return Effect.succeed(nextBase);\n  }\n}\n","import {\n  EventId,\n  type OrchestrationCommand,\n  type OrchestrationEvent,\n  type OrchestrationReadModel,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport type * as PlatformError from \"effect/PlatformError\";\n\nimport { OrchestrationCommandInvariantError, OrchestrationUnsupportedError } from \"./Errors.ts\";\nimport {\n  listThreadsByProjectId,\n  requireActiveProjectWorkspaceRootAbsent,\n  requireProject,\n  requireProjectAbsent,\n  requireThread,\n  requireThreadArchived,\n  requireThreadAbsent,\n  requireThreadNotArchived,\n} from \"./commandInvariants.ts\";\nimport { projectEvent } from \"./projector.ts\";\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\n// Session adoption takes seconds; a user message still unadopted after this\n// window is a failed/stale start, not pending work. Mirrors the client's\n// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.\nconst QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;\n\n/**\n * Blocked-on-you work derived from the thread's retained activities: an\n * approval or user-input request with no later resolution for the same\n * requestId. The server-side twin of the shell's hasPendingApprovals /\n * hasPendingUserInput flags, which the decider read model does not carry.\n * The clearing rules MUST match ProjectionPipeline's pending accounting —\n * resolved activities always clear, respond.failed clears only when the\n * failure detail marks the request stale/unknown — or settle would be\n * rejected on threads whose shell flags read as clear.\n */\nfunction isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {\n  const detail = typeof payload?.detail === \"string\" ? payload.detail.toLowerCase() : null;\n  if (detail === null) return false;\n  return (\n    detail.includes(\"stale pending approval request\") ||\n    detail.includes(\"unknown pending approval request\") ||\n    detail.includes(\"unknown pending permission request\") ||\n    detail.includes(\"stale pending user-input request\") ||\n    detail.includes(\"unknown pending user-input request\") ||\n    detail.includes(\"unknown pending user input request\") ||\n    detail.includes(\"unknown pending codex user input request\")\n  );\n}\n\n// Scans the read model's activities, which the projector caps at the most\n// recent 500. That bound is safe here: an OPEN approval/user-input request\n// blocks its turn, so the thread cannot accumulate hundreds of later\n// activities while one is outstanding — a request that has scrolled out of\n// the window is one whose turn kept running, i.e. it was resolved or went\n// stale. (The projection pipeline's pendingApprovalCount reads the same\n// capped stream and stays consistent with this view.)\nfunction hasOpenBlockingRequest(thread: {\n  readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;\n}): boolean {\n  const openRequestIds = new Set<string>();\n  for (const activity of thread.activities) {\n    const payload =\n      typeof activity.payload === \"object\" && activity.payload !== null\n        ? (activity.payload as Record<string, unknown>)\n        : null;\n    const requestId = typeof payload?.requestId === \"string\" ? payload.requestId : null;\n    if (requestId === null) continue;\n    if (activity.kind === \"approval.requested\" || activity.kind === \"user-input.requested\") {\n      openRequestIds.add(requestId);\n    } else if (activity.kind === \"approval.resolved\" || activity.kind === \"user-input.resolved\") {\n      openRequestIds.delete(requestId);\n    } else if (\n      (activity.kind === \"provider.approval.respond.failed\" ||\n        activity.kind === \"provider.user-input.respond.failed\") &&\n      isStaleRequestFailureDetail(payload)\n    ) {\n      openRequestIds.delete(requestId);\n    }\n  }\n  return openRequestIds.size > 0;\n}\n\n/**\n * A queued turn start — a user message no turn has picked up yet — is work\n * in flight even though session is still null (turn.start emits\n * message-sent + turn-start-requested; the session arrives later). Detection\n * mirrors the client's hasQueuedTurnStart: the newest user message is\n * strictly newer than every latestTurn timestamp (adoption stamps the new\n * turn's requestedAt with the message time, clearing this), and only within\n * the adoption grace window — historical threads whose last user message\n * postdates their turn timestamps (older-server data, mid-turn messages)\n * must not be blocked forever. A failed session start (status \"error\")\n * clears the block immediately.\n *\n * The age check is bounded on BOTH sides: message timestamps are\n * client-supplied, so a client clock ahead of the server yields a negative\n * age. Without the lower bound that negative age satisfies `<= grace` for\n * as long as the skew lasts, extending the block far past the intended two\n * minutes.\n */\nfunction threadHasQueuedTurnStart(\n  thread: {\n    readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;\n    readonly latestTurn: {\n      readonly requestedAt: string;\n      readonly startedAt: string | null;\n      readonly completedAt: string | null;\n    } | null;\n    readonly session: { readonly status: string } | null;\n  },\n  occurredAt: string,\n): boolean {\n  const latestUserMessageAtMs = thread.messages.reduce(\n    (latest, message) =>\n      message.role === \"user\" ? Math.max(latest, Date.parse(message.createdAt)) : latest,\n    Number.NEGATIVE_INFINITY,\n  );\n  const latestTurnAtMs =\n    thread.latestTurn === null\n      ? Number.NEGATIVE_INFINITY\n      : Math.max(\n          ...[\n            thread.latestTurn.requestedAt,\n            thread.latestTurn.startedAt,\n            thread.latestTurn.completedAt,\n          ].map((candidate) =>\n            candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),\n          ),\n        );\n  const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;\n  return (\n    thread.session?.status !== \"error\" &&\n    Number.isFinite(latestUserMessageAtMs) &&\n    latestUserMessageAtMs > latestTurnAtMs &&\n    Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS\n  );\n}\n\nfunction withEventBase(\n  input: Pick<OrchestrationCommand, \"commandId\"> & {\n    readonly aggregateKind: OrchestrationEvent[\"aggregateKind\"];\n    readonly aggregateId: OrchestrationEvent[\"aggregateId\"];\n    readonly occurredAt: string;\n    readonly metadata?: OrchestrationEvent[\"metadata\"];\n  },\n): Effect.Effect<\n  Omit<OrchestrationEvent, \"sequence\" | \"type\" | \"payload\">,\n  PlatformError.PlatformError,\n  Crypto.Crypto\n> {\n  return Crypto.Crypto.pipe(\n    Effect.flatMap((crypto) =>\n      crypto.randomUUIDv4.pipe(\n        Effect.map((eventId) => ({\n          eventId: EventId.make(eventId),\n          aggregateKind: input.aggregateKind,\n          aggregateId: input.aggregateId,\n          occurredAt: input.occurredAt,\n          commandId: input.commandId,\n          causationEventId: null,\n          correlationId: input.commandId,\n          metadata: input.metadata ?? {},\n        })),\n      ),\n    ),\n  );\n}\n\ntype PlannedOrchestrationEvent = Omit<OrchestrationEvent, \"sequence\">;\n\ntype DecideOrchestrationCommandResult =\n  | PlannedOrchestrationEvent\n  | ReadonlyArray<PlannedOrchestrationEvent>;\n\nconst decideCommandSequence = Effect.fn(\"decideCommandSequence\")(function* ({\n  commands,\n  readModel,\n}: {\n  readonly commands: ReadonlyArray<OrchestrationCommand>;\n  readonly readModel: OrchestrationReadModel;\n}): Effect.fn.Return<\n  ReadonlyArray<PlannedOrchestrationEvent>,\n  OrchestrationCommandInvariantError | OrchestrationUnsupportedError | PlatformError.PlatformError,\n  Crypto.Crypto\n> {\n  let nextReadModel = readModel;\n  let nextSequence = readModel.snapshotSequence;\n  const plannedEvents: PlannedOrchestrationEvent[] = [];\n\n  for (const nextCommand of commands) {\n    const decided = yield* decideOrchestrationCommand({\n      command: nextCommand,\n      readModel: nextReadModel,\n    });\n    const nextEvents = Array.isArray(decided) ? decided : [decided];\n    for (const nextEvent of nextEvents) {\n      plannedEvents.push(nextEvent);\n      nextSequence += 1;\n      nextReadModel = yield* projectEvent(nextReadModel, {\n        ...nextEvent,\n        sequence: nextSequence,\n      }).pipe(Effect.orDie);\n    }\n  }\n\n  return plannedEvents;\n});\n\nexport const decideOrchestrationCommand = Effect.fn(\"decideOrchestrationCommand\")(function* ({\n  command,\n  readModel,\n}: {\n  readonly command: OrchestrationCommand;\n  readonly readModel: OrchestrationReadModel;\n}): Effect.fn.Return<\n  DecideOrchestrationCommandResult,\n  OrchestrationCommandInvariantError | OrchestrationUnsupportedError | PlatformError.PlatformError,\n  Crypto.Crypto\n> {\n  switch (command.type) {\n    case \"project.create\": {\n      yield* requireProjectAbsent({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      yield* requireActiveProjectWorkspaceRootAbsent({\n        readModel,\n        command,\n        workspaceRoot: command.workspaceRoot,\n        exceptProjectId: command.projectId,\n      });\n\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"project\",\n          aggregateId: command.projectId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"project.created\",\n        payload: {\n          projectId: command.projectId,\n          title: command.title,\n          workspaceRoot: command.workspaceRoot,\n          defaultModelSelection: command.defaultModelSelection ?? null,\n          scripts: [],\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"project.meta.update\": {\n      yield* requireProject({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      if (command.workspaceRoot !== undefined) {\n        yield* requireActiveProjectWorkspaceRootAbsent({\n          readModel,\n          command,\n          workspaceRoot: command.workspaceRoot,\n          exceptProjectId: command.projectId,\n        });\n      }\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"project\",\n          aggregateId: command.projectId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"project.meta-updated\",\n        payload: {\n          projectId: command.projectId,\n          ...(command.title !== undefined ? { title: command.title } : {}),\n          ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),\n          ...(command.defaultModelSelection !== undefined\n            ? { defaultModelSelection: command.defaultModelSelection }\n            : {}),\n          ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"project.delete\": {\n      yield* requireProject({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(\n        (thread) => thread.deletedAt === null,\n      );\n      if (activeThreads.length > 0 && command.force !== true) {\n        return yield* new OrchestrationCommandInvariantError({\n          commandType: command.type,\n          detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,\n        });\n      }\n      if (activeThreads.length > 0) {\n        return yield* decideCommandSequence({\n          readModel,\n          commands: [\n            ...activeThreads.map(\n              (thread): Extract<OrchestrationCommand, { type: \"thread.delete\" }> => ({\n                type: \"thread.delete\",\n                commandId: command.commandId,\n                threadId: thread.id,\n              }),\n            ),\n            {\n              type: \"project.delete\",\n              commandId: command.commandId,\n              projectId: command.projectId,\n            },\n          ],\n        });\n      }\n\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"project\",\n          aggregateId: command.projectId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"project.deleted\" as const,\n        payload: {\n          projectId: command.projectId,\n          deletedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.create\": {\n      yield* requireProject({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      yield* requireThreadAbsent({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.created\",\n        payload: {\n          threadId: command.threadId,\n          projectId: command.projectId,\n          title: command.title,\n          modelSelection: command.modelSelection,\n          runtimeMode: command.runtimeMode,\n          interactionMode: command.interactionMode,\n          branch: command.branch,\n          worktreePath: command.worktreePath,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.delete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.deleted\",\n        payload: {\n          threadId: command.threadId,\n          deletedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.archive\": {\n      yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.archived\",\n        payload: {\n          threadId: command.threadId,\n          archivedAt: occurredAt,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.unarchive\": {\n      yield* requireThreadArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unarchived\",\n        payload: {\n          threadId: command.threadId,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.settle\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Server-side twin of the client's canSettle session check: a stale\n      // or raced client must not settle a thread whose session is coming\n      // alive or working.\n      if (thread.session?.status === \"starting\" || thread.session?.status === \"running\") {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has an active session and cannot be settled`,\n          }),\n        );\n      }\n      // Pending approval / user-input requests are blocked-on-you work: a\n      // raced or stale client must not park them behind a settled override\n      // that would surface only after the request resolves.\n      if (hasOpenBlockingRequest(thread)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be settled`,\n          }),\n        );\n      }\n      const occurredAt = yield* nowIso;\n      // Settling inside the adoption window would hide just-requested work.\n      if (threadHasQueuedTurnStart(thread, occurredAt)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a queued turn start and cannot be settled`,\n          }),\n        );\n      }\n      // Settling an already-settled thread re-emits with the original\n      // settledAt: the engine rejects zero-event commands, and bulk-settle /\n      // double-click must stay silent no-ops rather than surface errors.\n      const alreadySettled = thread.settledOverride === \"settled\" && thread.settledAt !== null;\n      const settledEvent = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.settled\" as const,\n        payload: {\n          threadId: command.threadId,\n          settledAt: alreadySettled ? thread.settledAt : occurredAt,\n          // A re-emission is a projected no-op: keep the existing updatedAt\n          // so duplicate settles neither rewind nor churn ordering. A fresh\n          // settle stamps the command time.\n          updatedAt: alreadySettled ? thread.updatedAt : occurredAt,\n        },\n      };\n      // Settling is \"I'm done with this\": it clears a pin the same way it\n      // parks the thread. Without this, settling a pinned thread would only\n      // stamp invisible state — the pin would hold the card in place until\n      // a separate unpin.\n      if (thread.pinnedAt == null) {\n        return settledEvent;\n      }\n      return [\n        settledEvent,\n        {\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unpinned\" as const,\n          payload: {\n            threadId: command.threadId,\n            updatedAt: occurredAt,\n          },\n        },\n      ];\n    }\n\n    case \"thread.unsettle\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Idempotent by re-emission (see thread.settle): reducing the event a\n      // second time lands on the same override state. A re-emission keeps\n      // the existing updatedAt so duplicates do not churn ordering.\n      const alreadyPinnedActive = thread.settledOverride === \"active\";\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsettled\",\n        payload: {\n          threadId: command.threadId,\n          reason: command.reason,\n          updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.snooze\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      // A wake time in the past would create a thread that is snoozed and\n      // woken at once — the row would never leave the inbox but still carry\n      // snooze state. Reject instead of silently normalizing. The negated\n      // comparison also catches unparseable wake times (IsoDateTime is\n      // structurally just a string): NaN fails every comparison, and an\n      // unparseable snoozedUntil must never persist.\n      if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,\n          }),\n        );\n      }\n      // Blocked-on-you work must not be snoozed away: a pending approval or\n      // user-input request is the agent waiting on the user, and hiding it\n      // defeats the request. (A running session IS snoozable — snooze only\n      // affects visibility, never the agent.)\n      if (hasOpenBlockingRequest(thread)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,\n          }),\n        );\n      }\n      // A queued turn start — a user message no turn has adopted yet — is\n      // invisible pending work: no session, no pending flags. Snoozing in\n      // that window would hide a just-requested turn exactly the way settle\n      // would.\n      if (threadHasQueuedTurnStart(thread, occurredAt)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,\n          }),\n        );\n      }\n      // Re-snoozing an already-snoozed thread to the SAME wake time is a\n      // duplicate (double-click, raced clients): re-emit with the original\n      // timestamps so the projection is a no-op. A different wake time is a\n      // real change and stamps fresh.\n      const existingSnoozedAt =\n        thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null\n          ? thread.snoozedAt\n          : null;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.snoozed\",\n        payload: {\n          threadId: command.threadId,\n          snoozedUntil: command.snoozedUntil,\n          snoozedAt: existingSnoozedAt ?? occurredAt,\n          updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.unsnooze\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Idempotent by re-emission (see thread.settle): waking a thread that\n      // is not snoozed lands on the same null state without churning\n      // updatedAt.\n      const alreadyAwake = thread.snoozedUntil == null;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsnoozed\",\n        payload: {\n          threadId: command.threadId,\n          reason: command.reason,\n          updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.pin\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      // Re-pinning an already-pinned thread is a duplicate (double-click,\n      // raced clients): re-emit with the original timestamps so the\n      // projection is a no-op. Pinning has no lifecycle invariants — a pin\n      // only ever promotes visibility, so it can never hide pending work.\n      const existingPinnedAt = thread.pinnedAt ?? null;\n      const pinnedEvent = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.pinned\" as const,\n        payload: {\n          threadId: command.threadId,\n          pinnedAt: existingPinnedAt ?? occurredAt,\n          updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,\n        },\n      };\n      // Pinning is a promotion: it clears the parked states rather than\n      // silently outranking them. An explicit settle un-settles (reason\n      // \"user\", same override the un-settle button stamps), and a snooze's\n      // return ticket is spent — the thread is on top NOW, not on Tuesday.\n      const promotionEvents: Array<Omit<OrchestrationEvent, \"sequence\">> = [];\n      if (thread.settledOverride === \"settled\") {\n        promotionEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsettled\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"user\",\n            updatedAt: occurredAt,\n          },\n        });\n      }\n      if (thread.snoozedUntil != null) {\n        promotionEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsnoozed\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"user\",\n            updatedAt: occurredAt,\n          },\n        });\n      }\n      return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;\n    }\n\n    case \"thread.unpin\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Idempotent by re-emission (see thread.settle): unpinning a thread\n      // that is not pinned lands on the same null state without churning\n      // updatedAt.\n      const alreadyUnpinned = thread.pinnedAt == null;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unpinned\",\n        payload: {\n          threadId: command.threadId,\n          updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.meta.update\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const branch =\n        command.branch !== undefined &&\n        command.expectedBranch !== undefined &&\n        thread.branch !== command.expectedBranch\n          ? thread.branch\n          : command.branch;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.meta-updated\",\n        payload: {\n          threadId: command.threadId,\n          ...(command.title !== undefined ? { title: command.title } : {}),\n          ...(command.regenerateTitle === true\n            ? {\n                regenerateTitle: true as const,\n                previousTitle: thread.title,\n                titleRegeneration: {\n                  requestId: command.commandId,\n                  startedAt: occurredAt,\n                },\n              }\n            : {}),\n          ...(command.title !== undefined && thread.titleRegeneration != null\n            ? { titleRegeneration: null }\n            : {}),\n          ...(command.modelSelection !== undefined\n            ? { modelSelection: command.modelSelection }\n            : {}),\n          ...(branch !== undefined ? { branch } : {}),\n          ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.title.regeneration.complete\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.meta-updated\",\n        payload: {\n          threadId: command.threadId,\n          ...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),\n          ...(requestIsCurrent ? { titleRegeneration: null } : {}),\n          updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,\n        },\n      };\n    }\n\n    case \"thread.runtime-mode.set\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.runtime-mode-set\",\n        payload: {\n          threadId: command.threadId,\n          runtimeMode: command.runtimeMode,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.interaction-mode.set\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.interaction-mode-set\",\n        payload: {\n          threadId: command.threadId,\n          interactionMode: command.interactionMode,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.turn.start\": {\n      const targetThread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const sourceProposedPlan = command.sourceProposedPlan;\n      const sourceThread = sourceProposedPlan\n        ? yield* requireThread({\n            readModel,\n            command,\n            threadId: sourceProposedPlan.threadId,\n          })\n        : null;\n      const sourcePlan =\n        sourceProposedPlan && sourceThread\n          ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)\n          : null;\n      if (sourceProposedPlan && !sourcePlan) {\n        return yield* new OrchestrationCommandInvariantError({\n          commandType: command.type,\n          detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,\n        });\n      }\n      if (sourceThread && sourceThread.projectId !== targetThread.projectId) {\n        return yield* new OrchestrationCommandInvariantError({\n          commandType: command.type,\n          detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,\n        });\n      }\n      const userMessageEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.message.messageId,\n          role: \"user\",\n          text: command.message.text,\n          attachments: command.message.attachments,\n          turnId: null,\n          streaming: false,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n      const turnStartRequestedEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        causationEventId: userMessageEvent.eventId,\n        type: \"thread.turn-start-requested\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.message.messageId,\n          ...(command.modelSelection !== undefined\n            ? { modelSelection: command.modelSelection }\n            : {}),\n          ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),\n          runtimeMode: targetThread.runtimeMode,\n          interactionMode: targetThread.interactionMode,\n          ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),\n          createdAt: command.createdAt,\n        },\n      };\n      // Real activity resets ANY override: it wakes an explicitly settled\n      // thread, and it clears a keep-active pin back to neutral so the\n      // thread can auto-settle again after this burst of work goes stale.\n      // A snooze clears the same way — sending a message to a snoozed\n      // thread is the user re-engaging, so the return ticket is spent.\n      const lifecycleResetEvents: Array<Omit<OrchestrationEvent, \"sequence\">> = [];\n      if (targetThread.settledOverride !== null) {\n        lifecycleResetEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt: command.createdAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsettled\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"activity\",\n            updatedAt: command.createdAt,\n          },\n        });\n      }\n      if (targetThread.snoozedUntil != null) {\n        lifecycleResetEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt: command.createdAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsnoozed\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"activity\",\n            updatedAt: command.createdAt,\n          },\n        });\n      }\n      return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];\n    }\n\n    case \"thread.turn.interrupt\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.turn-interrupt-requested\",\n        payload: {\n          threadId: command.threadId,\n          ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.approval.respond\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          metadata: {\n            requestId: command.requestId,\n          },\n        })),\n        type: \"thread.approval-response-requested\",\n        payload: {\n          threadId: command.threadId,\n          requestId: command.requestId,\n          decision: command.decision,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.user-input.respond\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          metadata: {\n            requestId: command.requestId,\n          },\n        })),\n        type: \"thread.user-input-response-requested\",\n        payload: {\n          threadId: command.threadId,\n          requestId: command.requestId,\n          answers: command.answers,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.checkpoint.revert\": {\n      // agentlink fork: the checkpointing subsystem (CheckpointReactor,\n      // CheckpointStore, git plumbing) was cut from this build, so revert\n      // can never succeed. Fail with a typed unsupported error instead of\n      // emitting a `thread.checkpoint-revert-requested` event no reactor\n      // will ever consume.\n      return yield* new OrchestrationUnsupportedError({\n        commandType: command.type,\n        detail: `Checkpoint revert is unsupported in this build (thread '${command.threadId}', turnCount ${command.turnCount}).`,\n      });\n    }\n\n    case \"thread.session.stop\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.session-stop-requested\",\n        payload: {\n          threadId: command.threadId,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.session.set\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const sessionSetEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          metadata: {},\n        })),\n        type: \"thread.session-set\",\n        payload: {\n          threadId: command.threadId,\n          session: command.session,\n        },\n      };\n      // Only a session coming alive is activity worth waking a settled thread\n      // for — status writes like ready/stopped/error arrive after the fact and\n      // must not fight a user's explicit settle. Snooze is deliberately NOT\n      // cleared here: snooze never pauses the agent, so its session starting\n      // or erroring is not the user re-engaging. Blocked/failed work still\n      // surfaces immediately — effectiveSnoozed refuses to classify a thread\n      // with a raised hand (approval / input / failure / fresh completion)\n      // as snoozed, without spending the return ticket.\n      const isSessionActivity =\n        command.session.status === \"starting\" || command.session.status === \"running\";\n      // Real activity resets ANY override (settled wakes, active unpins).\n      if (thread.settledOverride === null || !isSessionActivity) {\n        return sessionSetEvent;\n      }\n      const unsettledEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsettled\",\n        payload: {\n          threadId: command.threadId,\n          reason: \"activity\",\n          updatedAt: command.createdAt,\n        },\n      };\n      return [unsettledEvent, sessionSetEvent];\n    }\n\n    case \"thread.message.assistant.delta\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.messageId,\n          role: \"assistant\",\n          text: command.delta,\n          turnId: command.turnId ?? null,\n          streaming: true,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.message.user.import\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.messageId,\n          role: \"user\",\n          text: command.text,\n          attachments: [],\n          turnId: command.turnId,\n          streaming: false,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.message.assistant.complete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.messageId,\n          role: \"assistant\",\n          text: \"\",\n          turnId: command.turnId ?? null,\n          streaming: false,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.proposed-plan.upsert\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.proposed-plan-upserted\",\n        payload: {\n          threadId: command.threadId,\n          proposedPlan: command.proposedPlan,\n        },\n      };\n    }\n\n    case \"thread.turn.diff.complete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.turn-diff-completed\",\n        payload: {\n          threadId: command.threadId,\n          turnId: command.turnId,\n          checkpointTurnCount: command.checkpointTurnCount,\n          checkpointRef: command.checkpointRef,\n          status: command.status,\n          files: command.files,\n          assistantMessageId: command.assistantMessageId ?? null,\n          completedAt: command.completedAt,\n        },\n      };\n    }\n\n    case \"thread.revert.complete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.reverted\",\n        payload: {\n          threadId: command.threadId,\n          turnCount: command.turnCount,\n        },\n      };\n    }\n\n    case \"thread.activity.append\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const requestId =\n        typeof command.activity.payload === \"object\" &&\n        command.activity.payload !== null &&\n        \"requestId\" in command.activity.payload &&\n        typeof (command.activity.payload as { requestId?: unknown }).requestId === \"string\"\n          ? ((command.activity.payload as { requestId: string })\n              .requestId as OrchestrationEvent[\"metadata\"][\"requestId\"])\n          : undefined;\n      const activityAppendedEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          ...(requestId !== undefined ? { metadata: { requestId } } : {}),\n        })),\n        type: \"thread.activity-appended\",\n        payload: {\n          threadId: command.threadId,\n          activity: command.activity,\n        },\n      };\n      // An approval or user-input request is blocked-on-you work — it must\n      // never stay hidden inside a settled slim row.\n      const wakesSettledThread =\n        command.activity.kind === \"approval.requested\" ||\n        command.activity.kind === \"user-input.requested\";\n      // Real activity resets ANY override (settled wakes, active unpins).\n      if (thread.settledOverride === null || !wakesSettledThread) {\n        return activityAppendedEvent;\n      }\n      const unsettledEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsettled\",\n        payload: {\n          threadId: command.threadId,\n          reason: \"activity\",\n          updatedAt: command.createdAt,\n        },\n      };\n      return [unsettledEvent, activityAppendedEvent];\n    }\n\n    default: {\n      command satisfies never;\n      const fallback = command as never as { type: string };\n      return yield* new OrchestrationCommandInvariantError({\n        commandType: fallback.type,\n        detail: `Unknown command type: ${fallback.type}`,\n      });\n    }\n  }\n});\n","/**\n * OrchestrationProjectionPipeline - Event projection pipeline service interface.\n *\n * Coordinates projection bootstrap/replay and per-event projection updates for\n * orchestration read models.\n *\n * @module OrchestrationProjectionPipeline\n */\nimport type { OrchestrationEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../../persistence/Errors.ts\";\n\n/**\n * OrchestrationProjectionPipelineShape - Service API for projection execution.\n */\nexport interface OrchestrationProjectionPipelineShape {\n  /**\n   * Bootstrap projections by replaying persisted events.\n   *\n   * Resumes each projector from its stored projection-state cursor.\n   */\n  readonly bootstrap: Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Project a single orchestration event into projection repositories.\n   *\n   * Projectors are executed sequentially to preserve deterministic ordering.\n   */\n  readonly projectEvent: (\n    event: OrchestrationEvent,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * OrchestrationProjectionPipeline - Service tag for orchestration projections.\n */\nexport class OrchestrationProjectionPipeline extends Context.Service<\n  OrchestrationProjectionPipeline,\n  OrchestrationProjectionPipelineShape\n>()(\"t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline\") {}\n","import type {\n  OrchestrationEvent,\n  OrchestrationReadModel,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport { OrchestrationCommand } from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Clock from \"effect/Clock\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Metric from \"effect/Metric\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport {\n  metricAttributes,\n  orchestrationCommandAckDuration,\n  orchestrationCommandsTotal,\n  orchestrationCommandDuration,\n} from \"../../observability/Metrics.ts\";\nimport { toPersistenceSqlError } from \"../../persistence/Errors.ts\";\nimport { OrchestrationEventStore } from \"../../persistence/Services/OrchestrationEventStore.ts\";\nimport { OrchestrationCommandReceiptRepository } from \"../../persistence/Services/OrchestrationCommandReceipts.ts\";\nimport {\n  OrchestrationCommandInvariantError,\n  OrchestrationCommandPreviouslyRejectedError,\n  type OrchestrationDispatchError,\n  type OrchestrationProjectorDecodeError,\n} from \"../Errors.ts\";\nimport { decideOrchestrationCommand } from \"../decider.ts\";\nimport { createEmptyReadModel, projectEvent } from \"../projector.ts\";\nimport { OrchestrationProjectionPipeline } from \"../Services/ProjectionPipeline.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport {\n  OrchestrationEngineService,\n  type OrchestrationEngineShape,\n} from \"../Services/OrchestrationEngine.ts\";\nconst isOrchestrationCommandPreviouslyRejectedError = Schema.is(\n  OrchestrationCommandPreviouslyRejectedError,\n);\nconst isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError);\n\ninterface CommandEnvelope {\n  command: OrchestrationCommand;\n  result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;\n  startedAtMs: number;\n}\n\nfunction commandToAggregateRef(command: OrchestrationCommand): {\n  readonly aggregateKind: \"project\" | \"thread\";\n  readonly aggregateId: ProjectId | ThreadId;\n} {\n  switch (command.type) {\n    case \"project.create\":\n    case \"project.meta.update\":\n    case \"project.delete\":\n      return {\n        aggregateKind: \"project\",\n        aggregateId: command.projectId,\n      };\n    default:\n      return {\n        aggregateKind: \"thread\",\n        aggregateId: command.threadId,\n      };\n  }\n}\n\nconst makeOrchestrationEngine = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const eventStore = yield* OrchestrationEventStore;\n  const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;\n  const projectionPipeline = yield* OrchestrationProjectionPipeline;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const crypto = yield* Crypto.Crypto;\n\n  const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n  let commandReadModel = createEmptyReadModel(yield* nowIso);\n\n  const commandQueue = yield* Queue.unbounded<CommandEnvelope>();\n  const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();\n\n  const projectEventsOntoReadModel = (\n    baseReadModel: OrchestrationReadModel,\n    events: ReadonlyArray<OrchestrationEvent>,\n  ): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>\n    Effect.gen(function* () {\n      let nextReadModel = baseReadModel;\n      for (const event of events) {\n        nextReadModel = yield* projectEvent(nextReadModel, event);\n      }\n      return nextReadModel;\n    });\n\n  const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {\n    const dispatchStartSequence = commandReadModel.snapshotSequence;\n    let processingStartedAtMs = 0;\n    const aggregateRef = commandToAggregateRef(envelope.command);\n    const baseMetricAttributes = {\n      commandType: envelope.command.type,\n      aggregateKind: aggregateRef.aggregateKind,\n    } as const;\n    const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {\n      const persistedEvents = yield* Stream.runCollect(\n        eventStore.readFromSequence(dispatchStartSequence),\n      ).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)));\n      if (persistedEvents.length === 0) {\n        return;\n      }\n\n      commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);\n\n      for (const persistedEvent of persistedEvents) {\n        yield* PubSub.publish(eventPubSub, persistedEvent);\n      }\n    });\n\n    return Effect.exit(\n      Effect.gen(function* () {\n        processingStartedAtMs = yield* Clock.currentTimeMillis;\n        yield* Effect.annotateCurrentSpan({\n          \"orchestration.command_id\": envelope.command.commandId,\n          \"orchestration.command_type\": envelope.command.type,\n          \"orchestration.aggregate_kind\": aggregateRef.aggregateKind,\n          \"orchestration.aggregate_id\": aggregateRef.aggregateId,\n        });\n\n        const existingReceipt = yield* commandReceiptRepository.getByCommandId({\n          commandId: envelope.command.commandId,\n        });\n        if (Option.isSome(existingReceipt)) {\n          if (existingReceipt.value.status === \"accepted\") {\n            return {\n              sequence: existingReceipt.value.resultSequence,\n            };\n          }\n          return yield* new OrchestrationCommandPreviouslyRejectedError({\n            commandId: envelope.command.commandId,\n            detail: existingReceipt.value.error ?? \"Previously rejected.\",\n          });\n        }\n\n        const eventBase = yield* decideOrchestrationCommand({\n          command: envelope.command,\n          readModel: commandReadModel,\n        }).pipe(\n          Effect.provideService(Crypto.Crypto, crypto),\n          Effect.mapError((cause) =>\n            isOrchestrationCommandInvariantError(cause)\n              ? cause\n              : new OrchestrationCommandInvariantError({\n                  commandType: envelope.command.type,\n                  detail: \"Failed to generate an event identifier.\",\n                  cause,\n                }),\n          ),\n        );\n        const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];\n        const committedCommand = yield* sql\n          .withTransaction(\n            Effect.gen(function* () {\n              const committedEvents: OrchestrationEvent[] = [];\n              let nextCommandReadModel = commandReadModel;\n\n              for (const nextEvent of eventBases) {\n                const savedEvent = yield* eventStore.append(nextEvent);\n                nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);\n                yield* projectionPipeline.projectEvent(savedEvent);\n                committedEvents.push(savedEvent);\n              }\n\n              const lastSavedEvent = committedEvents.at(-1) ?? null;\n              if (lastSavedEvent === null) {\n                return yield* new OrchestrationCommandInvariantError({\n                  commandType: envelope.command.type,\n                  detail: \"Command produced no events.\",\n                });\n              }\n\n              yield* commandReceiptRepository.upsert({\n                commandId: envelope.command.commandId,\n                aggregateKind: lastSavedEvent.aggregateKind,\n                aggregateId: lastSavedEvent.aggregateId,\n                acceptedAt: lastSavedEvent.occurredAt,\n                resultSequence: lastSavedEvent.sequence,\n                status: \"accepted\",\n                error: null,\n              });\n\n              return {\n                committedEvents,\n                lastSequence: lastSavedEvent.sequence,\n                nextCommandReadModel,\n              } as const;\n            }),\n          )\n          .pipe(\n            Effect.catchTag(\"SqlError\", (sqlError) =>\n              Effect.fail(\n                toPersistenceSqlError(\"OrchestrationEngine.processEnvelope:transaction\")(sqlError),\n              ),\n            ),\n          );\n\n        commandReadModel = committedCommand.nextCommandReadModel;\n        for (const [index, event] of committedCommand.committedEvents.entries()) {\n          yield* PubSub.publish(eventPubSub, event);\n          if (index === 0) {\n            yield* Metric.update(\n              Metric.withAttributes(\n                orchestrationCommandAckDuration,\n                metricAttributes({\n                  ...baseMetricAttributes,\n                  ackEventType: event.type,\n                }),\n              ),\n              Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),\n            );\n          }\n        }\n        return { sequence: committedCommand.lastSequence };\n      }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),\n    ).pipe(\n      Effect.flatMap((exit) =>\n        Effect.gen(function* () {\n          const outcome = Exit.isSuccess(exit)\n            ? \"success\"\n            : Cause.hasInterruptsOnly(exit.cause)\n              ? \"interrupt\"\n              : \"failure\";\n          yield* Metric.update(\n            Metric.withAttributes(\n              orchestrationCommandDuration,\n              metricAttributes(baseMetricAttributes),\n            ),\n            Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - processingStartedAtMs)),\n          );\n          yield* Metric.update(\n            Metric.withAttributes(\n              orchestrationCommandsTotal,\n              metricAttributes({\n                ...baseMetricAttributes,\n                outcome,\n              }),\n            ),\n            1,\n          );\n\n          if (Exit.isSuccess(exit)) {\n            yield* Deferred.succeed(envelope.result, exit.value);\n            return;\n          }\n\n          const error = Cause.squash(exit.cause) as OrchestrationDispatchError;\n          if (!isOrchestrationCommandPreviouslyRejectedError(error)) {\n            yield* reconcileReadModelAfterDispatchFailure.pipe(\n              Effect.catch(() =>\n                Effect.logWarning(\n                  \"failed to reconcile orchestration read model after dispatch failure\",\n                ).pipe(\n                  Effect.annotateLogs({\n                    commandId: envelope.command.commandId,\n                    snapshotSequence: commandReadModel.snapshotSequence,\n                  }),\n                ),\n              ),\n            );\n\n            if (isOrchestrationCommandInvariantError(error)) {\n              yield* commandReceiptRepository\n                .upsert({\n                  commandId: envelope.command.commandId,\n                  aggregateKind: aggregateRef.aggregateKind,\n                  aggregateId: aggregateRef.aggregateId,\n                  acceptedAt: yield* nowIso,\n                  resultSequence: commandReadModel.snapshotSequence,\n                  status: \"rejected\",\n                  error: error.message,\n                })\n                .pipe(Effect.catch(() => Effect.void));\n            }\n          }\n\n          yield* Deferred.fail(envelope.result, error);\n        }),\n      ),\n    );\n  };\n\n  yield* projectionPipeline.bootstrap;\n  commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();\n\n  const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));\n  yield* Effect.forkScoped(worker);\n  yield* Effect.logDebug(\"orchestration engine started\").pipe(\n    Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),\n  );\n\n  const readEvents: OrchestrationEngineShape[\"readEvents\"] = (fromSequenceExclusive, limit) =>\n    eventStore.readFromSequence(fromSequenceExclusive, limit);\n\n  const dispatch: OrchestrationEngineShape[\"dispatch\"] = (command) =>\n    Effect.gen(function* () {\n      const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();\n      yield* Queue.offer(commandQueue, {\n        command,\n        result,\n        startedAtMs: yield* Clock.currentTimeMillis,\n      });\n      return yield* Deferred.await(result);\n    });\n\n  return {\n    readEvents,\n    dispatch,\n    // Each access creates a fresh PubSub subscription so that multiple\n    // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)\n    // each independently receive all domain events.\n    get streamDomainEvents(): OrchestrationEngineShape[\"streamDomainEvents\"] {\n      return Stream.fromPubSub(eventPubSub);\n    },\n    // The command read model's snapshotSequence tracks the latest committed\n    // event sequence (updated on the worker fiber). A plain property read is a\n    // consistent, committed value — reassignment of `commandReadModel` is\n    // atomic on the single-threaded event loop.\n    latestSequence: Effect.sync(() => commandReadModel.snapshotSequence),\n  } satisfies OrchestrationEngineShape;\n});\n\nexport const OrchestrationEngineLive = Layer.effect(\n  OrchestrationEngineService,\n  makeOrchestrationEngine,\n);\n","/**\n * ProjectionPendingApprovalRepository - Repository interface for pending approvals.\n *\n * Owns persistence operations for projected approval requests awaiting user\n * decisions.\n *\n * @module ProjectionPendingApprovalRepository\n */\nimport {\n  ApprovalRequestId,\n  IsoDateTime,\n  ProjectionPendingApprovalDecision,\n  ProjectionPendingApprovalStatus,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionPendingApproval = Schema.Struct({\n  requestId: ApprovalRequestId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  status: ProjectionPendingApprovalStatus,\n  decision: ProjectionPendingApprovalDecision,\n  createdAt: IsoDateTime,\n  resolvedAt: Schema.NullOr(IsoDateTime),\n});\nexport type ProjectionPendingApproval = typeof ProjectionPendingApproval.Type;\n\nexport const ListProjectionPendingApprovalsInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionPendingApprovalsInput = typeof ListProjectionPendingApprovalsInput.Type;\n\nexport const GetProjectionPendingApprovalInput = Schema.Struct({\n  requestId: ApprovalRequestId,\n});\nexport type GetProjectionPendingApprovalInput = typeof GetProjectionPendingApprovalInput.Type;\n\nexport const DeleteProjectionPendingApprovalInput = Schema.Struct({\n  requestId: ApprovalRequestId,\n});\nexport type DeleteProjectionPendingApprovalInput = typeof DeleteProjectionPendingApprovalInput.Type;\n\n/**\n * ProjectionPendingApprovalRepositoryShape - Service API for pending approvals.\n */\nexport interface ProjectionPendingApprovalRepositoryShape {\n  /**\n   * Insert or replace a projected pending approval row.\n   *\n   * Upserts by `requestId`.\n   */\n  readonly upsert: (\n    row: ProjectionPendingApproval,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * List pending approvals for a thread.\n   *\n   * Returned in ascending creation order.\n   */\n  readonly listByThreadId: (\n    input: ListProjectionPendingApprovalsInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionPendingApproval>, ProjectionRepositoryError>;\n\n  /**\n   * Read a pending approval row by request id.\n   */\n  readonly getByRequestId: (\n    input: GetProjectionPendingApprovalInput,\n  ) => Effect.Effect<Option.Option<ProjectionPendingApproval>, ProjectionRepositoryError>;\n\n  /**\n   * Delete a pending approval row by request id.\n   */\n  readonly deleteByRequestId: (\n    input: DeleteProjectionPendingApprovalInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionPendingApprovalRepository - Service tag for pending approval persistence.\n */\nexport class ProjectionPendingApprovalRepository extends Context.Service<\n  ProjectionPendingApprovalRepository,\n  ProjectionPendingApprovalRepositoryShape\n>()(\"t3/persistence/Services/ProjectionPendingApprovals/ProjectionPendingApprovalRepository\") {}\n","/**\n * ProjectionProjectRepository - Projection repository interface for projects.\n *\n * Owns persistence operations for project rows in the orchestration projection\n * read model.\n *\n * @module ProjectionProjectRepository\n */\nimport { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionProject = Schema.Struct({\n  projectId: ProjectId,\n  title: Schema.String,\n  workspaceRoot: Schema.String,\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  deletedAt: Schema.NullOr(IsoDateTime),\n});\nexport type ProjectionProject = typeof ProjectionProject.Type;\n\nexport const GetProjectionProjectInput = Schema.Struct({\n  projectId: ProjectId,\n});\nexport type GetProjectionProjectInput = typeof GetProjectionProjectInput.Type;\n\nexport const DeleteProjectionProjectInput = Schema.Struct({\n  projectId: ProjectId,\n});\nexport type DeleteProjectionProjectInput = typeof DeleteProjectionProjectInput.Type;\n\n/**\n * ProjectionProjectRepositoryShape - Service API for projected project records.\n */\nexport interface ProjectionProjectRepositoryShape {\n  /**\n   * Insert or replace a projected project row.\n   *\n   * Upserts by `projectId` and persists scripts through JSON encoding.\n   */\n  readonly upsert: (row: ProjectionProject) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected project row by id.\n   */\n  readonly getById: (\n    input: GetProjectionProjectInput,\n  ) => Effect.Effect<Option.Option<ProjectionProject>, ProjectionRepositoryError>;\n\n  /**\n   * List all projected project rows.\n   *\n   * Returned in deterministic creation order.\n   */\n  readonly listAll: () => Effect.Effect<\n    ReadonlyArray<ProjectionProject>,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Soft-delete a projected project row by id.\n   */\n  readonly deleteById: (\n    input: DeleteProjectionProjectInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionProjectRepository - Service tag for project projection persistence.\n */\nexport class ProjectionProjectRepository extends Context.Service<\n  ProjectionProjectRepository,\n  ProjectionProjectRepositoryShape\n>()(\"t3/persistence/Services/ProjectionProjects/ProjectionProjectRepository\") {}\n","/**\n * ProjectionStateRepository - Projection repository interface for projector cursors.\n *\n * Owns persistence operations for projection cursor state used to resume\n * incremental event projection.\n *\n * @module ProjectionStateRepository\n */\nimport { IsoDateTime, NonNegativeInt } from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionState = Schema.Struct({\n  projector: Schema.String,\n  lastAppliedSequence: NonNegativeInt,\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionState = typeof ProjectionState.Type;\n\nexport const GetProjectionStateInput = Schema.Struct({\n  projector: Schema.String,\n});\nexport type GetProjectionStateInput = typeof GetProjectionStateInput.Type;\n\n/**\n * ProjectionStateRepositoryShape - Service API for projector state records.\n */\nexport interface ProjectionStateRepositoryShape {\n  /**\n   * Insert or replace a projection cursor row.\n   *\n   * Upserts by projector name.\n   */\n  readonly upsert: (row: ProjectionState) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read projection cursor state for a projector key.\n   */\n  readonly getByProjector: (\n    input: GetProjectionStateInput,\n  ) => Effect.Effect<Option.Option<ProjectionState>, ProjectionRepositoryError>;\n\n  /**\n   * List all projector cursor rows.\n   */\n  readonly listAll: () => Effect.Effect<ReadonlyArray<ProjectionState>, ProjectionRepositoryError>;\n\n  /**\n   * Read the minimum applied sequence across all projectors.\n   *\n   * Returns `null` when no projector state rows exist.\n   */\n  readonly minLastAppliedSequence: () => Effect.Effect<number | null, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionStateRepository - Service tag for projection cursor persistence.\n */\nexport class ProjectionStateRepository extends Context.Service<\n  ProjectionStateRepository,\n  ProjectionStateRepositoryShape\n>()(\"t3/persistence/Services/ProjectionState/ProjectionStateRepository\") {}\n","/**\n * ProjectionThreadActivityRepository - Projection repository interface for thread activity.\n *\n * Owns persistence operations for activity timeline entries projected from\n * orchestration events.\n *\n * @module ProjectionThreadActivityRepository\n */\nimport {\n  EventId,\n  IsoDateTime,\n  NonNegativeInt,\n  OrchestrationThreadActivityTone,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadActivity = Schema.Struct({\n  activityId: EventId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  tone: OrchestrationThreadActivityTone,\n  kind: Schema.String,\n  summary: Schema.String,\n  payload: Schema.Unknown,\n  sequence: Schema.optional(NonNegativeInt),\n  createdAt: IsoDateTime,\n});\nexport type ProjectionThreadActivity = typeof ProjectionThreadActivity.Type;\n\nexport const ListProjectionThreadActivitiesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionThreadActivitiesInput = typeof ListProjectionThreadActivitiesInput.Type;\n\nexport const DeleteProjectionThreadActivitiesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadActivitiesInput =\n  typeof DeleteProjectionThreadActivitiesInput.Type;\n\n/**\n * ProjectionThreadActivityRepositoryShape - Service API for projected thread activity.\n */\nexport interface ProjectionThreadActivityRepositoryShape {\n  /**\n   * Insert or replace a projected thread activity row.\n   *\n   * Upserts by `activityId` and JSON-encodes payload.\n   */\n  readonly upsert: (\n    row: ProjectionThreadActivity,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * List projected thread activity rows for a thread.\n   *\n   * Returned in ascending runtime sequence order (or creation order when\n   * sequence is unavailable).\n   */\n  readonly listByThreadId: (\n    input: ListProjectionThreadActivitiesInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThreadActivity>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected thread activity rows by thread.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadActivitiesInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadActivityRepository - Service tag for thread activity persistence.\n */\nexport class ProjectionThreadActivityRepository extends Context.Service<\n  ProjectionThreadActivityRepository,\n  ProjectionThreadActivityRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreadActivities/ProjectionThreadActivityRepository\") {}\n","/**\n * ProjectionThreadMessageRepository - Projection repository interface for messages.\n *\n * Owns persistence operations for projected thread messages rendered in the\n * orchestration read model.\n *\n * @module ProjectionThreadMessageRepository\n */\nimport {\n  ChatAttachment,\n  MessageId,\n  OrchestrationMessageRole,\n  ThreadId,\n  TurnId,\n  IsoDateTime,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Option from \"effect/Option\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadMessage = Schema.Struct({\n  messageId: MessageId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  role: OrchestrationMessageRole,\n  text: Schema.String,\n  attachments: Schema.optional(Schema.Array(ChatAttachment)),\n  isStreaming: Schema.Boolean,\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionThreadMessage = typeof ProjectionThreadMessage.Type;\n\nexport const ListProjectionThreadMessagesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;\n\nexport const GetProjectionThreadMessageInput = Schema.Struct({\n  messageId: MessageId,\n});\nexport type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;\n\nexport const DeleteProjectionThreadMessagesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadMessagesInput = typeof DeleteProjectionThreadMessagesInput.Type;\n\n/**\n * ProjectionThreadMessageRepositoryShape - Service API for projected thread messages.\n */\nexport interface ProjectionThreadMessageRepositoryShape {\n  /**\n   * Insert or replace a projected thread message row.\n   *\n   * Upserts by `messageId`.\n   */\n  readonly upsert: (\n    message: ProjectionThreadMessage,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected thread message by id.\n   */\n  readonly getByMessageId: (\n    input: GetProjectionThreadMessageInput,\n  ) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;\n\n  /**\n   * List projected thread messages for a thread.\n   *\n   * Returned in ascending creation order.\n   */\n  readonly listByThreadId: (\n    input: ListProjectionThreadMessagesInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThreadMessage>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected thread messages by thread.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadMessagesInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadMessageRepository - Service tag for message projection persistence.\n */\nexport class ProjectionThreadMessageRepository extends Context.Service<\n  ProjectionThreadMessageRepository,\n  ProjectionThreadMessageRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreadMessages/ProjectionThreadMessageRepository\") {}\n","import {\n  IsoDateTime,\n  OrchestrationProposedPlanId,\n  ThreadId,\n  TrimmedNonEmptyString,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadProposedPlan = Schema.Struct({\n  planId: OrchestrationProposedPlanId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  planMarkdown: TrimmedNonEmptyString,\n  implementedAt: Schema.NullOr(IsoDateTime),\n  implementationThreadId: Schema.NullOr(ThreadId),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionThreadProposedPlan = typeof ProjectionThreadProposedPlan.Type;\n\nexport const ListProjectionThreadProposedPlansInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionThreadProposedPlansInput =\n  typeof ListProjectionThreadProposedPlansInput.Type;\n\nexport const DeleteProjectionThreadProposedPlansInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadProposedPlansInput =\n  typeof DeleteProjectionThreadProposedPlansInput.Type;\n\nexport interface ProjectionThreadProposedPlanRepositoryShape {\n  readonly upsert: (\n    proposedPlan: ProjectionThreadProposedPlan,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n  readonly listByThreadId: (\n    input: ListProjectionThreadProposedPlansInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadProposedPlansInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\nexport class ProjectionThreadProposedPlanRepository extends Context.Service<\n  ProjectionThreadProposedPlanRepository,\n  ProjectionThreadProposedPlanRepositoryShape\n>()(\n  \"t3/persistence/Services/ProjectionThreadProposedPlans/ProjectionThreadProposedPlanRepository\",\n) {}\n","/**\n * ProjectionThreadSessionRepository - Repository interface for thread sessions.\n *\n * Owns persistence operations for projected provider-session linkage and\n * runtime status for each thread.\n *\n * @module ProjectionThreadSessionRepository\n */\nimport {\n  RuntimeMode,\n  IsoDateTime,\n  OrchestrationSessionStatus,\n  ProviderInstanceId,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadSession = Schema.Struct({\n  threadId: ThreadId,\n  status: OrchestrationSessionStatus,\n  providerName: Schema.NullOr(Schema.String),\n  providerInstanceId: Schema.NullOr(ProviderInstanceId),\n  runtimeMode: RuntimeMode,\n  activeTurnId: Schema.NullOr(TurnId),\n  lastError: Schema.NullOr(Schema.String),\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionThreadSession = typeof ProjectionThreadSession.Type;\n\nexport const GetProjectionThreadSessionInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type GetProjectionThreadSessionInput = typeof GetProjectionThreadSessionInput.Type;\n\nexport const DeleteProjectionThreadSessionInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadSessionInput = typeof DeleteProjectionThreadSessionInput.Type;\n\n/**\n * ProjectionThreadSessionRepositoryShape - Service API for projected thread sessions.\n */\nexport interface ProjectionThreadSessionRepositoryShape {\n  /**\n   * Insert or replace a projected thread-session row.\n   *\n   * Upserts by `threadId`.\n   */\n  readonly upsert: (row: ProjectionThreadSession) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read projected thread-session state by thread id.\n   */\n  readonly getByThreadId: (\n    input: GetProjectionThreadSessionInput,\n  ) => Effect.Effect<Option.Option<ProjectionThreadSession>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected thread-session state by thread id.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadSessionInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadSessionRepository - Service tag for thread-session persistence.\n */\nexport class ProjectionThreadSessionRepository extends Context.Service<\n  ProjectionThreadSessionRepository,\n  ProjectionThreadSessionRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreadSessions/ProjectionThreadSessionRepository\") {}\n","/**\n * ProjectionTurnRepository - Projection repository interface for unified turn state.\n *\n * Owns persistence operations for pending starts, running/completed turn lifecycle,\n * and checkpoint metadata in a single projection table.\n *\n * @module ProjectionTurnRepository\n */\nimport {\n  CheckpointRef,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  OrchestrationProposedPlanId,\n  OrchestrationCheckpointFile,\n  OrchestrationCheckpointStatus,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionTurnState = Schema.Literals([\n  \"pending\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"error\",\n]);\nexport type ProjectionTurnState = typeof ProjectionTurnState.Type;\n\nexport const ProjectionTurn = Schema.Struct({\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  pendingMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n  assistantMessageId: Schema.NullOr(MessageId),\n  state: ProjectionTurnState,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  checkpointTurnCount: Schema.NullOr(NonNegativeInt),\n  checkpointRef: Schema.NullOr(CheckpointRef),\n  checkpointStatus: Schema.NullOr(OrchestrationCheckpointStatus),\n  checkpointFiles: Schema.Array(OrchestrationCheckpointFile),\n});\nexport type ProjectionTurn = typeof ProjectionTurn.Type;\n\nexport const ProjectionTurnById = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  pendingMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n  assistantMessageId: Schema.NullOr(MessageId),\n  state: ProjectionTurnState,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  checkpointTurnCount: Schema.NullOr(NonNegativeInt),\n  checkpointRef: Schema.NullOr(CheckpointRef),\n  checkpointStatus: Schema.NullOr(OrchestrationCheckpointStatus),\n  checkpointFiles: Schema.Array(OrchestrationCheckpointFile),\n});\nexport type ProjectionTurnById = typeof ProjectionTurnById.Type;\n\nexport const ProjectionPendingTurnStart = Schema.Struct({\n  threadId: ThreadId,\n  messageId: MessageId,\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n  requestedAt: IsoDateTime,\n});\nexport type ProjectionPendingTurnStart = typeof ProjectionPendingTurnStart.Type;\n\nexport const ListProjectionTurnsByThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionTurnsByThreadInput = typeof ListProjectionTurnsByThreadInput.Type;\n\nexport const GetProjectionTurnByTurnIdInput = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n});\nexport type GetProjectionTurnByTurnIdInput = typeof GetProjectionTurnByTurnIdInput.Type;\n\nexport const GetProjectionPendingTurnStartInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type GetProjectionPendingTurnStartInput = typeof GetProjectionPendingTurnStartInput.Type;\n\nexport const DeleteProjectionTurnsByThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionTurnsByThreadInput = typeof DeleteProjectionTurnsByThreadInput.Type;\n\nexport const ClearCheckpointTurnConflictInput = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n});\nexport type ClearCheckpointTurnConflictInput = typeof ClearCheckpointTurnConflictInput.Type;\n\nexport interface ProjectionTurnRepositoryShape {\n  /**\n   * Inserts or updates the canonical row for a concrete `{threadId, turnId}` turn lifecycle state.\n   */\n  readonly upsertByTurnId: (\n    row: ProjectionTurnById,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Replaces any existing pending-start placeholder rows for a thread with exactly one latest pending-start row.\n   */\n  readonly replacePendingTurnStart: (\n    row: ProjectionPendingTurnStart,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Returns the newest pending-start placeholder for a thread; this is expected to be at most one row after replacement writes.\n   */\n  readonly getPendingTurnStartByThreadId: (\n    input: GetProjectionPendingTurnStartInput,\n  ) => Effect.Effect<Option.Option<ProjectionPendingTurnStart>, ProjectionRepositoryError>;\n\n  /**\n   * Deletes only pending-start placeholder rows (`turnId = null`) for a thread and leaves concrete turn rows untouched.\n   */\n  readonly deletePendingTurnStartByThreadId: (\n    input: GetProjectionPendingTurnStartInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Lists all projection rows for a thread, including pending placeholders, with checkpoint rows ordered before non-checkpoint rows.\n   */\n  readonly listByThreadId: (\n    input: ListProjectionTurnsByThreadInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionTurn>, ProjectionRepositoryError>;\n\n  /**\n   * Looks up a concrete turn row by `{threadId, turnId}` and never returns pending placeholder rows.\n   */\n  readonly getByTurnId: (\n    input: GetProjectionTurnByTurnIdInput,\n  ) => Effect.Effect<Option.Option<ProjectionTurnById>, ProjectionRepositoryError>;\n\n  /**\n   * Clears checkpoint fields on conflicting rows that reuse the same checkpoint turn count in a thread, excluding the provided turn.\n   */\n  readonly clearCheckpointTurnConflict: (\n    input: ClearCheckpointTurnConflictInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Hard-deletes all projection rows for a thread, including pending-start placeholders and checkpoint metadata rows.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionTurnsByThreadInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\nexport class ProjectionTurnRepository extends Context.Service<\n  ProjectionTurnRepository,\n  ProjectionTurnRepositoryShape\n>()(\"t3/persistence/Services/ProjectionTurns/ProjectionTurnRepository\") {}\n","/**\n * ProjectionThreadRepository - Projection repository interface for threads.\n *\n * Owns persistence operations for projected thread records in the\n * orchestration read model.\n *\n * @module ProjectionThreadRepository\n */\nimport {\n  CommandId,\n  IsoDateTime,\n  ModelSelection,\n  NonNegativeInt,\n  ProjectId,\n  ProviderInteractionMode,\n  RuntimeMode,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThread = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  title: Schema.String,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode,\n  branch: Schema.NullOr(Schema.String),\n  worktreePath: Schema.NullOr(Schema.String),\n  latestTurnId: Schema.NullOr(TurnId),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  archivedAt: Schema.NullOr(IsoDateTime),\n  settledOverride: Schema.NullOr(Schema.Literals([\"settled\", \"active\"])),\n  settledAt: Schema.NullOr(IsoDateTime),\n  snoozedUntil: Schema.NullOr(IsoDateTime),\n  snoozedAt: Schema.NullOr(IsoDateTime),\n  pinnedAt: Schema.NullOr(IsoDateTime),\n  titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),\n  titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  latestUserMessageAt: Schema.NullOr(IsoDateTime),\n  pendingApprovalCount: NonNegativeInt,\n  pendingUserInputCount: NonNegativeInt,\n  hasActionableProposedPlan: NonNegativeInt,\n  deletedAt: Schema.NullOr(IsoDateTime),\n});\nexport type ProjectionThread = typeof ProjectionThread.Type;\n\nexport const GetProjectionThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type GetProjectionThreadInput = typeof GetProjectionThreadInput.Type;\n\nexport const DeleteProjectionThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadInput = typeof DeleteProjectionThreadInput.Type;\n\nexport const ListProjectionThreadsByProjectInput = Schema.Struct({\n  projectId: ProjectId,\n});\nexport type ListProjectionThreadsByProjectInput = typeof ListProjectionThreadsByProjectInput.Type;\n\n/**\n * ProjectionThreadRepositoryShape - Service API for projected thread records.\n */\nexport interface ProjectionThreadRepositoryShape {\n  /**\n   * Insert or replace a projected thread row.\n   *\n   * Upserts by `threadId`.\n   */\n  readonly upsert: (thread: ProjectionThread) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected thread row by id.\n   */\n  readonly getById: (\n    input: GetProjectionThreadInput,\n  ) => Effect.Effect<Option.Option<ProjectionThread>, ProjectionRepositoryError>;\n\n  /**\n   * List projected threads for a project.\n   *\n   * Returned in deterministic creation order.\n   */\n  readonly listByProjectId: (\n    input: ListProjectionThreadsByProjectInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThread>, ProjectionRepositoryError>;\n\n  /**\n   * Soft-delete a projected thread row by id.\n   */\n  readonly deleteById: (\n    input: DeleteProjectionThreadInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadRepository - Service tag for thread projection persistence.\n */\nexport class ProjectionThreadRepository extends Context.Service<\n  ProjectionThreadRepository,\n  ProjectionThreadRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreads/ProjectionThreadRepository\") {}\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  GetProjectionPendingApprovalInput,\n  DeleteProjectionPendingApprovalInput,\n  ListProjectionPendingApprovalsInput,\n  ProjectionPendingApproval,\n  ProjectionPendingApprovalRepository,\n  type ProjectionPendingApprovalRepositoryShape,\n} from \"../Services/ProjectionPendingApprovals.ts\";\n\nconst makeProjectionPendingApprovalRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionPendingApprovalRow = SqlSchema.void({\n    Request: ProjectionPendingApproval,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_pending_approvals (\n          request_id,\n          thread_id,\n          turn_id,\n          status,\n          decision,\n          created_at,\n          resolved_at\n        )\n        VALUES (\n          ${row.requestId},\n          ${row.threadId},\n          ${row.turnId},\n          ${row.status},\n          ${row.decision},\n          ${row.createdAt},\n          ${row.resolvedAt}\n        )\n        ON CONFLICT (request_id)\n        DO UPDATE SET\n          thread_id = excluded.thread_id,\n          turn_id = excluded.turn_id,\n          status = excluded.status,\n          decision = excluded.decision,\n          created_at = excluded.created_at,\n          resolved_at = excluded.resolved_at\n      `,\n  });\n\n  const listProjectionPendingApprovalRows = SqlSchema.findAll({\n    Request: ListProjectionPendingApprovalsInput,\n    Result: ProjectionPendingApproval,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          request_id AS \"requestId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          status,\n          decision,\n          created_at AS \"createdAt\",\n          resolved_at AS \"resolvedAt\"\n        FROM projection_pending_approvals\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, request_id ASC\n      `,\n  });\n\n  const getProjectionPendingApprovalRow = SqlSchema.findOneOption({\n    Request: GetProjectionPendingApprovalInput,\n    Result: ProjectionPendingApproval,\n    execute: ({ requestId }) =>\n      sql`\n        SELECT\n          request_id AS \"requestId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          status,\n          decision,\n          created_at AS \"createdAt\",\n          resolved_at AS \"resolvedAt\"\n        FROM projection_pending_approvals\n        WHERE request_id = ${requestId}\n      `,\n  });\n\n  const deleteProjectionPendingApprovalRow = SqlSchema.void({\n    Request: DeleteProjectionPendingApprovalInput,\n    execute: ({ requestId }) =>\n      sql`\n        DELETE FROM projection_pending_approvals\n        WHERE request_id = ${requestId}\n      `,\n  });\n\n  const upsert: ProjectionPendingApprovalRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionPendingApprovalRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionPendingApprovalRepository.upsert:query\")),\n    );\n\n  const listByThreadId: ProjectionPendingApprovalRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionPendingApprovalRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionPendingApprovalRepository.listByThreadId:query\"),\n      ),\n    );\n\n  const getByRequestId: ProjectionPendingApprovalRepositoryShape[\"getByRequestId\"] = (input) =>\n    getProjectionPendingApprovalRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionPendingApprovalRepository.getByRequestId:query\"),\n      ),\n    );\n\n  const deleteByRequestId: ProjectionPendingApprovalRepositoryShape[\"deleteByRequestId\"] = (\n    input,\n  ) =>\n    deleteProjectionPendingApprovalRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionPendingApprovalRepository.deleteByRequestId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    listByThreadId,\n    getByRequestId,\n    deleteByRequestId,\n  } satisfies ProjectionPendingApprovalRepositoryShape;\n});\n\nexport const ProjectionPendingApprovalRepositoryLive = Layer.effect(\n  ProjectionPendingApprovalRepository,\n  makeProjectionPendingApprovalRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { ModelSelection, ProjectScript } from \"@t3tools/contracts\";\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  DeleteProjectionProjectInput,\n  GetProjectionProjectInput,\n  ProjectionProject,\n  ProjectionProjectRepository,\n  type ProjectionProjectRepositoryShape,\n} from \"../Services/ProjectionProjects.ts\";\n\nconst ProjectionProjectDbRow = ProjectionProject.mapFields(\n  Struct.assign({\n    defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),\n    scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),\n  }),\n);\ntype ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;\n\nconst makeProjectionProjectRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionProjectRow = SqlSchema.void({\n    Request: ProjectionProject,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_projects (\n          project_id,\n          title,\n          workspace_root,\n          default_model_selection_json,\n          scripts_json,\n          created_at,\n          updated_at,\n          deleted_at\n        )\n        VALUES (\n          ${row.projectId},\n          ${row.title},\n          ${row.workspaceRoot},\n          ${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},\n          ${JSON.stringify(row.scripts)},\n          ${row.createdAt},\n          ${row.updatedAt},\n          ${row.deletedAt}\n        )\n        ON CONFLICT (project_id)\n        DO UPDATE SET\n          title = excluded.title,\n          workspace_root = excluded.workspace_root,\n          default_model_selection_json = excluded.default_model_selection_json,\n          scripts_json = excluded.scripts_json,\n          created_at = excluded.created_at,\n          updated_at = excluded.updated_at,\n          deleted_at = excluded.deleted_at\n      `,\n  });\n\n  const getProjectionProjectRow = SqlSchema.findOneOption({\n    Request: GetProjectionProjectInput,\n    Result: ProjectionProjectDbRow,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        WHERE project_id = ${projectId}\n      `,\n  });\n\n  const listProjectionProjectRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionProjectDbRow,\n    execute: () =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        ORDER BY created_at ASC, project_id ASC\n      `,\n  });\n\n  const deleteProjectionProjectRow = SqlSchema.void({\n    Request: DeleteProjectionProjectInput,\n    execute: ({ projectId }) =>\n      sql`\n        DELETE FROM projection_projects\n        WHERE project_id = ${projectId}\n      `,\n  });\n\n  const upsert: ProjectionProjectRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionProjectRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.upsert:query\")),\n    );\n\n  const getById: ProjectionProjectRepositoryShape[\"getById\"] = (input) =>\n    getProjectionProjectRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.getById:query\")),\n    );\n\n  const listAll: ProjectionProjectRepositoryShape[\"listAll\"] = () =>\n    listProjectionProjectRows().pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.listAll:query\")),\n    );\n\n  const deleteById: ProjectionProjectRepositoryShape[\"deleteById\"] = (input) =>\n    deleteProjectionProjectRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.deleteById:query\")),\n    );\n\n  return {\n    upsert,\n    getById,\n    listAll,\n    deleteById,\n  } satisfies ProjectionProjectRepositoryShape;\n});\n\nexport const ProjectionProjectRepositoryLive = Layer.effect(\n  ProjectionProjectRepository,\n  makeProjectionProjectRepository,\n);\n","import { NonNegativeInt } from \"@t3tools/contracts\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  ProjectionStateRepository,\n  type ProjectionStateRepositoryShape,\n  GetProjectionStateInput,\n  ProjectionState,\n} from \"../Services/ProjectionState.ts\";\n\nconst MinLastAppliedSequenceRowSchema = Schema.Struct({\n  minLastAppliedSequence: Schema.NullOr(NonNegativeInt),\n});\n\nconst makeProjectionStateRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionStateRow = SqlSchema.void({\n    Request: ProjectionState,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_state (\n          projector,\n          last_applied_sequence,\n          updated_at\n        )\n        VALUES (\n          ${row.projector},\n          ${row.lastAppliedSequence},\n          ${row.updatedAt}\n        )\n        ON CONFLICT (projector)\n        DO UPDATE SET\n          last_applied_sequence = excluded.last_applied_sequence,\n          updated_at = excluded.updated_at\n      `,\n  });\n\n  const getProjectionStateRow = SqlSchema.findOneOption({\n    Request: GetProjectionStateInput,\n    Result: ProjectionState,\n    execute: ({ projector }) =>\n      sql`\n        SELECT\n          projector,\n          last_applied_sequence AS \"lastAppliedSequence\",\n          updated_at AS \"updatedAt\"\n        FROM projection_state\n        WHERE projector = ${projector}\n      `,\n  });\n\n  const listProjectionStateRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionState,\n    execute: () =>\n      sql`\n        SELECT\n          projector,\n          last_applied_sequence AS \"lastAppliedSequence\",\n          updated_at AS \"updatedAt\"\n        FROM projection_state\n        ORDER BY projector ASC\n      `,\n  });\n\n  const readMinLastAppliedSequence = SqlSchema.findOne({\n    Request: Schema.Void,\n    Result: MinLastAppliedSequenceRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          MIN(last_applied_sequence) AS \"minLastAppliedSequence\"\n        FROM projection_state\n      `,\n  });\n\n  const upsert: ProjectionStateRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionStateRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionStateRepository.upsert:query\")),\n    );\n\n  const getByProjector: ProjectionStateRepositoryShape[\"getByProjector\"] = (input) =>\n    getProjectionStateRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionStateRepository.getByProjector:query\")),\n    );\n\n  const listAll: ProjectionStateRepositoryShape[\"listAll\"] = () =>\n    listProjectionStateRows(undefined).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionStateRepository.listAll:query\")),\n    );\n\n  const minLastAppliedSequence: ProjectionStateRepositoryShape[\"minLastAppliedSequence\"] = () =>\n    readMinLastAppliedSequence(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionStateRepository.minLastAppliedSequence:query\"),\n      ),\n      Effect.map((row) => row.minLastAppliedSequence),\n    );\n\n  return {\n    upsert,\n    getByProjector,\n    listAll,\n    minLastAppliedSequence,\n  } satisfies ProjectionStateRepositoryShape;\n});\n\nexport const ProjectionStateRepositoryLive = Layer.effect(\n  ProjectionStateRepository,\n  makeProjectionStateRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport { NonNegativeInt } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { toPersistenceDecodeError, toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  DeleteProjectionThreadActivitiesInput,\n  ListProjectionThreadActivitiesInput,\n  ProjectionThreadActivity,\n  ProjectionThreadActivityRepository,\n  type ProjectionThreadActivityRepositoryShape,\n} from \"../Services/ProjectionThreadActivities.ts\";\n\nconst ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(\n  Struct.assign({\n    payload: Schema.fromJsonString(Schema.Unknown),\n    sequence: Schema.NullOr(NonNegativeInt),\n  }),\n);\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown) =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeProjectionThreadActivityRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadActivityRow = SqlSchema.void({\n    Request: ProjectionThreadActivity,\n    execute: (row) =>\n      sql`\n            INSERT INTO projection_thread_activities (\n              activity_id,\n              thread_id,\n              turn_id,\n              tone,\n              kind,\n              summary,\n              payload_json,\n              sequence,\n              created_at\n            )\n            VALUES (\n              ${row.activityId},\n              ${row.threadId},\n              ${row.turnId},\n              ${row.tone},\n              ${row.kind},\n              ${row.summary},\n              ${JSON.stringify(row.payload)},\n              ${row.sequence ?? null},\n              ${row.createdAt}\n            )\n            ON CONFLICT (activity_id)\n            DO UPDATE SET\n              thread_id = excluded.thread_id,\n              turn_id = excluded.turn_id,\n              tone = excluded.tone,\n              kind = excluded.kind,\n              summary = excluded.summary,\n              payload_json = excluded.payload_json,\n              sequence = excluded.sequence,\n              created_at = excluded.created_at\n          `,\n  });\n\n  const listProjectionThreadActivityRows = SqlSchema.findAll({\n    Request: ListProjectionThreadActivitiesInput,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n        ORDER BY\n          CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const deleteProjectionThreadActivityRows = SqlSchema.void({\n    Request: DeleteProjectionThreadActivitiesInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadActivityRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadActivityRow(row).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionThreadActivityRepository.upsert:query\",\n          \"ProjectionThreadActivityRepository.upsert:encodeRequest\",\n        ),\n      ),\n    );\n\n  const listByThreadId: ProjectionThreadActivityRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionThreadActivityRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionThreadActivityRepository.listByThreadId:query\",\n          \"ProjectionThreadActivityRepository.listByThreadId:decodeRows\",\n        ),\n      ),\n      Effect.map((rows) =>\n        rows.map((row) => ({\n          activityId: row.activityId,\n          threadId: row.threadId,\n          turnId: row.turnId,\n          tone: row.tone,\n          kind: row.kind,\n          summary: row.summary,\n          payload: row.payload,\n          ...(row.sequence !== null ? { sequence: row.sequence } : {}),\n          createdAt: row.createdAt,\n        })),\n      ),\n    );\n\n  const deleteByThreadId: ProjectionThreadActivityRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionThreadActivityRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadActivityRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    listByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadActivityRepositoryShape;\n});\n\nexport const ProjectionThreadActivityRepositoryLive = Layer.effect(\n  ProjectionThreadActivityRepository,\n  makeProjectionThreadActivityRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\nimport { ChatAttachment } from \"@t3tools/contracts\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  GetProjectionThreadMessageInput,\n  ProjectionThreadMessageRepository,\n  type ProjectionThreadMessageRepositoryShape,\n  DeleteProjectionThreadMessagesInput,\n  ListProjectionThreadMessagesInput,\n  ProjectionThreadMessage,\n} from \"../Services/ProjectionThreadMessages.ts\";\n\nconst ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(\n  Struct.assign({\n    isStreaming: Schema.Number,\n    attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),\n  }),\n);\n\nfunction toProjectionThreadMessage(\n  row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,\n): ProjectionThreadMessage {\n  return {\n    messageId: row.messageId,\n    threadId: row.threadId,\n    turnId: row.turnId,\n    role: row.role,\n    text: row.text,\n    isStreaming: row.isStreaming === 1,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n    ...(row.attachments !== null ? { attachments: row.attachments } : {}),\n  };\n}\n\nconst makeProjectionThreadMessageRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadMessageRow = SqlSchema.void({\n    Request: ProjectionThreadMessage,\n    execute: (row) => {\n      const nextAttachmentsJson =\n        row.attachments !== undefined ? JSON.stringify(row.attachments) : null;\n      return sql`\n        INSERT INTO projection_thread_messages (\n          message_id,\n          thread_id,\n          turn_id,\n          role,\n          text,\n          attachments_json,\n          is_streaming,\n          created_at,\n          updated_at\n        )\n        VALUES (\n          ${row.messageId},\n          ${row.threadId},\n          ${row.turnId},\n          ${row.role},\n          ${row.text},\n          COALESCE(\n            ${nextAttachmentsJson},\n            (\n              SELECT attachments_json\n              FROM projection_thread_messages\n              WHERE message_id = ${row.messageId}\n            )\n          ),\n          ${row.isStreaming ? 1 : 0},\n          ${row.createdAt},\n          ${row.updatedAt}\n        )\n        ON CONFLICT (message_id)\n        DO UPDATE SET\n          thread_id = excluded.thread_id,\n          turn_id = excluded.turn_id,\n          role = excluded.role,\n          text = excluded.text,\n          attachments_json = COALESCE(\n            excluded.attachments_json,\n            projection_thread_messages.attachments_json\n          ),\n          is_streaming = excluded.is_streaming,\n          created_at = excluded.created_at,\n          updated_at = excluded.updated_at\n      `;\n    },\n  });\n\n  const getProjectionThreadMessageRow = SqlSchema.findOneOption({\n    Request: GetProjectionThreadMessageInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ messageId }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE message_id = ${messageId}\n        LIMIT 1\n      `,\n  });\n\n  const listProjectionThreadMessageRows = SqlSchema.findAll({\n    Request: ListProjectionThreadMessagesInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, message_id ASC\n      `,\n  });\n\n  const deleteProjectionThreadMessageRows = SqlSchema.void({\n    Request: DeleteProjectionThreadMessagesInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadMessageRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadMessageRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadMessageRepository.upsert:query\")),\n    );\n\n  const getByMessageId: ProjectionThreadMessageRepositoryShape[\"getByMessageId\"] = (input) =>\n    getProjectionThreadMessageRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadMessageRepository.getByMessageId:query\"),\n      ),\n      Effect.map(Option.map(toProjectionThreadMessage)),\n    );\n\n  const listByThreadId: ProjectionThreadMessageRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionThreadMessageRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadMessageRepository.listByThreadId:query\"),\n      ),\n      Effect.map((rows) => rows.map(toProjectionThreadMessage)),\n    );\n\n  const deleteByThreadId: ProjectionThreadMessageRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionThreadMessageRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadMessageRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    getByMessageId,\n    listByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadMessageRepositoryShape;\n});\n\nexport const ProjectionThreadMessageRepositoryLive = Layer.effect(\n  ProjectionThreadMessageRepository,\n  makeProjectionThreadMessageRepository,\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  DeleteProjectionThreadProposedPlansInput,\n  ListProjectionThreadProposedPlansInput,\n  ProjectionThreadProposedPlan,\n  ProjectionThreadProposedPlanRepository,\n  type ProjectionThreadProposedPlanRepositoryShape,\n} from \"../Services/ProjectionThreadProposedPlans.ts\";\n\nconst makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadProposedPlanRow = SqlSchema.void({\n    Request: ProjectionThreadProposedPlan,\n    execute: (row) => sql`\n      INSERT INTO projection_thread_proposed_plans (\n        plan_id,\n        thread_id,\n        turn_id,\n        plan_markdown,\n        implemented_at,\n        implementation_thread_id,\n        created_at,\n        updated_at\n      )\n      VALUES (\n        ${row.planId},\n        ${row.threadId},\n        ${row.turnId},\n        ${row.planMarkdown},\n        ${row.implementedAt},\n        ${row.implementationThreadId},\n        ${row.createdAt},\n        ${row.updatedAt}\n      )\n      ON CONFLICT (plan_id)\n      DO UPDATE SET\n        thread_id = excluded.thread_id,\n        turn_id = excluded.turn_id,\n        plan_markdown = excluded.plan_markdown,\n        implemented_at = excluded.implemented_at,\n        implementation_thread_id = excluded.implementation_thread_id,\n        created_at = excluded.created_at,\n        updated_at = excluded.updated_at\n    `,\n  });\n\n  const listProjectionThreadProposedPlanRows = SqlSchema.findAll({\n    Request: ListProjectionThreadProposedPlansInput,\n    Result: ProjectionThreadProposedPlan,\n    execute: ({ threadId }) => sql`\n      SELECT\n        plan_id AS \"planId\",\n        thread_id AS \"threadId\",\n        turn_id AS \"turnId\",\n        plan_markdown AS \"planMarkdown\",\n        implemented_at AS \"implementedAt\",\n        implementation_thread_id AS \"implementationThreadId\",\n        created_at AS \"createdAt\",\n        updated_at AS \"updatedAt\"\n      FROM projection_thread_proposed_plans\n      WHERE thread_id = ${threadId}\n      ORDER BY created_at ASC, plan_id ASC\n    `,\n  });\n\n  const deleteProjectionThreadProposedPlanRows = SqlSchema.void({\n    Request: DeleteProjectionThreadProposedPlansInput,\n    execute: ({ threadId }) => sql`\n      DELETE FROM projection_thread_proposed_plans\n      WHERE thread_id = ${threadId}\n    `,\n  });\n\n  const upsert: ProjectionThreadProposedPlanRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadProposedPlanRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadProposedPlanRepository.upsert:query\")),\n    );\n\n  const listByThreadId: ProjectionThreadProposedPlanRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionThreadProposedPlanRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadProposedPlanRepository.listByThreadId:query\"),\n      ),\n    );\n\n  const deleteByThreadId: ProjectionThreadProposedPlanRepositoryShape[\"deleteByThreadId\"] = (\n    input,\n  ) =>\n    deleteProjectionThreadProposedPlanRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadProposedPlanRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    listByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadProposedPlanRepositoryShape;\n});\n\nexport const ProjectionThreadProposedPlanRepositoryLive = Layer.effect(\n  ProjectionThreadProposedPlanRepository,\n  makeProjectionThreadProposedPlanRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  ProjectionThreadSession,\n  ProjectionThreadSessionRepository,\n  type ProjectionThreadSessionRepositoryShape,\n  DeleteProjectionThreadSessionInput,\n  GetProjectionThreadSessionInput,\n} from \"../Services/ProjectionThreadSessions.ts\";\n\nconst makeProjectionThreadSessionRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadSessionRow = SqlSchema.void({\n    Request: ProjectionThreadSession,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_thread_sessions (\n          thread_id,\n          status,\n          provider_name,\n          provider_instance_id,\n          runtime_mode,\n          active_turn_id,\n          last_error,\n          updated_at\n        )\n        VALUES (\n          ${row.threadId},\n          ${row.status},\n          ${row.providerName},\n          ${row.providerInstanceId},\n          ${row.runtimeMode},\n          ${row.activeTurnId},\n          ${row.lastError},\n          ${row.updatedAt}\n        )\n        ON CONFLICT (thread_id)\n        DO UPDATE SET\n          status = excluded.status,\n          provider_name = excluded.provider_name,\n          provider_instance_id = excluded.provider_instance_id,\n          runtime_mode = excluded.runtime_mode,\n          active_turn_id = excluded.active_turn_id,\n          last_error = excluded.last_error,\n          updated_at = excluded.updated_at\n      `,\n  });\n\n  const getProjectionThreadSessionRow = SqlSchema.findOneOption({\n    Request: GetProjectionThreadSessionInput,\n    Result: ProjectionThreadSession,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          status,\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          runtime_mode AS \"runtimeMode\",\n          active_turn_id AS \"activeTurnId\",\n          last_error AS \"lastError\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const deleteProjectionThreadSessionRow = SqlSchema.void({\n    Request: DeleteProjectionThreadSessionInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_thread_sessions\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadSessionRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadSessionRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadSessionRepository.upsert:query\")),\n    );\n\n  const getByThreadId: ProjectionThreadSessionRepositoryShape[\"getByThreadId\"] = (input) =>\n    getProjectionThreadSessionRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadSessionRepository.getByThreadId:query\"),\n      ),\n    );\n\n  const deleteByThreadId: ProjectionThreadSessionRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionThreadSessionRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadSessionRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    getByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadSessionRepositoryShape;\n});\n\nexport const ProjectionThreadSessionRepositoryLive = Layer.effect(\n  ProjectionThreadSessionRepository,\n  makeProjectionThreadSessionRepository,\n);\n","import { OrchestrationCheckpointFile } from \"@t3tools/contracts\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { toPersistenceDecodeError, toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  ClearCheckpointTurnConflictInput,\n  DeleteProjectionTurnsByThreadInput,\n  GetProjectionPendingTurnStartInput,\n  GetProjectionTurnByTurnIdInput,\n  ListProjectionTurnsByThreadInput,\n  ProjectionPendingTurnStart,\n  ProjectionTurn,\n  ProjectionTurnById,\n  ProjectionTurnRepository,\n  type ProjectionTurnRepositoryShape,\n} from \"../Services/ProjectionTurns.ts\";\n\nconst ProjectionTurnDbRowSchema = ProjectionTurn.mapFields(\n  Struct.assign({\n    checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),\n  }),\n);\n\nconst ProjectionTurnByIdDbRowSchema = ProjectionTurnById.mapFields(\n  Struct.assign({\n    checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),\n  }),\n);\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown) =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeProjectionTurnRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionTurnById = SqlSchema.void({\n    Request: ProjectionTurnByIdDbRowSchema,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_turns (\n          thread_id,\n          turn_id,\n          pending_message_id,\n          source_proposed_plan_thread_id,\n          source_proposed_plan_id,\n          assistant_message_id,\n          state,\n          requested_at,\n          started_at,\n          completed_at,\n          checkpoint_turn_count,\n          checkpoint_ref,\n          checkpoint_status,\n          checkpoint_files_json\n        )\n        VALUES (\n          ${row.threadId},\n          ${row.turnId},\n          ${row.pendingMessageId},\n          ${row.sourceProposedPlanThreadId},\n          ${row.sourceProposedPlanId},\n          ${row.assistantMessageId},\n          ${row.state},\n          ${row.requestedAt},\n          ${row.startedAt},\n          ${row.completedAt},\n          ${row.checkpointTurnCount},\n          ${row.checkpointRef},\n          ${row.checkpointStatus},\n          ${row.checkpointFiles}\n        )\n        ON CONFLICT (thread_id, turn_id)\n        DO UPDATE SET\n          pending_message_id = excluded.pending_message_id,\n          source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,\n          source_proposed_plan_id = excluded.source_proposed_plan_id,\n          assistant_message_id = excluded.assistant_message_id,\n          state = excluded.state,\n          requested_at = excluded.requested_at,\n          started_at = excluded.started_at,\n          completed_at = excluded.completed_at,\n          checkpoint_turn_count = excluded.checkpoint_turn_count,\n          checkpoint_ref = excluded.checkpoint_ref,\n          checkpoint_status = excluded.checkpoint_status,\n          checkpoint_files_json = excluded.checkpoint_files_json\n      `,\n  });\n\n  const clearPendingProjectionTurnsByThread = SqlSchema.void({\n    Request: DeleteProjectionTurnsByThreadInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND turn_id IS NULL\n          AND state = 'pending'\n          AND checkpoint_turn_count IS NULL\n      `,\n  });\n\n  const insertPendingProjectionTurn = SqlSchema.void({\n    Request: ProjectionPendingTurnStart,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_turns (\n          thread_id,\n          turn_id,\n          pending_message_id,\n          source_proposed_plan_thread_id,\n          source_proposed_plan_id,\n          assistant_message_id,\n          state,\n          requested_at,\n          started_at,\n          completed_at,\n          checkpoint_turn_count,\n          checkpoint_ref,\n          checkpoint_status,\n          checkpoint_files_json\n        )\n        VALUES (\n          ${row.threadId},\n          NULL,\n          ${row.messageId},\n          ${row.sourceProposedPlanThreadId},\n          ${row.sourceProposedPlanId},\n          NULL,\n          'pending',\n          ${row.requestedAt},\n          NULL,\n          NULL,\n          NULL,\n          NULL,\n          NULL,\n          '[]'\n        )\n      `,\n  });\n\n  const getPendingProjectionTurn = SqlSchema.findOneOption({\n    Request: GetProjectionPendingTurnStartInput,\n    Result: ProjectionPendingTurnStart,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          pending_message_id AS \"messageId\",\n          source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          source_proposed_plan_id AS \"sourceProposedPlanId\",\n          requested_at AS \"requestedAt\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND turn_id IS NULL\n          AND state = 'pending'\n          AND pending_message_id IS NOT NULL\n          AND checkpoint_turn_count IS NULL\n        ORDER BY requested_at DESC\n        LIMIT 1\n      `,\n  });\n\n  const listProjectionTurnsByThread = SqlSchema.findAll({\n    Request: ListProjectionTurnsByThreadInput,\n    Result: ProjectionTurnDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          pending_message_id AS \"pendingMessageId\",\n          source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          source_proposed_plan_id AS \"sourceProposedPlanId\",\n          assistant_message_id AS \"assistantMessageId\",\n          state,\n          requested_at AS \"requestedAt\",\n          started_at AS \"startedAt\",\n          completed_at AS \"completedAt\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"checkpointStatus\",\n          checkpoint_files_json AS \"checkpointFiles\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n        ORDER BY\n          CASE\n            WHEN checkpoint_turn_count IS NULL THEN 1\n            ELSE 0\n          END ASC,\n          checkpoint_turn_count ASC,\n          requested_at ASC,\n          turn_id ASC\n      `,\n  });\n\n  const getProjectionTurnByTurnId = SqlSchema.findOneOption({\n    Request: GetProjectionTurnByTurnIdInput,\n    Result: ProjectionTurnByIdDbRowSchema,\n    execute: ({ threadId, turnId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          pending_message_id AS \"pendingMessageId\",\n          source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          source_proposed_plan_id AS \"sourceProposedPlanId\",\n          assistant_message_id AS \"assistantMessageId\",\n          state,\n          requested_at AS \"requestedAt\",\n          started_at AS \"startedAt\",\n          completed_at AS \"completedAt\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"checkpointStatus\",\n          checkpoint_files_json AS \"checkpointFiles\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND turn_id = ${turnId}\n        LIMIT 1\n      `,\n  });\n\n  const clearCheckpointTurnConflictRow = SqlSchema.void({\n    Request: ClearCheckpointTurnConflictInput,\n    execute: ({ threadId, turnId, checkpointTurnCount }) =>\n      sql`\n        UPDATE projection_turns\n        SET\n          checkpoint_turn_count = NULL,\n          checkpoint_ref = NULL,\n          checkpoint_status = NULL,\n          checkpoint_files_json = '[]'\n        WHERE thread_id = ${threadId}\n          AND checkpoint_turn_count = ${checkpointTurnCount}\n          AND (turn_id IS NULL OR turn_id <> ${turnId})\n      `,\n  });\n\n  const deleteProjectionTurnsByThread = SqlSchema.void({\n    Request: DeleteProjectionTurnsByThreadInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_turns\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsertByTurnId: ProjectionTurnRepositoryShape[\"upsertByTurnId\"] = (row) =>\n    upsertProjectionTurnById(row).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionTurnRepository.upsertByTurnId:query\",\n          \"ProjectionTurnRepository.upsertByTurnId:encodeRequest\",\n        ),\n      ),\n    );\n\n  const replacePendingTurnStart: ProjectionTurnRepositoryShape[\"replacePendingTurnStart\"] = (row) =>\n    sql\n      .withTransaction(\n        clearPendingProjectionTurnsByThread({ threadId: row.threadId }).pipe(\n          Effect.flatMap(() => insertPendingProjectionTurn(row)),\n        ),\n      )\n      .pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionTurnRepository.replacePendingTurnStart:query\",\n            \"ProjectionTurnRepository.replacePendingTurnStart:encodeRequest\",\n          ),\n        ),\n      );\n\n  const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape[\"getPendingTurnStartByThreadId\"] =\n    (input) =>\n      getPendingProjectionTurn(input).pipe(\n        Effect.mapError(\n          toPersistenceSqlError(\"ProjectionTurnRepository.getPendingTurnStartByThreadId:query\"),\n        ),\n      );\n\n  const deletePendingTurnStartByThreadId: ProjectionTurnRepositoryShape[\"deletePendingTurnStartByThreadId\"] =\n    (input) =>\n      clearPendingProjectionTurnsByThread(input).pipe(\n        Effect.mapError(\n          toPersistenceSqlError(\"ProjectionTurnRepository.deletePendingTurnStartByThreadId:query\"),\n        ),\n      );\n\n  const listByThreadId: ProjectionTurnRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionTurnsByThread(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionTurnRepository.listByThreadId:query\",\n          \"ProjectionTurnRepository.listByThreadId:decodeRows\",\n        ),\n      ),\n      Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionTurn>>),\n    );\n\n  const getByTurnId: ProjectionTurnRepositoryShape[\"getByTurnId\"] = (input) =>\n    getProjectionTurnByTurnId(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionTurnRepository.getByTurnId:query\",\n          \"ProjectionTurnRepository.getByTurnId:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionTurnById>)),\n        }),\n      ),\n    );\n\n  const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape[\"clearCheckpointTurnConflict\"] =\n    (input) =>\n      clearCheckpointTurnConflictRow(input).pipe(\n        Effect.mapError(\n          toPersistenceSqlError(\"ProjectionTurnRepository.clearCheckpointTurnConflict:query\"),\n        ),\n      );\n\n  const deleteByThreadId: ProjectionTurnRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionTurnsByThread(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionTurnRepository.deleteByThreadId:query\")),\n    );\n\n  return {\n    upsertByTurnId,\n    replacePendingTurnStart,\n    getPendingTurnStartByThreadId,\n    deletePendingTurnStartByThreadId,\n    listByThreadId,\n    getByTurnId,\n    clearCheckpointTurnConflict,\n    deleteByThreadId,\n  } satisfies ProjectionTurnRepositoryShape;\n});\n\nexport const ProjectionTurnRepositoryLive = Layer.effect(\n  ProjectionTurnRepository,\n  makeProjectionTurnRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  DeleteProjectionThreadInput,\n  GetProjectionThreadInput,\n  ListProjectionThreadsByProjectInput,\n  ProjectionThread,\n  ProjectionThreadRepository,\n  type ProjectionThreadRepositoryShape,\n} from \"../Services/ProjectionThreads.ts\";\nimport { ModelSelection } from \"@t3tools/contracts\";\n\nconst ProjectionThreadDbRow = ProjectionThread.mapFields(\n  Struct.assign({\n    modelSelection: Schema.fromJsonString(ModelSelection),\n  }),\n);\ntype ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;\n\nconst makeProjectionThreadRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadRow = SqlSchema.void({\n    Request: ProjectionThread,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_threads (\n          thread_id,\n          project_id,\n          title,\n          model_selection_json,\n          runtime_mode,\n          interaction_mode,\n          branch,\n          worktree_path,\n          latest_turn_id,\n          created_at,\n          updated_at,\n          archived_at,\n          settled_override,\n          settled_at,\n          snoozed_until,\n          snoozed_at,\n          pinned_at,\n          title_regeneration_request_id,\n          title_regeneration_started_at,\n          latest_user_message_at,\n          pending_approval_count,\n          pending_user_input_count,\n          has_actionable_proposed_plan,\n          deleted_at\n        )\n        VALUES (\n          ${row.threadId},\n          ${row.projectId},\n          ${row.title},\n          ${JSON.stringify(row.modelSelection)},\n          ${row.runtimeMode},\n          ${row.interactionMode},\n          ${row.branch},\n          ${row.worktreePath},\n          ${row.latestTurnId},\n          ${row.createdAt},\n          ${row.updatedAt},\n          ${row.archivedAt},\n          ${row.settledOverride},\n          ${row.settledAt},\n          ${row.snoozedUntil},\n          ${row.snoozedAt},\n          ${row.pinnedAt},\n          ${row.titleRegenerationRequestId ?? null},\n          ${row.titleRegenerationStartedAt ?? null},\n          ${row.latestUserMessageAt},\n          ${row.pendingApprovalCount},\n          ${row.pendingUserInputCount},\n          ${row.hasActionableProposedPlan},\n          ${row.deletedAt}\n        )\n        ON CONFLICT (thread_id)\n        DO UPDATE SET\n          project_id = excluded.project_id,\n          title = excluded.title,\n          model_selection_json = excluded.model_selection_json,\n          runtime_mode = excluded.runtime_mode,\n          interaction_mode = excluded.interaction_mode,\n          branch = excluded.branch,\n          worktree_path = excluded.worktree_path,\n          latest_turn_id = excluded.latest_turn_id,\n          created_at = excluded.created_at,\n          updated_at = excluded.updated_at,\n          archived_at = excluded.archived_at,\n          settled_override = excluded.settled_override,\n          settled_at = excluded.settled_at,\n          snoozed_until = excluded.snoozed_until,\n          snoozed_at = excluded.snoozed_at,\n          pinned_at = excluded.pinned_at,\n          title_regeneration_request_id = excluded.title_regeneration_request_id,\n          title_regeneration_started_at = excluded.title_regeneration_started_at,\n          latest_user_message_at = excluded.latest_user_message_at,\n          pending_approval_count = excluded.pending_approval_count,\n          pending_user_input_count = excluded.pending_user_input_count,\n          has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,\n          deleted_at = excluded.deleted_at\n      `,\n  });\n\n  const getProjectionThreadRow = SqlSchema.findOneOption({\n    Request: GetProjectionThreadInput,\n    Result: ProjectionThreadDbRow,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const listProjectionThreadRows = SqlSchema.findAll({\n    Request: ListProjectionThreadsByProjectInput,\n    Result: ProjectionThreadDbRow,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE project_id = ${projectId}\n        ORDER BY created_at ASC, thread_id ASC\n      `,\n  });\n\n  const deleteProjectionThreadRow = SqlSchema.void({\n    Request: DeleteProjectionThreadInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_threads\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.upsert:query\")),\n    );\n\n  const getById: ProjectionThreadRepositoryShape[\"getById\"] = (input) =>\n    getProjectionThreadRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.getById:query\")),\n    );\n\n  const listByProjectId: ProjectionThreadRepositoryShape[\"listByProjectId\"] = (input) =>\n    listProjectionThreadRows(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.listByProjectId:query\")),\n    );\n\n  const deleteById: ProjectionThreadRepositoryShape[\"deleteById\"] = (input) =>\n    deleteProjectionThreadRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.deleteById:query\")),\n    );\n\n  return {\n    upsert,\n    getById,\n    listByProjectId,\n    deleteById,\n  } satisfies ProjectionThreadRepositoryShape;\n});\n\nexport const ProjectionThreadRepositoryLive = Layer.effect(\n  ProjectionThreadRepository,\n  makeProjectionThreadRepository,\n);\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodePath from \"node:path\";\n\nexport function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {\n  const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\\\]+/, \"\");\n  if (normalized.length === 0 || normalized.startsWith(\"..\") || normalized.includes(\"\\0\")) {\n    return null;\n  }\n  return normalized.replace(/\\\\/g, \"/\");\n}\n\nexport function resolveAttachmentRelativePath(input: {\n  readonly attachmentsDir: string;\n  readonly relativePath: string;\n}): string | null {\n  const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);\n  if (!normalizedRelativePath) {\n    return null;\n  }\n\n  const attachmentsRoot = NodePath.resolve(input.attachmentsDir);\n  const filePath = NodePath.resolve(NodePath.join(attachmentsRoot, normalizedRelativePath));\n  if (!filePath.startsWith(`${attachmentsRoot}${NodePath.sep}`)) {\n    return null;\n  }\n  return filePath;\n}\n","import Mime from \"@effect/platform-node/Mime\";\n\nexport const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {\n  \"image/avif\": \".avif\",\n  \"image/bmp\": \".bmp\",\n  \"image/gif\": \".gif\",\n  \"image/heic\": \".heic\",\n  \"image/heif\": \".heif\",\n  \"image/jpeg\": \".jpg\",\n  \"image/jpg\": \".jpg\",\n  \"image/png\": \".png\",\n  \"image/svg+xml\": \".svg\",\n  \"image/tiff\": \".tiff\",\n  \"image/webp\": \".webp\",\n};\n\nexport const SAFE_IMAGE_FILE_EXTENSIONS = new Set([\n  \".avif\",\n  \".bmp\",\n  \".gif\",\n  \".heic\",\n  \".heif\",\n  \".ico\",\n  \".jpeg\",\n  \".jpg\",\n  \".png\",\n  \".svg\",\n  \".tiff\",\n  \".webp\",\n]);\n\n// Whether `code` is a character the base64 payload may contain, aside from\n// the whitespace handled separately below.\nfunction isBase64Char(code: number): boolean {\n  return (\n    (code >= 0x61 && code <= 0x7a) || // a-z\n    (code >= 0x41 && code <= 0x5a) || // A-Z\n    (code >= 0x30 && code <= 0x39) || // 0-9\n    code === 0x2b || // +\n    code === 0x2f || // /\n    code === 0x3d // =\n  );\n}\n\nfunction isBase64Whitespace(code: number): boolean {\n  return code === 0x0d || code === 0x0a || code === 0x20; // \\r \\n space\n}\n\n// Data URLs carry the full image payload, so this parser must never run a\n// regex across the payload: V8's regex engine borrows the JS call stack, and\n// matching a multi-megabyte string from a deep call stack (e.g. inside fiber\n// execution) throws \"Maximum call stack size exceeded\".\nexport function parseBase64DataUrl(\n  dataUrl: string,\n): { readonly mimeType: string; readonly base64: string } | null {\n  const trimmed = dataUrl.trim();\n  if (trimmed.slice(0, 5).toLowerCase() !== \"data:\") return null;\n\n  const commaIndex = trimmed.indexOf(\",\");\n  if (commaIndex === -1) return null;\n  const header = trimmed.slice(5, commaIndex);\n  if (header.length === 0) return null;\n\n  const headerParts: Array<string> = [];\n  for (const part of header.split(\";\")) {\n    const partTrimmed = part.trim();\n    if (partTrimmed.length > 0) {\n      headerParts.push(partTrimmed);\n    }\n  }\n  if (headerParts.length < 2) {\n    return null;\n  }\n  const trailingToken = headerParts.at(-1)?.toLowerCase();\n  if (trailingToken !== \"base64\") {\n    return null;\n  }\n\n  const mimeType = headerParts[0]?.toLowerCase();\n  if (!mimeType) return null;\n\n  const payload = trimmed.slice(commaIndex + 1);\n  const runs: Array<string> = [];\n  let runStart = -1;\n  for (let index = 0; index < payload.length; index += 1) {\n    const code = payload.charCodeAt(index);\n    if (isBase64Char(code)) {\n      if (runStart === -1) runStart = index;\n      continue;\n    }\n    if (!isBase64Whitespace(code)) return null;\n    if (runStart !== -1) {\n      runs.push(payload.slice(runStart, index));\n      runStart = -1;\n    }\n  }\n  if (runStart !== -1) {\n    runs.push(payload.slice(runStart));\n  }\n  const base64 = runs.length === 1 ? runs[0]! : runs.join(\"\");\n  if (base64.length === 0 || base64.length % 4 !== 0) return null;\n  const firstPad = base64.indexOf(\"=\");\n  if (firstPad !== -1) {\n    // '=' is only valid as one or two trailing padding characters; Node's\n    // decoder would otherwise silently truncate at the first '='.\n    if (base64.length - firstPad > 2) return null;\n    for (let index = firstPad; index < base64.length; index += 1) {\n      if (base64.charCodeAt(index) !== 0x3d) return null;\n    }\n  }\n\n  return { mimeType, base64 };\n}\n\nexport function inferImageExtension(input: { mimeType: string; fileName?: string }): string {\n  const key = input.mimeType.toLowerCase();\n  const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)\n    ? IMAGE_EXTENSION_BY_MIME_TYPE[key]\n    : undefined;\n  if (fromMime) {\n    return fromMime;\n  }\n\n  const fromMimeExtension = Mime.getExtension(input.mimeType);\n  if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {\n    return fromMimeExtension;\n  }\n\n  const fileName = input.fileName?.trim() ?? \"\";\n  const extensionMatch = /\\.([a-z0-9]{1,8})$/i.exec(fileName);\n  const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : \"\";\n  if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {\n    return fileNameExtension;\n  }\n\n  return \".bin\";\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeCrypto from \"node:crypto\";\nimport * as NodeFS from \"node:fs\";\n\nimport type { ChatAttachment } from \"@t3tools/contracts\";\n\nimport {\n  normalizeAttachmentRelativePath,\n  resolveAttachmentRelativePath,\n} from \"./attachmentPaths.ts\";\nimport { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from \"./imageMime.ts\";\n\nconst ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, \".bin\"];\nconst ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;\nconst ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = \"[a-z0-9_]+(?:-[a-z0-9_]+)*\";\nconst ATTACHMENT_ID_UUID_PATTERN = \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\";\nconst ATTACHMENT_ID_PATTERN = new RegExp(\n  `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,\n  \"i\",\n);\n\nexport function toSafeThreadAttachmentSegment(threadId: string): string | null {\n  const segment = threadId\n    .trim()\n    .toLowerCase()\n    .replace(/[^a-z0-9_-]+/gi, \"-\")\n    .replace(/-+/g, \"-\")\n    .replace(/^[-_]+|[-_]+$/g, \"\")\n    .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)\n    .replace(/[-_]+$/g, \"\");\n  if (segment.length === 0) {\n    return null;\n  }\n  return segment;\n}\n\nexport function createAttachmentId(threadId: string): string | null {\n  const threadSegment = toSafeThreadAttachmentSegment(threadId);\n  if (!threadSegment) {\n    return null;\n  }\n  return `${threadSegment}-${NodeCrypto.randomUUID()}`;\n}\n\nexport function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {\n  const normalizedId = normalizeAttachmentRelativePath(attachmentId);\n  if (!normalizedId || normalizedId.includes(\"/\") || normalizedId.includes(\".\")) {\n    return null;\n  }\n  const match = normalizedId.match(ATTACHMENT_ID_PATTERN);\n  if (!match) {\n    return null;\n  }\n  return match[1]?.toLowerCase() ?? null;\n}\n\nexport function attachmentRelativePath(attachment: ChatAttachment): string {\n  switch (attachment.type) {\n    case \"image\": {\n      const extension = inferImageExtension({\n        mimeType: attachment.mimeType,\n        fileName: attachment.name,\n      });\n      return `${attachment.id}${extension}`;\n    }\n  }\n}\n\nexport function resolveAttachmentPath(input: {\n  readonly attachmentsDir: string;\n  readonly attachment: ChatAttachment;\n}): string | null {\n  return resolveAttachmentRelativePath({\n    attachmentsDir: input.attachmentsDir,\n    relativePath: attachmentRelativePath(input.attachment),\n  });\n}\n\nexport function resolveAttachmentPathById(input: {\n  readonly attachmentsDir: string;\n  readonly attachmentId: string;\n}): string | null {\n  const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);\n  if (!normalizedId || normalizedId.includes(\"/\") || normalizedId.includes(\".\")) {\n    return null;\n  }\n  for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {\n    const maybePath = resolveAttachmentRelativePath({\n      attachmentsDir: input.attachmentsDir,\n      relativePath: `${normalizedId}${extension}`,\n    });\n    if (maybePath && NodeFS.existsSync(maybePath)) {\n      return maybePath;\n    }\n  }\n  return null;\n}\n\nexport function parseAttachmentIdFromRelativePath(relativePath: string): string | null {\n  const normalized = normalizeAttachmentRelativePath(relativePath);\n  if (!normalized || normalized.includes(\"/\")) {\n    return null;\n  }\n  const extensionIndex = normalized.lastIndexOf(\".\");\n  if (extensionIndex <= 0) {\n    return null;\n  }\n  const id = normalized.slice(0, extensionIndex);\n  return id.length > 0 && !id.includes(\".\") ? id : null;\n}\n","import {\n  ApprovalRequestId,\n  type ChatAttachment,\n  type OrchestrationEvent,\n  type OrchestrationSessionStatus,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Stream from \"effect/Stream\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport { toPersistenceSqlError, type ProjectionRepositoryError } from \"../../persistence/Errors.ts\";\nimport { OrchestrationEventStore } from \"../../persistence/Services/OrchestrationEventStore.ts\";\nimport { ProjectionPendingApprovalRepository } from \"../../persistence/Services/ProjectionPendingApprovals.ts\";\nimport { ProjectionProjectRepository } from \"../../persistence/Services/ProjectionProjects.ts\";\nimport { ProjectionStateRepository } from \"../../persistence/Services/ProjectionState.ts\";\nimport { ProjectionThreadActivityRepository } from \"../../persistence/Services/ProjectionThreadActivities.ts\";\nimport { type ProjectionThreadActivity } from \"../../persistence/Services/ProjectionThreadActivities.ts\";\nimport {\n  type ProjectionThreadMessage,\n  ProjectionThreadMessageRepository,\n} from \"../../persistence/Services/ProjectionThreadMessages.ts\";\nimport {\n  type ProjectionThreadProposedPlan,\n  ProjectionThreadProposedPlanRepository,\n} from \"../../persistence/Services/ProjectionThreadProposedPlans.ts\";\nimport { ProjectionThreadSessionRepository } from \"../../persistence/Services/ProjectionThreadSessions.ts\";\nimport {\n  type ProjectionTurn,\n  ProjectionTurnRepository,\n} from \"../../persistence/Services/ProjectionTurns.ts\";\nimport { ProjectionThreadRepository } from \"../../persistence/Services/ProjectionThreads.ts\";\nimport { ProjectionPendingApprovalRepositoryLive } from \"../../persistence/Layers/ProjectionPendingApprovals.ts\";\nimport { ProjectionProjectRepositoryLive } from \"../../persistence/Layers/ProjectionProjects.ts\";\nimport { ProjectionStateRepositoryLive } from \"../../persistence/Layers/ProjectionState.ts\";\nimport { ProjectionThreadActivityRepositoryLive } from \"../../persistence/Layers/ProjectionThreadActivities.ts\";\nimport { ProjectionThreadMessageRepositoryLive } from \"../../persistence/Layers/ProjectionThreadMessages.ts\";\nimport { ProjectionThreadProposedPlanRepositoryLive } from \"../../persistence/Layers/ProjectionThreadProposedPlans.ts\";\nimport { ProjectionThreadSessionRepositoryLive } from \"../../persistence/Layers/ProjectionThreadSessions.ts\";\nimport { ProjectionTurnRepositoryLive } from \"../../persistence/Layers/ProjectionTurns.ts\";\nimport { ProjectionThreadRepositoryLive } from \"../../persistence/Layers/ProjectionThreads.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport {\n  OrchestrationProjectionPipeline,\n  type OrchestrationProjectionPipelineShape,\n} from \"../Services/ProjectionPipeline.ts\";\nimport {\n  attachmentRelativePath,\n  parseAttachmentIdFromRelativePath,\n  parseThreadSegmentFromAttachmentId,\n  toSafeThreadAttachmentSegment,\n} from \"../../attachmentStore.ts\";\n\nexport const ORCHESTRATION_PROJECTOR_NAMES = {\n  projects: \"projection.projects\",\n  threads: \"projection.threads\",\n  threadMessages: \"projection.thread-messages\",\n  threadProposedPlans: \"projection.thread-proposed-plans\",\n  threadActivities: \"projection.thread-activities\",\n  threadSessions: \"projection.thread-sessions\",\n  threadTurns: \"projection.thread-turns\",\n  checkpoints: \"projection.checkpoints\",\n  pendingApprovals: \"projection.pending-approvals\",\n} as const;\n\ntype ProjectorName =\n  (typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];\n\n/**\n * Turn state to settle still-running turns with when their session leaves the\n * \"running\" status, or null while the session is (re)starting or running and\n * turns must stay unsettled.\n */\nfunction settledTurnStateForSessionStatus(\n  status: OrchestrationSessionStatus,\n): \"completed\" | \"interrupted\" | \"error\" | null {\n  switch (status) {\n    case \"idle\":\n    case \"ready\":\n      return \"completed\";\n    case \"error\":\n      return \"error\";\n    case \"interrupted\":\n    case \"stopped\":\n      return \"interrupted\";\n    case \"starting\":\n    case \"running\":\n      return null;\n  }\n}\n\ninterface ProjectorDefinition {\n  readonly name: ProjectorName;\n  readonly apply: (\n    event: OrchestrationEvent,\n    attachmentSideEffects: AttachmentSideEffects,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\ninterface AttachmentSideEffects {\n  readonly deletedThreadIds: Set<string>;\n  readonly prunedThreadRelativePaths: Map<string, Set<string>>;\n}\n\nconst materializeAttachmentsForProjection = Effect.fn(\"materializeAttachmentsForProjection\")(\n  (input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>\n    Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),\n);\n\nfunction extractActivityRequestId(payload: unknown): ApprovalRequestId | null {\n  if (typeof payload !== \"object\" || payload === null) {\n    return null;\n  }\n  const requestId = (payload as Record<string, unknown>).requestId;\n  return typeof requestId === \"string\" ? ApprovalRequestId.make(requestId) : null;\n}\n\nfunction isStalePendingApprovalFailureDetail(detail: string | null): boolean {\n  if (detail === null) {\n    return false;\n  }\n  return (\n    detail.includes(\"stale pending approval request\") ||\n    detail.includes(\"unknown pending approval request\") ||\n    detail.includes(\"unknown pending permission request\")\n  );\n}\n\nfunction derivePendingUserInputCountFromActivities(\n  activities: ReadonlyArray<ProjectionThreadActivity>,\n): number {\n  const openRequestIds = new Set<string>();\n  const ordered = [...activities].toSorted(\n    (left, right) =>\n      left.createdAt.localeCompare(right.createdAt) ||\n      left.activityId.localeCompare(right.activityId),\n  );\n\n  for (const activity of ordered) {\n    const requestId = extractActivityRequestId(activity.payload);\n    if (requestId === null) {\n      continue;\n    }\n    const payload =\n      typeof activity.payload === \"object\" && activity.payload !== null\n        ? (activity.payload as Record<string, unknown>)\n        : null;\n    const detail = typeof payload?.detail === \"string\" ? payload.detail.toLowerCase() : null;\n\n    if (activity.kind === \"user-input.requested\") {\n      openRequestIds.add(requestId);\n      continue;\n    }\n\n    if (activity.kind === \"user-input.resolved\") {\n      openRequestIds.delete(requestId);\n      continue;\n    }\n\n    if (\n      activity.kind === \"provider.user-input.respond.failed\" &&\n      detail !== null &&\n      (detail.includes(\"stale pending user-input request\") ||\n        detail.includes(\"unknown pending user-input request\") ||\n        detail.includes(\"unknown pending user input request\") ||\n        detail.includes(\"unknown pending codex user input request\"))\n    ) {\n      openRequestIds.delete(requestId);\n    }\n  }\n\n  return openRequestIds.size;\n}\n\nfunction deriveHasActionableProposedPlan(input: {\n  readonly latestTurnId: string | null;\n  readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;\n}): boolean {\n  const sorted = [...input.proposedPlans].toSorted(\n    (left, right) =>\n      left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),\n  );\n\n  let latestForTurn: ProjectionThreadProposedPlan | null = null;\n  if (input.latestTurnId !== null) {\n    for (let index = sorted.length - 1; index >= 0; index -= 1) {\n      const plan = sorted[index];\n      if (plan?.turnId === input.latestTurnId) {\n        latestForTurn = plan;\n        break;\n      }\n    }\n  }\n  if (latestForTurn !== null) {\n    return latestForTurn.implementedAt === null;\n  }\n\n  const latestPlan = sorted.at(-1) ?? null;\n  return latestPlan !== null && latestPlan.implementedAt === null;\n}\n\nfunction retainProjectionMessagesAfterRevert(\n  messages: ReadonlyArray<ProjectionThreadMessage>,\n  turns: ReadonlyArray<ProjectionTurn>,\n  turnCount: number,\n): ReadonlyArray<ProjectionThreadMessage> {\n  const retainedMessageIds = new Set<string>();\n  const retainedTurnIds = new Set<string>();\n  const keptTurns = turns.filter(\n    (turn) =>\n      turn.turnId !== null &&\n      turn.checkpointTurnCount !== null &&\n      turn.checkpointTurnCount <= turnCount,\n  );\n  for (const turn of keptTurns) {\n    if (turn.turnId !== null) {\n      retainedTurnIds.add(turn.turnId);\n    }\n    if (turn.pendingMessageId !== null) {\n      retainedMessageIds.add(turn.pendingMessageId);\n    }\n    if (turn.assistantMessageId !== null) {\n      retainedMessageIds.add(turn.assistantMessageId);\n    }\n  }\n\n  for (const message of messages) {\n    if (message.role === \"system\") {\n      retainedMessageIds.add(message.messageId);\n      continue;\n    }\n    if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {\n      retainedMessageIds.add(message.messageId);\n    }\n  }\n\n  const retainedUserCount = messages.filter(\n    (message) => message.role === \"user\" && retainedMessageIds.has(message.messageId),\n  ).length;\n  const missingUserCount = Math.max(0, turnCount - retainedUserCount);\n  if (missingUserCount > 0) {\n    const fallbackUserMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"user\" &&\n          !retainedMessageIds.has(message.messageId) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) ||\n          left.messageId.localeCompare(right.messageId),\n      )\n      .slice(0, missingUserCount);\n    for (const message of fallbackUserMessages) {\n      retainedMessageIds.add(message.messageId);\n    }\n  }\n\n  const retainedAssistantCount = messages.filter(\n    (message) => message.role === \"assistant\" && retainedMessageIds.has(message.messageId),\n  ).length;\n  const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);\n  if (missingAssistantCount > 0) {\n    const fallbackAssistantMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"assistant\" &&\n          !retainedMessageIds.has(message.messageId) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) ||\n          left.messageId.localeCompare(right.messageId),\n      )\n      .slice(0, missingAssistantCount);\n    for (const message of fallbackAssistantMessages) {\n      retainedMessageIds.add(message.messageId);\n    }\n  }\n\n  return messages.filter((message) => retainedMessageIds.has(message.messageId));\n}\n\nfunction retainProjectionActivitiesAfterRevert(\n  activities: ReadonlyArray<ProjectionThreadActivity>,\n  turns: ReadonlyArray<ProjectionTurn>,\n  turnCount: number,\n): ReadonlyArray<ProjectionThreadActivity> {\n  const retainedTurnIds = new Set<string>(\n    turns\n      .filter(\n        (turn) =>\n          turn.turnId !== null &&\n          turn.checkpointTurnCount !== null &&\n          turn.checkpointTurnCount <= turnCount,\n      )\n      .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),\n  );\n  return activities.filter(\n    (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),\n  );\n}\n\nfunction retainProjectionProposedPlansAfterRevert(\n  proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>,\n  turns: ReadonlyArray<ProjectionTurn>,\n  turnCount: number,\n): ReadonlyArray<ProjectionThreadProposedPlan> {\n  const retainedTurnIds = new Set<string>(\n    turns\n      .filter(\n        (turn) =>\n          turn.turnId !== null &&\n          turn.checkpointTurnCount !== null &&\n          turn.checkpointTurnCount <= turnCount,\n      )\n      .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),\n  );\n  return proposedPlans.filter(\n    (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),\n  );\n}\n\nfunction collectThreadAttachmentRelativePaths(\n  threadId: string,\n  messages: ReadonlyArray<ProjectionThreadMessage>,\n): Set<string> {\n  const threadSegment = toSafeThreadAttachmentSegment(threadId);\n  if (!threadSegment) {\n    return new Set();\n  }\n  const relativePaths = new Set<string>();\n  for (const message of messages) {\n    for (const attachment of message.attachments ?? []) {\n      if (attachment.type !== \"image\") {\n        continue;\n      }\n      const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);\n      if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {\n        continue;\n      }\n      relativePaths.add(attachmentRelativePath(attachment));\n    }\n  }\n  return relativePaths;\n}\n\nconst runAttachmentSideEffects = Effect.fn(\"runAttachmentSideEffects\")(function* (\n  sideEffects: AttachmentSideEffects,\n) {\n  const serverConfig = yield* Effect.service(ServerConfig);\n  const fileSystem = yield* Effect.service(FileSystem.FileSystem);\n  const path = yield* Effect.service(Path.Path);\n\n  const attachmentsRootDir = serverConfig.attachmentsDir;\n  const readAttachmentRootEntries = fileSystem\n    .readDirectory(attachmentsRootDir, { recursive: false })\n    .pipe(Effect.orElseSucceed(() => [] as Array<string>));\n\n  const removeDeletedThreadAttachmentEntry = Effect.fn(\"removeDeletedThreadAttachmentEntry\")(\n    function* (threadSegment: string, entry: string) {\n      const normalizedEntry = entry.replace(/^[/\\\\]+/, \"\").replace(/\\\\/g, \"/\");\n      if (normalizedEntry.length === 0 || normalizedEntry.includes(\"/\")) {\n        return;\n      }\n      const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);\n      if (!attachmentId) {\n        return;\n      }\n      const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);\n      if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {\n        return;\n      }\n      yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {\n        force: true,\n      });\n    },\n  );\n\n  const deleteThreadAttachments = Effect.fn(\"deleteThreadAttachments\")(function* (\n    threadId: string,\n  ) {\n    const threadSegment = toSafeThreadAttachmentSegment(threadId);\n    if (!threadSegment) {\n      yield* Effect.logWarning(\"skipping attachment cleanup for unsafe thread id\", {\n        threadId,\n      });\n      return;\n    }\n\n    const entries = yield* readAttachmentRootEntries;\n    yield* Effect.forEach(\n      entries,\n      (entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry),\n      {\n        concurrency: 1,\n      },\n    );\n  });\n\n  const pruneThreadAttachmentEntry = Effect.fn(\"pruneThreadAttachmentEntry\")(function* (\n    threadSegment: string,\n    keptThreadRelativePaths: Set<string>,\n    entry: string,\n  ) {\n    const relativePath = entry.replace(/^[/\\\\]+/, \"\").replace(/\\\\/g, \"/\");\n    if (relativePath.length === 0 || relativePath.includes(\"/\")) {\n      return;\n    }\n    const attachmentId = parseAttachmentIdFromRelativePath(relativePath);\n    if (!attachmentId) {\n      return;\n    }\n    const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);\n    if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {\n      return;\n    }\n\n    const absolutePath = path.join(attachmentsRootDir, relativePath);\n    const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));\n    if (!fileInfo || fileInfo.type !== \"File\") {\n      return;\n    }\n\n    if (!keptThreadRelativePaths.has(relativePath)) {\n      yield* fileSystem.remove(absolutePath, { force: true });\n    }\n  });\n\n  const pruneThreadAttachments = Effect.fn(\"pruneThreadAttachments\")(function* (\n    threadId: string,\n    keptThreadRelativePaths: Set<string>,\n  ) {\n    if (sideEffects.deletedThreadIds.has(threadId)) {\n      return;\n    }\n\n    const threadSegment = toSafeThreadAttachmentSegment(threadId);\n    if (!threadSegment) {\n      yield* Effect.logWarning(\"skipping attachment prune for unsafe thread id\", { threadId });\n      return;\n    }\n\n    const entries = yield* readAttachmentRootEntries;\n    yield* Effect.forEach(\n      entries,\n      (entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry),\n      { concurrency: 1 },\n    );\n  });\n\n  yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, {\n    concurrency: 1,\n  });\n\n  yield* Effect.forEach(\n    sideEffects.prunedThreadRelativePaths.entries(),\n    ([threadId, keptThreadRelativePaths]) =>\n      pruneThreadAttachments(threadId, keptThreadRelativePaths),\n    { concurrency: 1 },\n  );\n});\n\nconst makeOrchestrationProjectionPipeline = Effect.fn(\"makeOrchestrationProjectionPipeline\")(\n  function* () {\n    const sql = yield* SqlClient.SqlClient;\n    const eventStore = yield* OrchestrationEventStore;\n    const projectionStateRepository = yield* ProjectionStateRepository;\n    const projectionProjectRepository = yield* ProjectionProjectRepository;\n    const projectionThreadRepository = yield* ProjectionThreadRepository;\n    const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;\n    const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;\n    const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;\n    const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;\n    const projectionTurnRepository = yield* ProjectionTurnRepository;\n    const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;\n\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const serverConfig = yield* ServerConfig;\n\n    const applyProjectsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyProjectsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"project.created\":\n          yield* projectionProjectRepository.upsert({\n            projectId: event.payload.projectId,\n            title: event.payload.title,\n            workspaceRoot: event.payload.workspaceRoot,\n            defaultModelSelection: event.payload.defaultModelSelection,\n            scripts: event.payload.scripts,\n            createdAt: event.payload.createdAt,\n            updatedAt: event.payload.updatedAt,\n            deletedAt: null,\n          });\n          return;\n\n        case \"project.meta-updated\": {\n          const existingRow = yield* projectionProjectRepository.getById({\n            projectId: event.payload.projectId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionProjectRepository.upsert({\n            ...existingRow.value,\n            ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),\n            ...(event.payload.workspaceRoot !== undefined\n              ? { workspaceRoot: event.payload.workspaceRoot }\n              : {}),\n            ...(event.payload.defaultModelSelection !== undefined\n              ? { defaultModelSelection: event.payload.defaultModelSelection }\n              : {}),\n            ...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"project.deleted\": {\n          const existingRow = yield* projectionProjectRepository.getById({\n            projectId: event.payload.projectId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionProjectRepository.upsert({\n            ...existingRow.value,\n            deletedAt: event.payload.deletedAt,\n            updatedAt: event.payload.deletedAt,\n          });\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const refreshThreadShellSummary = Effect.fn(\"refreshThreadShellSummary\")(function* (\n      threadId: ThreadId,\n    ) {\n      const existingRow = yield* projectionThreadRepository.getById({\n        threadId,\n      });\n      if (Option.isNone(existingRow)) {\n        return;\n      }\n\n      const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([\n        projectionThreadMessageRepository.listByThreadId({ threadId }),\n        projectionThreadProposedPlanRepository.listByThreadId({ threadId }),\n        projectionThreadActivityRepository.listByThreadId({ threadId }),\n        projectionPendingApprovalRepository.listByThreadId({ threadId }),\n      ]);\n\n      let latestUserMessageAt: string | null = null;\n      for (const message of messages) {\n        if (\n          message.role === \"user\" &&\n          (latestUserMessageAt === null || message.createdAt > latestUserMessageAt)\n        ) {\n          latestUserMessageAt = message.createdAt;\n        }\n      }\n\n      const pendingApprovalCount = pendingApprovals.filter(\n        (approval) => approval.status === \"pending\",\n      ).length;\n      const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);\n      const hasActionableProposedPlan = deriveHasActionableProposedPlan({\n        latestTurnId: existingRow.value.latestTurnId,\n        proposedPlans,\n      });\n\n      yield* projectionThreadRepository.upsert({\n        ...existingRow.value,\n        latestUserMessageAt,\n        pendingApprovalCount,\n        pendingUserInputCount,\n        hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,\n      });\n    });\n\n    const applyThreadsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadsProjection\",\n    )(function* (event, attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.created\":\n          yield* projectionThreadRepository.upsert({\n            threadId: event.payload.threadId,\n            projectId: event.payload.projectId,\n            title: event.payload.title,\n            modelSelection: event.payload.modelSelection,\n            runtimeMode: event.payload.runtimeMode,\n            interactionMode: event.payload.interactionMode,\n            branch: event.payload.branch,\n            worktreePath: event.payload.worktreePath,\n            latestTurnId: null,\n            createdAt: event.payload.createdAt,\n            updatedAt: event.payload.updatedAt,\n            archivedAt: null,\n            settledOverride: null,\n            settledAt: null,\n            snoozedUntil: null,\n            snoozedAt: null,\n            pinnedAt: null,\n            titleRegenerationRequestId: null,\n            titleRegenerationStartedAt: null,\n            latestUserMessageAt: null,\n            pendingApprovalCount: 0,\n            pendingUserInputCount: 0,\n            hasActionableProposedPlan: 0,\n            deletedAt: null,\n          });\n          return;\n\n        case \"thread.archived\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            archivedAt: event.payload.archivedAt,\n            titleRegenerationRequestId: null,\n            titleRegenerationStartedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unarchived\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            archivedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.settled\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            settledOverride: \"settled\",\n            settledAt: event.payload.settledAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unsettled\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            settledOverride: event.payload.reason === \"user\" ? \"active\" : null,\n            settledAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.snoozed\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            snoozedUntil: event.payload.snoozedUntil,\n            snoozedAt: event.payload.snoozedAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unsnoozed\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            snoozedUntil: null,\n            snoozedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.pinned\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            pinnedAt: event.payload.pinnedAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unpinned\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            pinnedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.meta-updated\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),\n            ...(event.payload.titleRegeneration !== undefined\n              ? {\n                  titleRegenerationRequestId: event.payload.titleRegeneration?.requestId ?? null,\n                  titleRegenerationStartedAt: event.payload.titleRegeneration?.startedAt ?? null,\n                }\n              : {}),\n            ...(event.payload.modelSelection !== undefined\n              ? { modelSelection: event.payload.modelSelection }\n              : {}),\n            ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),\n            ...(event.payload.worktreePath !== undefined\n              ? { worktreePath: event.payload.worktreePath }\n              : {}),\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.runtime-mode-set\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            runtimeMode: event.payload.runtimeMode,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.interaction-mode-set\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            interactionMode: event.payload.interactionMode,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.deleted\": {\n          attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            deletedAt: event.payload.deletedAt,\n            updatedAt: event.payload.deletedAt,\n          });\n          return;\n        }\n\n        case \"thread.message-sent\":\n        case \"thread.proposed-plan-upserted\":\n        case \"thread.activity-appended\":\n        case \"thread.approval-response-requested\":\n        case \"thread.user-input-response-requested\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        case \"thread.session-set\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            latestTurnId: event.payload.session.activeTurnId,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        case \"thread.turn-diff-completed\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            latestTurnId: event.payload.turnId,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        case \"thread.reverted\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n\n          const retainedTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          let latestTurnId: ProjectionTurn[\"turnId\"] = null;\n          let latestCheckpointTurnCount = -1;\n          for (let index = 0; index < retainedTurns.length; index += 1) {\n            const turn = retainedTurns[index];\n            if (\n              !turn ||\n              turn.turnId === null ||\n              turn.checkpointTurnCount === null ||\n              turn.checkpointTurnCount > event.payload.turnCount\n            ) {\n              continue;\n            }\n            if (turn.checkpointTurnCount > latestCheckpointTurnCount) {\n              latestCheckpointTurnCount = turn.checkpointTurnCount;\n              latestTurnId = turn.turnId;\n            }\n          }\n\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            latestTurnId,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadMessagesProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadMessagesProjection\",\n    )(function* (event, attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.message-sent\": {\n          const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({\n            messageId: event.payload.messageId,\n          });\n          const previousMessage = Option.getOrUndefined(existingMessage);\n          const nextText = Option.match(existingMessage, {\n            onNone: () => event.payload.text,\n            onSome: (message) => {\n              if (event.payload.streaming) {\n                return `${message.text}${event.payload.text}`;\n              }\n              if (event.payload.text.length === 0) {\n                return message.text;\n              }\n              return event.payload.text;\n            },\n          });\n          const nextAttachments =\n            event.payload.attachments !== undefined\n              ? yield* materializeAttachmentsForProjection({\n                  attachments: event.payload.attachments,\n                })\n              : previousMessage?.attachments;\n          yield* projectionThreadMessageRepository.upsert({\n            messageId: event.payload.messageId,\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n            role: event.payload.role,\n            text: nextText,\n            ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),\n            isStreaming: event.payload.streaming,\n            createdAt: previousMessage?.createdAt ?? event.payload.createdAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.reverted\": {\n          const existingRows = yield* projectionThreadMessageRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (existingRows.length === 0) {\n            return;\n          }\n\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptRows = retainProjectionMessagesAfterRevert(\n            existingRows,\n            existingTurns,\n            event.payload.turnCount,\n          );\n          if (keptRows.length === existingRows.length) {\n            return;\n          }\n\n          yield* projectionThreadMessageRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {\n            concurrency: 1,\n          }).pipe(Effect.asVoid);\n          attachmentSideEffects.prunedThreadRelativePaths.set(\n            event.payload.threadId,\n            collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),\n          );\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadProposedPlansProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadProposedPlansProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.proposed-plan-upserted\":\n          yield* projectionThreadProposedPlanRepository.upsert({\n            planId: event.payload.proposedPlan.id,\n            threadId: event.payload.threadId,\n            turnId: event.payload.proposedPlan.turnId,\n            planMarkdown: event.payload.proposedPlan.planMarkdown,\n            implementedAt: event.payload.proposedPlan.implementedAt,\n            implementationThreadId: event.payload.proposedPlan.implementationThreadId,\n            createdAt: event.payload.proposedPlan.createdAt,\n            updatedAt: event.payload.proposedPlan.updatedAt,\n          });\n          return;\n\n        case \"thread.reverted\": {\n          const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (existingRows.length === 0) {\n            return;\n          }\n\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptRows = retainProjectionProposedPlansAfterRevert(\n            existingRows,\n            existingTurns,\n            event.payload.turnCount,\n          );\n          if (keptRows.length === existingRows.length) {\n            return;\n          }\n\n          yield* projectionThreadProposedPlanRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, {\n            concurrency: 1,\n          }).pipe(Effect.asVoid);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadActivitiesProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadActivitiesProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.activity-appended\":\n          yield* projectionThreadActivityRepository.upsert({\n            activityId: event.payload.activity.id,\n            threadId: event.payload.threadId,\n            turnId: event.payload.activity.turnId,\n            tone: event.payload.activity.tone,\n            kind: event.payload.activity.kind,\n            summary: event.payload.activity.summary,\n            payload: event.payload.activity.payload,\n            ...(event.payload.activity.sequence !== undefined\n              ? { sequence: event.payload.activity.sequence }\n              : {}),\n            createdAt: event.payload.activity.createdAt,\n          });\n          return;\n\n        case \"thread.reverted\": {\n          const existingRows = yield* projectionThreadActivityRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (existingRows.length === 0) {\n            return;\n          }\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptRows = retainProjectionActivitiesAfterRevert(\n            existingRows,\n            existingTurns,\n            event.payload.turnCount,\n          );\n          if (keptRows.length === existingRows.length) {\n            return;\n          }\n          yield* projectionThreadActivityRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {\n            concurrency: 1,\n          }).pipe(Effect.asVoid);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadSessionsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadSessionsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      if (event.type !== \"thread.session-set\") {\n        return;\n      }\n      yield* projectionThreadSessionRepository.upsert({\n        threadId: event.payload.threadId,\n        status: event.payload.session.status,\n        providerName: event.payload.session.providerName,\n        providerInstanceId: event.payload.session.providerInstanceId ?? null,\n        runtimeMode: event.payload.session.runtimeMode,\n        activeTurnId: event.payload.session.activeTurnId,\n        lastError: event.payload.session.lastError,\n        updatedAt: event.payload.session.updatedAt,\n      });\n    });\n\n    const applyThreadTurnsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadTurnsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.turn-start-requested\": {\n          yield* projectionTurnRepository.replacePendingTurnStart({\n            threadId: event.payload.threadId,\n            messageId: event.payload.messageId,\n            sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,\n            sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,\n            requestedAt: event.payload.createdAt,\n          });\n          return;\n        }\n\n        case \"thread.session-set\": {\n          const turnId = event.payload.session.activeTurnId;\n          if (turnId === null || event.payload.session.status !== \"running\") {\n            if (\n              event.payload.session.status === \"error\" ||\n              event.payload.session.status === \"stopped\" ||\n              event.payload.session.status === \"interrupted\"\n            ) {\n              yield* projectionTurnRepository.deletePendingTurnStartByThreadId({\n                threadId: event.payload.threadId,\n              });\n            }\n            // Leaving the \"running\" session status is the turn-end signal:\n            // settle still-running turns so their duration reflects the whole\n            // turn rather than the last assistant message.\n            const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);\n            if (settledTurnState === null) {\n              return;\n            }\n            const existingTurns = yield* projectionTurnRepository.listByThreadId({\n              threadId: event.payload.threadId,\n            });\n            yield* Effect.forEach(\n              existingTurns.filter((turn) => turn.turnId !== null && turn.state === \"running\"),\n              (turn) =>\n                turn.turnId === null\n                  ? Effect.void\n                  : projectionTurnRepository.upsertByTurnId({\n                      ...turn,\n                      turnId: turn.turnId,\n                      state: settledTurnState,\n                      // A running turn's completedAt can only hold a mid-turn\n                      // placeholder checkpoint timestamp — the session leaving\n                      // \"running\" is the authoritative turn end.\n                      completedAt: event.payload.session.updatedAt,\n                    }),\n              { concurrency: 1 },\n            );\n            return;\n          }\n\n          // A new active turn supersedes any still-running turn on the same\n          // thread — steering can open a new turn without the provider ever\n          // completing the previous one.\n          const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(\n            otherRunningTurns.filter(\n              (turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === \"running\",\n            ),\n            (turn) =>\n              turn.turnId === null\n                ? Effect.void\n                : projectionTurnRepository.upsertByTurnId({\n                    ...turn,\n                    turnId: turn.turnId,\n                    state: \"completed\",\n                    completedAt: event.payload.session.updatedAt,\n                  }),\n            { concurrency: 1 },\n          );\n\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId,\n          });\n          const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isSome(existingTurn)) {\n            const nextState =\n              existingTurn.value.state === \"completed\" || existingTurn.value.state === \"error\"\n                ? existingTurn.value.state\n                : \"running\";\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              state: nextState,\n              pendingMessageId:\n                existingTurn.value.pendingMessageId ??\n                (Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),\n              sourceProposedPlanThreadId:\n                existingTurn.value.sourceProposedPlanThreadId ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.sourceProposedPlanThreadId\n                  : null),\n              sourceProposedPlanId:\n                existingTurn.value.sourceProposedPlanId ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.sourceProposedPlanId\n                  : null),\n              startedAt:\n                existingTurn.value.startedAt ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.requestedAt\n                  : event.occurredAt),\n              requestedAt:\n                existingTurn.value.requestedAt ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.requestedAt\n                  : event.occurredAt),\n            });\n          } else {\n            yield* projectionTurnRepository.upsertByTurnId({\n              turnId,\n              threadId: event.payload.threadId,\n              pendingMessageId: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.messageId\n                : null,\n              sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.sourceProposedPlanThreadId\n                : null,\n              sourceProposedPlanId: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.sourceProposedPlanId\n                : null,\n              assistantMessageId: null,\n              state: \"running\",\n              requestedAt: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.requestedAt\n                : event.occurredAt,\n              startedAt: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.requestedAt\n                : event.occurredAt,\n              completedAt: null,\n              checkpointTurnCount: null,\n              checkpointRef: null,\n              checkpointStatus: null,\n              checkpointFiles: [],\n            });\n          }\n\n          yield* projectionTurnRepository.deletePendingTurnStartByThreadId({\n            threadId: event.payload.threadId,\n          });\n          return;\n        }\n\n        case \"thread.message-sent\": {\n          if (event.payload.turnId === null || event.payload.role !== \"assistant\") {\n            return;\n          }\n          // A completed assistant message only settles the turn once the\n          // session is no longer running it — providers may emit several\n          // assistant messages per turn (commentary between tool calls), and\n          // the turn must stay unsettled until the provider reports turn end\n          // (projected as thread.session-set leaving the \"running\" status).\n          const session = yield* projectionThreadSessionRepository.getByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const turnStillRunning =\n            Option.isSome(session) &&\n            session.value.status === \"running\" &&\n            session.value.activeTurnId === event.payload.turnId;\n          const settlesTurn = !event.payload.streaming && !turnStillRunning;\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n          });\n          if (Option.isSome(existingTurn)) {\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              assistantMessageId: event.payload.messageId,\n              state: settlesTurn\n                ? existingTurn.value.state === \"interrupted\"\n                  ? \"interrupted\"\n                  : existingTurn.value.state === \"error\"\n                    ? \"error\"\n                    : \"completed\"\n                : existingTurn.value.state,\n              completedAt: settlesTurn\n                ? (existingTurn.value.completedAt ?? event.payload.updatedAt)\n                : existingTurn.value.completedAt,\n              startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,\n              requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,\n            });\n            return;\n          }\n          yield* projectionTurnRepository.upsertByTurnId({\n            turnId: event.payload.turnId,\n            threadId: event.payload.threadId,\n            pendingMessageId: null,\n            sourceProposedPlanThreadId: null,\n            sourceProposedPlanId: null,\n            assistantMessageId: event.payload.messageId,\n            state: settlesTurn ? \"completed\" : \"running\",\n            requestedAt: event.payload.createdAt,\n            startedAt: event.payload.createdAt,\n            completedAt: settlesTurn ? event.payload.updatedAt : null,\n            checkpointTurnCount: null,\n            checkpointRef: null,\n            checkpointStatus: null,\n            checkpointFiles: [],\n          });\n          return;\n        }\n\n        case \"thread.turn-interrupt-requested\": {\n          if (event.payload.turnId === undefined) {\n            return;\n          }\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n          });\n          if (Option.isSome(existingTurn)) {\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              state: \"interrupted\",\n              completedAt: existingTurn.value.completedAt ?? event.payload.createdAt,\n              startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,\n              requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,\n            });\n            return;\n          }\n          yield* projectionTurnRepository.upsertByTurnId({\n            turnId: event.payload.turnId,\n            threadId: event.payload.threadId,\n            pendingMessageId: null,\n            sourceProposedPlanThreadId: null,\n            sourceProposedPlanId: null,\n            assistantMessageId: null,\n            state: \"interrupted\",\n            requestedAt: event.payload.createdAt,\n            startedAt: event.payload.createdAt,\n            completedAt: event.payload.createdAt,\n            checkpointTurnCount: null,\n            checkpointRef: null,\n            checkpointStatus: null,\n            checkpointFiles: [],\n          });\n          return;\n        }\n\n        case \"thread.turn-diff-completed\": {\n          // Mid-turn diff updates produce placeholder checkpoints; record the\n          // checkpoint, but don't settle a turn its session is still running.\n          const session = yield* projectionThreadSessionRepository.getByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const turnStillRunning =\n            Option.isSome(session) &&\n            session.value.status === \"running\" &&\n            session.value.activeTurnId === event.payload.turnId;\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n          });\n          const nextState = event.payload.status === \"error\" ? \"error\" : \"completed\";\n          yield* projectionTurnRepository.clearCheckpointTurnConflict({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n            checkpointTurnCount: event.payload.checkpointTurnCount,\n          });\n\n          if (Option.isSome(existingTurn)) {\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              assistantMessageId: event.payload.assistantMessageId,\n              state: turnStillRunning ? existingTurn.value.state : nextState,\n              checkpointTurnCount: event.payload.checkpointTurnCount,\n              checkpointRef: event.payload.checkpointRef,\n              checkpointStatus: event.payload.status,\n              checkpointFiles: event.payload.files,\n              startedAt: existingTurn.value.startedAt ?? event.payload.completedAt,\n              requestedAt: existingTurn.value.requestedAt ?? event.payload.completedAt,\n              completedAt: event.payload.completedAt,\n            });\n            return;\n          }\n          yield* projectionTurnRepository.upsertByTurnId({\n            turnId: event.payload.turnId,\n            threadId: event.payload.threadId,\n            pendingMessageId: null,\n            sourceProposedPlanThreadId: null,\n            sourceProposedPlanId: null,\n            assistantMessageId: event.payload.assistantMessageId,\n            state: turnStillRunning ? \"running\" : nextState,\n            requestedAt: event.payload.completedAt,\n            startedAt: event.payload.completedAt,\n            completedAt: event.payload.completedAt,\n            checkpointTurnCount: event.payload.checkpointTurnCount,\n            checkpointRef: event.payload.checkpointRef,\n            checkpointStatus: event.payload.status,\n            checkpointFiles: event.payload.files,\n          });\n          return;\n        }\n\n        case \"thread.reverted\": {\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptTurns = existingTurns.filter(\n            (turn) =>\n              turn.turnId !== null &&\n              turn.checkpointTurnCount !== null &&\n              turn.checkpointTurnCount <= event.payload.turnCount,\n          );\n          yield* projectionTurnRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(\n            keptTurns,\n            (turn) =>\n              turn.turnId === null\n                ? Effect.void\n                : projectionTurnRepository.upsertByTurnId({\n                    ...turn,\n                    turnId: turn.turnId,\n                  }),\n            { concurrency: 1 },\n          ).pipe(Effect.asVoid);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyCheckpointsProjection: ProjectorDefinition[\"apply\"] = () => Effect.void;\n\n    const applyPendingApprovalsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyPendingApprovalsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.activity-appended\": {\n          const requestId =\n            extractActivityRequestId(event.payload.activity.payload) ??\n            event.metadata.requestId ??\n            null;\n          if (requestId === null) {\n            return;\n          }\n          const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({\n            requestId,\n          });\n          if (event.payload.activity.kind === \"approval.resolved\") {\n            const resolvedDecisionRaw =\n              typeof event.payload.activity.payload === \"object\" &&\n              event.payload.activity.payload !== null &&\n              \"decision\" in event.payload.activity.payload\n                ? (event.payload.activity.payload as { decision?: unknown }).decision\n                : null;\n            const resolvedDecision =\n              resolvedDecisionRaw === \"accept\" ||\n              resolvedDecisionRaw === \"acceptForSession\" ||\n              resolvedDecisionRaw === \"decline\" ||\n              resolvedDecisionRaw === \"cancel\"\n                ? resolvedDecisionRaw\n                : null;\n            yield* projectionPendingApprovalRepository.upsert({\n              requestId,\n              threadId: Option.isSome(existingRow)\n                ? existingRow.value.threadId\n                : event.payload.threadId,\n              turnId: Option.isSome(existingRow)\n                ? existingRow.value.turnId\n                : event.payload.activity.turnId,\n              status: \"resolved\",\n              decision: resolvedDecision,\n              createdAt: Option.isSome(existingRow)\n                ? existingRow.value.createdAt\n                : event.payload.activity.createdAt,\n              resolvedAt: event.payload.activity.createdAt,\n            });\n            return;\n          }\n          if (event.payload.activity.kind === \"provider.approval.respond.failed\") {\n            const payload =\n              typeof event.payload.activity.payload === \"object\" &&\n              event.payload.activity.payload !== null\n                ? (event.payload.activity.payload as Record<string, unknown>)\n                : null;\n            const detail =\n              typeof payload?.detail === \"string\" ? payload.detail.toLowerCase() : null;\n            if (isStalePendingApprovalFailureDetail(detail)) {\n              if (Option.isNone(existingRow)) {\n                return;\n              }\n              if (existingRow.value.status === \"resolved\") {\n                return;\n              }\n              yield* projectionPendingApprovalRepository.upsert({\n                requestId,\n                threadId: existingRow.value.threadId,\n                turnId: existingRow.value.turnId,\n                status: \"resolved\",\n                decision: null,\n                createdAt: existingRow.value.createdAt,\n                resolvedAt: event.payload.activity.createdAt,\n              });\n              return;\n            }\n            return;\n          }\n          // Only approval-requested activities should create pending-approval\n          // rows.  Other activity kinds that happen to carry a requestId\n          // (e.g. user-input.requested / user-input.resolved) must not\n          // pollute this projection — they have their own accounting via\n          // derivePendingUserInputCountFromActivities.\n          if (event.payload.activity.kind !== \"approval.requested\") {\n            return;\n          }\n          if (Option.isSome(existingRow) && existingRow.value.status === \"resolved\") {\n            return;\n          }\n          yield* projectionPendingApprovalRepository.upsert({\n            requestId,\n            threadId: event.payload.threadId,\n            turnId: event.payload.activity.turnId,\n            status: \"pending\",\n            decision: null,\n            createdAt: Option.isSome(existingRow)\n              ? existingRow.value.createdAt\n              : event.payload.activity.createdAt,\n            resolvedAt: null,\n          });\n          return;\n        }\n\n        case \"thread.approval-response-requested\": {\n          const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({\n            requestId: event.payload.requestId,\n          });\n          yield* projectionPendingApprovalRepository.upsert({\n            requestId: event.payload.requestId,\n            threadId: Option.isSome(existingRow)\n              ? existingRow.value.threadId\n              : event.payload.threadId,\n            turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null,\n            status: \"resolved\",\n            decision: event.payload.decision,\n            createdAt: Option.isSome(existingRow)\n              ? existingRow.value.createdAt\n              : event.payload.createdAt,\n            resolvedAt: event.payload.createdAt,\n          });\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const projectors: ReadonlyArray<ProjectorDefinition> = [\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.projects,\n        apply: applyProjectsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,\n        apply: applyThreadMessagesProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,\n        apply: applyThreadProposedPlansProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,\n        apply: applyThreadActivitiesProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,\n        apply: applyThreadSessionsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,\n        apply: applyThreadTurnsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,\n        apply: applyCheckpointsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,\n        apply: applyPendingApprovalsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threads,\n        apply: applyThreadsProjection,\n      },\n    ];\n\n    const runProjectorForEvent = Effect.fn(\"runProjectorForEvent\")(function* (\n      projector: ProjectorDefinition,\n      event: OrchestrationEvent,\n    ) {\n      const attachmentSideEffects: AttachmentSideEffects = {\n        deletedThreadIds: new Set<string>(),\n        prunedThreadRelativePaths: new Map<string, Set<string>>(),\n      };\n\n      yield* sql.withTransaction(\n        projector.apply(event, attachmentSideEffects).pipe(\n          Effect.flatMap(() =>\n            projectionStateRepository.upsert({\n              projector: projector.name,\n              lastAppliedSequence: event.sequence,\n              updatedAt: event.occurredAt,\n            }),\n          ),\n        ),\n      );\n\n      yield* runAttachmentSideEffects(attachmentSideEffects).pipe(\n        Effect.catch((cause) =>\n          Effect.logWarning(\"failed to apply projected attachment side-effects\", {\n            projector: projector.name,\n            sequence: event.sequence,\n            eventType: event.type,\n            cause,\n          }),\n        ),\n      );\n    });\n\n    const bootstrapProjector = (projector: ProjectorDefinition) =>\n      projectionStateRepository\n        .getByProjector({\n          projector: projector.name,\n        })\n        .pipe(\n          Effect.flatMap((stateRow) =>\n            Stream.runForEach(\n              eventStore.readFromSequence(\n                Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,\n              ),\n              (event) => runProjectorForEvent(projector, event),\n            ),\n          ),\n        );\n\n    const projectEvent: OrchestrationProjectionPipelineShape[\"projectEvent\"] = (event) =>\n      Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {\n        concurrency: 1,\n      }).pipe(\n        Effect.provideService(FileSystem.FileSystem, fileSystem),\n        Effect.provideService(Path.Path, path),\n        Effect.provideService(ServerConfig, serverConfig),\n        Effect.asVoid,\n        Effect.catchTag(\"SqlError\", (sqlError) =>\n          Effect.fail(toPersistenceSqlError(\"ProjectionPipeline.projectEvent:query\")(sqlError)),\n        ),\n      );\n\n    const bootstrap: OrchestrationProjectionPipelineShape[\"bootstrap\"] = Effect.forEach(\n      projectors,\n      bootstrapProjector,\n      { concurrency: 1 },\n    ).pipe(\n      Effect.provideService(FileSystem.FileSystem, fileSystem),\n      Effect.provideService(Path.Path, path),\n      Effect.provideService(ServerConfig, serverConfig),\n      Effect.asVoid,\n      Effect.tap(() =>\n        Effect.logDebug(\"orchestration projection pipeline bootstrapped\").pipe(\n          Effect.annotateLogs({ projectors: projectors.length }),\n        ),\n      ),\n      Effect.catchTag(\"SqlError\", (sqlError) =>\n        Effect.fail(toPersistenceSqlError(\"ProjectionPipeline.bootstrap:query\")(sqlError)),\n      ),\n    );\n\n    return {\n      bootstrap,\n      projectEvent,\n    } satisfies OrchestrationProjectionPipelineShape;\n  },\n);\n\nexport const OrchestrationProjectionPipelineLive = Layer.effect(\n  OrchestrationProjectionPipeline,\n  makeOrchestrationProjectionPipeline(),\n).pipe(\n  Layer.provideMerge(ProjectionProjectRepositoryLive),\n  Layer.provideMerge(ProjectionThreadRepositoryLive),\n  Layer.provideMerge(ProjectionThreadMessageRepositoryLive),\n  Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),\n  Layer.provideMerge(ProjectionThreadActivityRepositoryLive),\n  Layer.provideMerge(ProjectionThreadSessionRepositoryLive),\n  Layer.provideMerge(ProjectionTurnRepositoryLive),\n  Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),\n  Layer.provideMerge(ProjectionStateRepositoryLive),\n);\n","/**\n * ProjectionCheckpointRepository - Projection repository interface for checkpoints.\n *\n * Owns persistence operations for projected checkpoint summaries in thread\n * timelines.\n *\n * @module ProjectionCheckpointRepository\n */\nimport {\n  CheckpointRef,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  OrchestrationCheckpointFile,\n  OrchestrationCheckpointStatus,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Context from \"effect/Context\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionCheckpoint = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\nexport type ProjectionCheckpoint = typeof ProjectionCheckpoint.Type;\n\nexport const ListByThreadIdInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListByThreadIdInput = typeof ListByThreadIdInput.Type;\n\nexport const GetByThreadAndTurnCountInput = Schema.Struct({\n  threadId: ThreadId,\n  checkpointTurnCount: NonNegativeInt,\n});\nexport type GetByThreadAndTurnCountInput = typeof GetByThreadAndTurnCountInput.Type;\n\nexport const DeleteByThreadIdInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteByThreadIdInput = typeof DeleteByThreadIdInput.Type;\n\n/**\n * ProjectionCheckpointRepositoryShape - Service API for projected checkpoints.\n */\nexport interface ProjectionCheckpointRepositoryShape {\n  /**\n   * Insert or replace a projected checkpoint row.\n   *\n   * Upserts by composite key `(threadId, checkpointTurnCount)`.\n   */\n  readonly upsert: (row: ProjectionCheckpoint) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * List projected checkpoints for a thread.\n   *\n   * Returned in ascending checkpoint turn-count order.\n   */\n  readonly listByThreadId: (\n    input: ListByThreadIdInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionCheckpoint>, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected checkpoint by thread and turn-count key.\n   */\n  readonly getByThreadAndTurnCount: (\n    input: GetByThreadAndTurnCountInput,\n  ) => Effect.Effect<Option.Option<ProjectionCheckpoint>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected checkpoint rows by thread.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteByThreadIdInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionCheckpointRepository - Service tag for checkpoint projection persistence.\n */\nexport class ProjectionCheckpointRepository extends Context.Service<\n  ProjectionCheckpointRepository,\n  ProjectionCheckpointRepositoryShape\n>()(\"t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository\") {}\n","/**\n * ThreadBackgroundLivenessService - in-memory per-thread background liveness\n * for the sidebar status pill.\n *\n * The turn can settle while native background work runs on (subagent fleets,\n * workflow runs, Monitor watch loops); the shell previously showed nothing.\n * Ingestion records task lifecycle transitions and the shell query reads the\n * derived state at mapping time — no persistence, no migration. After a\n * server restart the registry is empty until new task events arrive, which\n * matches reality: orphaned background work is not live.\n *\n * \"monitoring\" is reserved for watch loops (monitor tasks and background\n * shells) when they are the ONLY live work; any agent work presents as\n * \"working\".\n *\n * @module ThreadBackgroundLivenessService\n */\nimport { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nexport type ThreadBackgroundLiveness = \"working\" | \"monitoring\" | null;\n\ninterface ThreadLivenessState {\n  readonly agents: Set<string>;\n  readonly monitors: Set<string>;\n}\n\n// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:\n// watch loops — monitor tasks plus background shells, which in practice are\n// PR babysitting/log tails since pacing sleeps complete inside the turn;\n// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's\n// agentKind stamp, and the client fold can never drift apart.\n\nconst TERMINAL_STATUSES: ReadonlySet<string> = new Set([\n  \"completed\",\n  \"failed\",\n  \"stopped\",\n  \"cancelled\",\n  \"interrupted\",\n]);\n\nexport class ThreadBackgroundLivenessService extends Context.Service<\n  ThreadBackgroundLivenessService,\n  {\n    /**\n     * Feed one task lifecycle transition. taskType may be absent on\n     * synthesized rows (workflow members, Codex children) — those count as\n     * agents. agentId marks a task launched from inside a subagent: its\n     * internal shells are covered by the owning agent's liveness, but a\n     * NESTED AGENT (agentId + agent-flavored taskType) still counts — it\n     * can outlive its parent and must keep the thread Working.\n     */\n    readonly recordTaskLiveness: (input: {\n      readonly threadId: string;\n      readonly taskId: string;\n      readonly taskType: string | undefined;\n      readonly status: string | undefined;\n      readonly kind: \"started\" | \"progress\" | \"updated\" | \"completed\";\n      readonly agentId?: string | undefined;\n    }) => void;\n\n    /** Session death orphans all of a thread's background work. */\n    readonly clearThreadLiveness: (threadId: string) => void;\n\n    /**\n     * Two-state vocabulary by design: any live agent work is \"working\";\n     * \"monitoring\" only when watch loops are the ONLY live work.\n     */\n    readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;\n  }\n>()(\"t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService\") {}\n\nexport function make(): ThreadBackgroundLivenessService[\"Service\"] {\n  const stateByThreadId = new Map<string, ThreadLivenessState>();\n\n  const stateFor = (threadId: string): ThreadLivenessState => {\n    const existing = stateByThreadId.get(threadId);\n    if (existing) {\n      return existing;\n    }\n    const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };\n    stateByThreadId.set(threadId, created);\n    return created;\n  };\n\n  // Classification is per-transition, not sticky: a task first seen without\n  // a taskType may later reveal itself as a shell, become inert, or turn out\n  // to be agent-owned. Every path drops any prior entry for the taskId so a\n  // stale bucket assignment can't pin the thread's status (review finding).\n  const drop = (threadId: string, taskId: string) => {\n    const state = stateByThreadId.get(threadId);\n    if (!state) {\n      return;\n    }\n    state.agents.delete(taskId);\n    state.monitors.delete(taskId);\n    if (state.agents.size === 0 && state.monitors.size === 0) {\n      stateByThreadId.delete(threadId);\n    }\n  };\n\n  return {\n    recordTaskLiveness: (input) => {\n      const taskType = input.taskType;\n      if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {\n        drop(input.threadId, input.taskId);\n        return;\n      }\n      // A subagent's internal non-agent work (its own shells/monitors) is\n      // covered by the owning agent's liveness. Nested agents fall through:\n      // they can outlive their parent (review finding).\n      if (\n        input.agentId !== undefined &&\n        (taskType === undefined || MONITOR_TASK_TYPES.has(taskType))\n      ) {\n        drop(input.threadId, input.taskId);\n        return;\n      }\n\n      // Idle counts as not-live: a resting (resumable) Codex child isn't\n      // doing anything, and an all-idle fleet must not pin Working.\n      const terminal =\n        input.kind === \"completed\" ||\n        input.status === \"idle\" ||\n        (input.status !== undefined && TERMINAL_STATUSES.has(input.status));\n      if (terminal) {\n        drop(input.threadId, input.taskId);\n        return;\n      }\n\n      drop(input.threadId, input.taskId);\n      const state = stateFor(input.threadId);\n      const bucket =\n        taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;\n      bucket.add(input.taskId);\n    },\n\n    clearThreadLiveness: (threadId) => {\n      stateByThreadId.delete(threadId);\n    },\n\n    getThreadBackgroundLiveness: (threadId) => {\n      const state = stateByThreadId.get(threadId);\n      if (!state) {\n        return null;\n      }\n      if (state.agents.size > 0) {\n        return \"working\";\n      }\n      if (state.monitors.size > 0) {\n        return \"monitoring\";\n      }\n      return null;\n    },\n  };\n}\n\nexport const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));\n","import type { SourceControlProviderInfo, SourceControlProviderKind } from \"@t3tools/contracts\";\n\nexport interface ChangeRequestPresentation {\n  readonly icon: \"github\" | \"gitlab\" | \"azure-devops\" | \"bitbucket\" | \"change-request\";\n  readonly providerName: string;\n  readonly shortName: string;\n  readonly longName: string;\n  readonly pluralLongName: string;\n  readonly providerLongName: string;\n  readonly checkoutCommandExample?: string;\n  readonly urlExample: string;\n}\n\nexport interface ChangeRequestTerminology {\n  readonly shortLabel: string;\n  readonly singular: string;\n}\n\nexport const DEFAULT_CHANGE_REQUEST_TERMINOLOGY: ChangeRequestTerminology = {\n  shortLabel: \"PR\",\n  singular: \"pull request\",\n};\n\nconst GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"github\",\n  providerName: \"GitHub\",\n  shortName: \"PR\",\n  longName: \"pull request\",\n  pluralLongName: \"pull requests\",\n  providerLongName: \"GitHub pull request\",\n  checkoutCommandExample: \"gh pr checkout 123\",\n  urlExample: \"https://github.com/owner/repo/pull/42\",\n};\n\nconst GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"gitlab\",\n  providerName: \"GitLab\",\n  shortName: \"MR\",\n  longName: \"merge request\",\n  pluralLongName: \"merge requests\",\n  providerLongName: \"GitLab merge request\",\n  checkoutCommandExample: \"glab mr checkout 123\",\n  urlExample: \"https://gitlab.com/group/project/-/merge_requests/42\",\n};\n\nconst AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"azure-devops\",\n  providerName: \"Azure DevOps\",\n  shortName: \"PR\",\n  longName: \"pull request\",\n  pluralLongName: \"pull requests\",\n  providerLongName: \"Azure DevOps pull request\",\n  checkoutCommandExample: \"az repos pr checkout --id 123\",\n  urlExample: \"https://dev.azure.com/org/project/_git/repo/pullrequest/42\",\n};\n\nconst BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"bitbucket\",\n  providerName: \"Bitbucket\",\n  shortName: \"PR\",\n  longName: \"pull request\",\n  pluralLongName: \"pull requests\",\n  providerLongName: \"Bitbucket pull request\",\n  urlExample: \"https://bitbucket.org/workspace/repo/pull-requests/42\",\n};\n\nconst GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"change-request\",\n  providerName: \"source control\",\n  shortName: \"change request\",\n  longName: \"change request\",\n  pluralLongName: \"change requests\",\n  providerLongName: \"change request\",\n  urlExample: \"#42\",\n};\n\nexport function resolveChangeRequestPresentation(\n  provider: SourceControlProviderInfo | null | undefined,\n): ChangeRequestPresentation {\n  switch (provider?.kind) {\n    case \"github\":\n    case undefined:\n      return GITHUB_CHANGE_REQUEST_PRESENTATION;\n    case \"gitlab\":\n      return GITLAB_CHANGE_REQUEST_PRESENTATION;\n    case \"azure-devops\":\n      return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;\n    case \"bitbucket\":\n      return BITBUCKET_CHANGE_REQUEST_PRESENTATION;\n    case \"unknown\":\n      return GENERIC_CHANGE_REQUEST_PRESENTATION;\n  }\n}\n\nexport function resolveChangeRequestPresentationForKind(\n  kind: SourceControlProviderKind,\n): ChangeRequestPresentation {\n  return resolveChangeRequestPresentation({ kind, name: \"\", baseUrl: \"\" });\n}\n\nexport function formatChangeRequestAction(\n  verb: \"View\" | \"Create\",\n  presentation: ChangeRequestPresentation,\n): string {\n  return `${verb} ${presentation.shortName}`;\n}\n\nexport function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {\n  return `create ${presentation.shortName}`;\n}\n\nexport function getChangeRequestTerminology(\n  provider: SourceControlProviderInfo | null | undefined,\n): ChangeRequestTerminology {\n  if (!provider) {\n    return DEFAULT_CHANGE_REQUEST_TERMINOLOGY;\n  }\n\n  const presentation = resolveChangeRequestPresentation(provider);\n  return {\n    shortLabel: presentation.shortName,\n    singular: presentation.longName,\n  };\n}\n\nexport function getChangeRequestTerminologyForKind(\n  kind: SourceControlProviderKind,\n): ChangeRequestTerminology {\n  const presentation = resolveChangeRequestPresentationForKind(kind);\n  return {\n    shortLabel: presentation.shortName,\n    singular: presentation.longName,\n  };\n}\n\nfunction parseRemoteHost(remoteUrl: string): string | null {\n  const trimmed = remoteUrl.trim();\n  if (trimmed.length === 0) {\n    return null;\n  }\n\n  if (trimmed.startsWith(\"git@\")) {\n    const hostWithPath = trimmed.slice(\"git@\".length);\n    const separatorIndex = hostWithPath.search(/[:/]/);\n    if (separatorIndex <= 0) {\n      return null;\n    }\n    return hostWithPath.slice(0, separatorIndex).toLowerCase();\n  }\n\n  try {\n    return new URL(trimmed).host.toLowerCase();\n  } catch {\n    return null;\n  }\n}\n\nfunction parseHostName(host: string): string {\n  try {\n    return new URL(`https://${host}`).hostname.toLowerCase();\n  } catch {\n    return host.replace(/:\\d+$/u, \"\").toLowerCase();\n  }\n}\n\nfunction toBaseUrl(host: string): string {\n  return `https://${host}`;\n}\n\nfunction isGitHubHost(host: string): boolean {\n  return host === \"github.com\" || host.includes(\"github\");\n}\n\nfunction isGitLabHost(host: string): boolean {\n  return host === \"gitlab.com\" || host.includes(\"gitlab\");\n}\n\nfunction isAzureDevOpsHost(host: string): boolean {\n  return host === \"dev.azure.com\" || host.endsWith(\".visualstudio.com\");\n}\n\nfunction isBitbucketHost(host: string): boolean {\n  return host === \"bitbucket.org\" || host.includes(\"bitbucket\");\n}\n\nexport function detectSourceControlProviderFromRemoteUrl(\n  remoteUrl: string,\n): SourceControlProviderInfo | null {\n  const host = parseRemoteHost(remoteUrl);\n  if (!host) {\n    return null;\n  }\n  const hostname = parseHostName(host);\n\n  if (isGitHubHost(hostname)) {\n    return {\n      kind: \"github\",\n      name: hostname === \"github.com\" ? \"GitHub\" : \"GitHub Self-Hosted\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  if (isGitLabHost(hostname)) {\n    return {\n      kind: \"gitlab\",\n      name: hostname === \"gitlab.com\" ? \"GitLab\" : \"GitLab Self-Hosted\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  if (isAzureDevOpsHost(hostname)) {\n    return {\n      kind: \"azure-devops\",\n      name: \"Azure DevOps\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  if (isBitbucketHost(hostname)) {\n    return {\n      kind: \"bitbucket\",\n      name: hostname === \"bitbucket.org\" ? \"Bitbucket\" : \"Bitbucket Self-Hosted\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  return {\n    kind: \"unknown\",\n    name: host,\n    baseUrl: toBaseUrl(host),\n  };\n}\n","import type {\n  VcsRef,\n  SourceControlProviderInfo,\n  VcsStatusLocalResult,\n  VcsStatusRemoteResult,\n  VcsStatusResult,\n  VcsStatusStreamEvent,\n} from \"@t3tools/contracts\";\nimport * as Arr from \"effect/Array\";\nimport * as Result from \"effect/Result\";\nimport { detectSourceControlProviderFromRemoteUrl } from \"./sourceControl.ts\";\n\nexport const WORKTREE_BRANCH_PREFIX = \"t3code\";\n// Canonical form is `t3code/<8 hex>`. Older mobile builds generated `t3code/<uuid>`\n// via Crypto.randomUUID() (always RFC 4122 v4), so the matcher also accepts exactly\n// that shape — version nibble `4`, variant nibble `[89ab]` — to keep those threads\n// eligible for branch regeneration without loosening beyond what was ever generated.\nconst TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(\n  `^${WORKTREE_BRANCH_PREFIX}\\\\/(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`,\n);\n\n/**\n * Sanitize an arbitrary string into a valid, lowercase git refName fragment.\n * Strips quotes, collapses separators, limits to 64 chars.\n */\nexport function sanitizeBranchFragment(raw: string): string {\n  const normalized = raw\n    .trim()\n    .toLowerCase()\n    .replace(/['\"`]/g, \"\")\n    .replace(/^[./\\s_-]+|[./\\s_-]+$/g, \"\");\n\n  const branchFragment = normalized\n    .replace(/[^a-z0-9/_-]+/g, \"-\")\n    .replace(/\\/+/g, \"/\")\n    .replace(/-+/g, \"-\")\n    .replace(/^[./_-]+|[./_-]+$/g, \"\")\n    .slice(0, 64)\n    .replace(/[./_-]+$/g, \"\");\n\n  return branchFragment.length > 0 ? branchFragment : \"update\";\n}\n\n/**\n * Sanitize a string into a `feature/…` refName name.\n * Preserves an existing `feature/` prefix or slash-separated namespace.\n */\nexport function sanitizeFeatureBranchName(raw: string): string {\n  const sanitized = sanitizeBranchFragment(raw);\n  if (sanitized.includes(\"/\")) {\n    return sanitized.startsWith(\"feature/\") ? sanitized : `feature/${sanitized}`;\n  }\n  return `feature/${sanitized}`;\n}\n\nconst AUTO_FEATURE_BRANCH_FALLBACK = \"feature/update\";\n\n/**\n * Resolve a unique `feature/…` refName name that doesn't collide with\n * any existing refName. Appends a numeric suffix when needed.\n */\nexport function resolveAutoFeatureBranchName(\n  existingBranchNames: readonly string[],\n  preferredBranch?: string,\n): string {\n  const preferred = preferredBranch?.trim();\n  const resolvedBase = sanitizeFeatureBranchName(\n    preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,\n  );\n  const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));\n\n  if (!existingNames.has(resolvedBase)) {\n    return resolvedBase;\n  }\n\n  let suffix = 2;\n  while (existingNames.has(`${resolvedBase}-${suffix}`)) {\n    suffix += 1;\n  }\n\n  return `${resolvedBase}-${suffix}`;\n}\n\n/**\n * Strip the remote prefix from a remote ref such as `origin/feature/demo`.\n */\nexport function deriveLocalBranchNameFromRemoteRef(branchName: string): string {\n  const firstSeparatorIndex = branchName.indexOf(\"/\");\n  if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {\n    return branchName;\n  }\n  return branchName.slice(firstSeparatorIndex + 1);\n}\n\nexport function buildTemporaryWorktreeBranchName(\n  randomHex: (byteLength: number) => string,\n): string {\n  // Normalize to exactly 8 lowercase hex chars so a UUID-shaped callback\n  // still produces the canonical temporary branch form.\n  const token = randomHex(4)\n    .toLowerCase()\n    .replace(/[^0-9a-f]/g, \"\")\n    .slice(0, 8);\n  return `${WORKTREE_BRANCH_PREFIX}/${token}`;\n}\n\nexport function isTemporaryWorktreeBranch(refName: string): boolean {\n  return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());\n}\n\n/**\n * Normalize a git remote URL into a stable comparison key.\n */\nexport function normalizeGitRemoteUrl(value: string): string {\n  const normalized = value\n    .trim()\n    .replace(/\\/+$/g, \"\")\n    .replace(/\\.git$/i, \"\")\n    .toLowerCase();\n\n  if (/^(?:ssh|https?|git):\\/\\//i.test(normalized)) {\n    try {\n      const url = new URL(normalized);\n      const repositoryPath = url.pathname\n        .split(\"/\")\n        .filter((segment) => segment.length > 0)\n        .join(\"/\");\n      if (url.hostname && repositoryPath.includes(\"/\")) {\n        return `${url.hostname}/${repositoryPath}`;\n      }\n    } catch {\n      return normalized;\n    }\n  }\n\n  const scpStyleHostAndPath = /^git@([^:/\\s]+)[:/]([^/\\s]+(?:\\/[^/\\s]+)+)$/i.exec(normalized);\n  if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {\n    return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;\n  }\n\n  return normalized;\n}\n\n/**\n * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.\n */\nexport function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {\n  const trimmed = url?.trim() ?? \"\";\n  if (trimmed.length === 0) {\n    return null;\n  }\n\n  const match =\n    /^(?:git@github\\.com:|ssh:\\/\\/git@github\\.com\\/|https:\\/\\/github\\.com\\/|git:\\/\\/github\\.com\\/)([^/\\s]+\\/[^/\\s]+?)(?:\\.git)?\\/?$/i.exec(\n      trimmed,\n    );\n  const repositoryNameWithOwner = match?.[1]?.trim() ?? \"\";\n  return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;\n}\n\nfunction deriveLocalBranchNameCandidatesFromRemoteRef(\n  branchName: string,\n  remoteName?: string,\n): ReadonlyArray<string> {\n  const candidates = new Set<string>();\n  const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);\n  if (firstSlashCandidate.length > 0) {\n    candidates.add(firstSlashCandidate);\n  }\n\n  if (remoteName) {\n    const remotePrefix = `${remoteName}/`;\n    if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {\n      candidates.add(branchName.slice(remotePrefix.length));\n    }\n  }\n\n  return [...candidates];\n}\n\n/**\n * Hide `origin/*` remote refs when a matching local refName already exists.\n */\nexport function dedupeRemoteBranchesWithLocalMatches(\n  refs: ReadonlyArray<VcsRef>,\n): ReadonlyArray<VcsRef> {\n  const localBranchNames = new Set(\n    Arr.filterMap(refs, (refName) =>\n      refName.isRemote ? Result.failVoid : Result.succeed(refName.name),\n    ),\n  );\n\n  return refs.filter((refName) => {\n    if (!refName.isRemote) {\n      return true;\n    }\n\n    if (refName.remoteName !== \"origin\") {\n      return true;\n    }\n\n    const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(\n      refName.name,\n      refName.remoteName,\n    );\n    return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));\n  });\n}\n\nexport function detectSourceControlProviderFromGitRemoteUrl(\n  remoteUrl: string,\n): SourceControlProviderInfo | null {\n  return detectSourceControlProviderFromRemoteUrl(remoteUrl);\n}\n\nconst EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {\n  hasUpstream: false,\n  aheadCount: 0,\n  behindCount: 0,\n  aheadOfDefaultCount: 0,\n  pr: null,\n};\n\nexport function mergeGitStatusParts(\n  local: VcsStatusLocalResult,\n  remote: VcsStatusRemoteResult | null,\n): VcsStatusResult {\n  return {\n    ...local,\n    ...(remote ?? EMPTY_GIT_STATUS_REMOTE),\n  };\n}\n\nfunction toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {\n  return {\n    hasUpstream: status.hasUpstream,\n    aheadCount: status.aheadCount,\n    behindCount: status.behindCount,\n    ...(status.aheadOfDefaultCount === undefined\n      ? {}\n      : { aheadOfDefaultCount: status.aheadOfDefaultCount }),\n    pr: status.pr,\n  };\n}\n\nfunction toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {\n  return {\n    isRepo: status.isRepo,\n    ...(status.sourceControlProvider\n      ? { sourceControlProvider: status.sourceControlProvider }\n      : {}),\n    hasPrimaryRemote: status.hasPrimaryRemote,\n    isDefaultRef: status.isDefaultRef,\n    refName: status.refName,\n    hasWorkingTreeChanges: status.hasWorkingTreeChanges,\n    workingTree: status.workingTree,\n  };\n}\n\nexport function applyGitStatusStreamEvent(\n  current: VcsStatusResult | null,\n  event: VcsStatusStreamEvent,\n): VcsStatusResult {\n  switch (event._tag) {\n    case \"snapshot\":\n      return mergeGitStatusParts(event.local, event.remote);\n    case \"localUpdated\":\n      return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);\n    case \"remoteUpdated\":\n      if (current === null) {\n        return mergeGitStatusParts(\n          {\n            isRepo: true,\n            hasPrimaryRemote: false,\n            isDefaultRef: false,\n            refName: null,\n            hasWorkingTreeChanges: false,\n            workingTree: { files: [], insertions: 0, deletions: 0 },\n          },\n          event.remote,\n        );\n      }\n      return mergeGitStatusParts(toLocalStatusPart(current), event.remote);\n  }\n}\n","import * as Effect from \"effect/Effect\";\nimport * as Stream from \"effect/Stream\";\n\nexport interface CollectedUint8StreamText {\n  readonly text: string;\n  readonly truncated: boolean;\n  readonly bytes: number;\n}\n\ninterface CollectState {\n  chunks: Uint8Array[];\n  readonly bytes: number;\n  readonly truncated: boolean;\n}\n\nexport const collectUint8StreamText = <E>(input: {\n  readonly stream: Stream.Stream<Uint8Array, E>;\n  readonly maxBytes?: number | undefined;\n  readonly truncatedMarker?: string | null | undefined;\n}): Effect.Effect<CollectedUint8StreamText, E> => {\n  const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;\n  const truncatedMarker = input.truncatedMarker ?? \"\";\n\n  return input.stream.pipe(\n    Stream.runFold(\n      (): CollectState => ({\n        chunks: [],\n        bytes: 0,\n        truncated: false,\n      }),\n      (state, chunk): CollectState => {\n        /*\n         * keep draining after truncation so the child process can exit normally.\n         * its a know issue that on windows killing after the output cap can force an expensive taskkill operation and hurt performance\n         */\n        if (state.truncated) {\n          return state;\n        }\n\n        const remainingBytes = maxBytes - state.bytes;\n        if (remainingBytes <= 0) {\n          return {\n            ...state,\n            truncated: true,\n          };\n        }\n\n        const nextChunk =\n          chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;\n        state.chunks.push(nextChunk);\n        const bytes = state.bytes + nextChunk.byteLength;\n        const truncated = chunk.byteLength > remainingBytes;\n\n        return {\n          chunks: state.chunks,\n          bytes,\n          truncated,\n        };\n      },\n    ),\n    Effect.map((state): CollectedUint8StreamText => {\n      const text = Buffer.concat(state.chunks, state.bytes).toString(\"utf8\");\n      return {\n        text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,\n        bytes: state.bytes,\n        truncated: state.truncated,\n      };\n    }),\n  );\n};\n","import * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport {\n  collectUint8StreamText,\n  type CollectedUint8StreamText,\n} from \"./stream/collectUint8StreamText.ts\";\n\nexport interface ProcessRunInput {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd?: string | undefined;\n  readonly spawnCwd?: string | undefined;\n  readonly timeout?: Duration.Input | undefined;\n  readonly env?: NodeJS.ProcessEnv | undefined;\n  readonly stdin?: string | undefined;\n  readonly maxOutputBytes?: number | undefined;\n  readonly outputMode?: \"error\" | \"truncate\" | undefined;\n  readonly truncatedMarker?: string | undefined;\n  /**\n   * On timeout, return a synthetic timedOut result.\n   * Partial stdout/stderr are not preserved.\n   */\n  readonly timeoutBehavior?: \"error\" | \"timedOutResult\" | undefined;\n}\n\nexport interface ProcessRunOutput {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly code: ChildProcessSpawner.ExitCode | null;\n  readonly timedOut: boolean;\n  readonly stdoutTruncated: boolean;\n  readonly stderrTruncated: boolean;\n}\n\nconst ProcessInvocationFields = {\n  command: Schema.String,\n  argumentCount: Schema.Number,\n  cwd: Schema.optional(Schema.String),\n  spawnCwd: Schema.optional(Schema.String),\n};\n\nconst formatProcessInvocation = (input: {\n  readonly command: string;\n  readonly cwd?: string | undefined;\n  readonly spawnCwd?: string | undefined;\n}): string => {\n  const executionCwd = input.spawnCwd ?? input.cwd;\n  return executionCwd === undefined\n    ? `'${input.command}'`\n    : `'${input.command}' in '${executionCwd}'`;\n};\n\nexport class ProcessSpawnError extends Schema.TaggedErrorClass<ProcessSpawnError>()(\n  \"ProcessSpawnError\",\n  {\n    ...ProcessInvocationFields,\n    resolvedCommand: Schema.optional(Schema.String),\n    resolvedArgumentCount: Schema.optional(Schema.Number),\n    shell: Schema.optional(Schema.Boolean),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to spawn process ${formatProcessInvocation(this)}`;\n  }\n}\n\nexport class ProcessStdinError extends Schema.TaggedErrorClass<ProcessStdinError>()(\n  \"ProcessStdinError\",\n  {\n    ...ProcessInvocationFields,\n    stdinBytes: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to write stdin for process ${formatProcessInvocation(this)}`;\n  }\n}\n\nexport class ProcessOutputLimitError extends Schema.TaggedErrorClass<ProcessOutputLimitError>()(\n  \"ProcessOutputLimitError\",\n  {\n    ...ProcessInvocationFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\"]),\n    maxBytes: Schema.Number,\n    observedBytes: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;\n  }\n}\n\nexport class ProcessReadError extends Schema.TaggedErrorClass<ProcessReadError>()(\n  \"ProcessReadError\",\n  {\n    ...ProcessInvocationFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\", \"exitCode\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;\n  }\n}\n\nexport class ProcessTimeoutError extends Schema.TaggedErrorClass<ProcessTimeoutError>()(\n  \"ProcessTimeoutError\",\n  {\n    ...ProcessInvocationFields,\n    timeoutMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;\n  }\n}\n\nexport const ProcessRunError = Schema.Union([\n  ProcessSpawnError,\n  ProcessStdinError,\n  ProcessOutputLimitError,\n  ProcessReadError,\n  ProcessTimeoutError,\n]);\nexport type ProcessRunError = typeof ProcessRunError.Type;\n\nexport class ProcessRunner extends Context.Service<\n  ProcessRunner,\n  {\n    readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;\n  }\n>()(\"t3/processRunner\") {}\n\nconst DEFAULT_TIMEOUT = \"60 seconds\";\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n\nconst WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [\n  /is not recognized as an internal or external command/i,\n  /n.o . reconhecido como um comando interno/i,\n  /non . riconosciuto come comando interno o esterno/i,\n  /n.est pas reconnu en tant que commande interne/i,\n  /no se reconoce como un comando interno o externo/i,\n  /wird nicht als interner oder externer befehl/i,\n] as const;\n\nfunction hasWindowsCommandNotFoundMessage(output: string): boolean {\n  return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));\n}\n\nexport const isWindowsCommandNotFound = Effect.fn(\"processRunner.isWindowsCommandNotFound\")(\n  function* (code: number | null, stderr: string) {\n    const platform = yield* HostProcessPlatform;\n    if (platform !== \"win32\") return false;\n    if (code === 9009) return true;\n    return hasWindowsCommandNotFoundMessage(stderr);\n  },\n);\n\nconst collectText = Effect.fn(\"processRunner.collectText\")(function* (input: {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd?: string | undefined;\n  readonly spawnCwd?: string | undefined;\n  readonly streamName: \"stdout\" | \"stderr\";\n  readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;\n  readonly maxOutputBytes: number;\n  readonly outputMode: \"error\" | \"truncate\";\n  readonly truncatedMarker: string;\n}) {\n  const stream = input.stream.pipe(\n    Stream.mapError(\n      (cause) =>\n        new ProcessReadError({\n          command: input.command,\n          argumentCount: input.args.length,\n          cwd: input.cwd,\n          spawnCwd: input.spawnCwd,\n          stream: input.streamName,\n          cause,\n        }),\n    ),\n  );\n\n  if (input.outputMode === \"truncate\") {\n    return yield* collectUint8StreamText({\n      stream,\n      maxBytes: input.maxOutputBytes,\n      truncatedMarker: input.truncatedMarker,\n    });\n  }\n\n  return yield* stream.pipe(\n    Stream.runFoldEffect<\n      {\n        readonly chunks: Uint8Array<ArrayBufferLike>[];\n        readonly bytes: number;\n      },\n      Uint8Array<ArrayBufferLike>,\n      ProcessOutputLimitError | ProcessReadError,\n      never\n    >(\n      () => ({ chunks: [], bytes: 0 }),\n      (state, chunk) => {\n        const remainingBytes = input.maxOutputBytes - state.bytes;\n        if (chunk.byteLength > remainingBytes) {\n          return Effect.fail(\n            new ProcessOutputLimitError({\n              command: input.command,\n              argumentCount: input.args.length,\n              cwd: input.cwd,\n              spawnCwd: input.spawnCwd,\n              stream: input.streamName,\n              maxBytes: input.maxOutputBytes,\n              observedBytes: state.bytes + chunk.byteLength,\n            }),\n          );\n        }\n\n        state.chunks.push(chunk);\n        return Effect.succeed({\n          chunks: state.chunks,\n          bytes: state.bytes + chunk.byteLength,\n        });\n      },\n    ),\n    Effect.map(\n      (state): CollectedUint8StreamText => ({\n        text: Buffer.concat(state.chunks, state.bytes).toString(\"utf8\"),\n        bytes: state.bytes,\n        truncated: false,\n      }),\n    ),\n  );\n});\n\nfunction finalizeRunProcess<R>(\n  effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,\n  input: ProcessRunInput,\n): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {\n  const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);\n  const timeoutBehavior = input.timeoutBehavior ?? \"error\";\n\n  return effect.pipe(\n    Effect.scoped,\n    Effect.timeoutOption(timeout),\n    Effect.flatMap((result) => {\n      if (Option.isSome(result)) {\n        return Effect.succeed(result.value);\n      }\n      if (timeoutBehavior === \"timedOutResult\") {\n        return Effect.succeed({\n          stdout: \"\",\n          stderr: \"\",\n          code: null,\n          timedOut: true,\n          stdoutTruncated: false,\n          stderrTruncated: false,\n        } satisfies ProcessRunOutput);\n      }\n      return Effect.fail(\n        new ProcessTimeoutError({\n          command: input.command,\n          argumentCount: input.args.length,\n          cwd: input.cwd,\n          spawnCwd: input.spawnCwd,\n          timeoutMs: Duration.toMillis(timeout),\n        }),\n      );\n    }),\n  );\n}\n\nconst runProcessCore = Effect.fn(\"processRunner.runProcessCore\")(function* (\n  spawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"],\n  input: ProcessRunInput,\n): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {\n  const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n  const outputMode = input.outputMode ?? \"error\";\n  const truncatedMarker = input.truncatedMarker ?? \"\";\n  const extendEnv = input.env !== undefined;\n  const spawnCommand = yield* resolveSpawnCommand(\n    input.command,\n    input.args,\n    input.env === undefined ? {} : { env: input.env, extendEnv },\n  );\n\n  const child = yield* spawner\n    .spawn(\n      ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),\n        ...(input.env !== undefined\n          ? {\n              env: input.env,\n              extendEnv,\n            }\n          : {}),\n        shell: spawnCommand.shell,\n      }),\n    )\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProcessSpawnError({\n            command: input.command,\n            argumentCount: input.args.length,\n            cwd: input.cwd,\n            spawnCwd: input.spawnCwd,\n            resolvedCommand: spawnCommand.command,\n            resolvedArgumentCount: spawnCommand.args.length,\n            shell: spawnCommand.shell,\n            cause,\n          }),\n      ),\n    );\n\n  const stdin = input.stdin;\n  const writeStdin =\n    stdin === undefined\n      ? Effect.void\n      : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProcessStdinError({\n                command: input.command,\n                argumentCount: input.args.length,\n                cwd: input.cwd,\n                spawnCwd: input.spawnCwd,\n                stdinBytes: Buffer.byteLength(stdin),\n                cause,\n              }),\n          ),\n        );\n\n  const [stdout, stderr] = yield* Effect.all(\n    [\n      collectText({\n        command: input.command,\n        args: input.args,\n        cwd: input.cwd,\n        spawnCwd: input.spawnCwd,\n        streamName: \"stdout\",\n        stream: child.stdout,\n        maxOutputBytes,\n        outputMode,\n        truncatedMarker,\n      }),\n      collectText({\n        command: input.command,\n        args: input.args,\n        cwd: input.cwd,\n        spawnCwd: input.spawnCwd,\n        streamName: \"stderr\",\n        stream: child.stderr,\n        maxOutputBytes,\n        outputMode,\n        truncatedMarker,\n      }),\n      writeStdin,\n    ],\n    { concurrency: \"unbounded\" },\n  );\n\n  const exitCode = yield* child.exitCode.pipe(\n    Effect.mapError(\n      (cause) =>\n        new ProcessReadError({\n          command: input.command,\n          argumentCount: input.args.length,\n          cwd: input.cwd,\n          spawnCwd: input.spawnCwd,\n          stream: \"exitCode\",\n          cause,\n        }),\n    ),\n  );\n\n  return {\n    stdout: stdout.text,\n    stderr: stderr.text,\n    code: exitCode,\n    timedOut: false,\n    stdoutTruncated: stdout.truncated,\n    stderrTruncated: stderr.truncated,\n  } satisfies ProcessRunOutput;\n});\n\nexport const make = Effect.fn(\"ProcessRunner.make\")(function* () {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\n  const run: ProcessRunner[\"Service\"][\"run\"] = (input) =>\n    finalizeRunProcess(runProcessCore(spawner, input), input);\n\n  return ProcessRunner.of({\n    run,\n  });\n});\n\nexport const layer = Layer.effect(ProcessRunner, make());\n","import type { RepositoryIdentity } from \"@t3tools/contracts\";\nimport {\n  detectSourceControlProviderFromGitRemoteUrl,\n  normalizeGitRemoteUrl,\n} from \"@t3tools/shared/git\";\nimport * as Cache from \"effect/Cache\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\nconst DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;\nconst DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);\nconst DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);\n\nexport interface RepositoryIdentityResolverOptions {\n  readonly cacheCapacity?: number;\n  readonly positiveCacheTtl?: Duration.Input;\n  readonly negativeCacheTtl?: Duration.Input;\n}\n\nexport class RepositoryIdentityResolver extends Context.Service<\n  RepositoryIdentityResolver,\n  {\n    readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;\n  }\n>()(\"t3/project/RepositoryIdentityResolver\") {}\n\nfunction parseRemoteFetchUrls(stdout: string): Map<string, string> {\n  const remotes = new Map<string, string>();\n  for (const line of stdout.split(\"\\n\")) {\n    const trimmed = line.trim();\n    if (trimmed.length === 0) continue;\n    const match = /^(\\S+)\\s+(\\S+)\\s+\\((fetch|push)\\)$/.exec(trimmed);\n    if (!match) continue;\n    const [, remoteName = \"\", remoteUrl = \"\", direction = \"\"] = match;\n    if (direction !== \"fetch\" || remoteName.length === 0 || remoteUrl.length === 0) {\n      continue;\n    }\n    remotes.set(remoteName, remoteUrl);\n  }\n  return remotes;\n}\n\nfunction pickPrimaryRemote(\n  remotes: ReadonlyMap<string, string>,\n): { readonly remoteName: string; readonly remoteUrl: string } | null {\n  for (const preferredRemoteName of [\"upstream\", \"origin\"] as const) {\n    const remoteUrl = remotes.get(preferredRemoteName);\n    if (remoteUrl) {\n      return { remoteName: preferredRemoteName, remoteUrl };\n    }\n  }\n\n  const [remoteName, remoteUrl] =\n    [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];\n  return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;\n}\n\nfunction buildRepositoryIdentity(input: {\n  readonly remoteName: string;\n  readonly remoteUrl: string;\n  readonly rootPath: string;\n}): RepositoryIdentity {\n  const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);\n  const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);\n  const repositoryPath = canonicalKey.split(\"/\").slice(1).join(\"/\");\n  const repositoryPathSegments = repositoryPath.split(\"/\").filter((segment) => segment.length > 0);\n  const [owner] = repositoryPathSegments;\n  const repositoryName = repositoryPathSegments.at(-1);\n\n  return {\n    canonicalKey,\n    locator: {\n      source: \"git-remote\",\n      remoteName: input.remoteName,\n      remoteUrl: input.remoteUrl,\n    },\n    rootPath: input.rootPath,\n    ...(repositoryPath ? { displayName: repositoryPath } : {}),\n    ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),\n    ...(owner ? { owner } : {}),\n    ...(repositoryName ? { name: repositoryName } : {}),\n  };\n}\n\nconst resolveRepositoryIdentityCacheKey = Effect.fn(\"RepositoryIdentityResolver.resolveCacheKey\")(\n  function* (cwd: string) {\n    const processRunner = yield* ProcessRunner.ProcessRunner;\n    let cacheKey = cwd;\n\n    // git is a real executable on every platform — no cmd.exe shell mode, which\n    // would split paths containing spaces during cmd's re-tokenization.\n    const topLevelResult = yield* processRunner\n      .run({\n        command: \"git\",\n        args: [\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"],\n        timeoutBehavior: \"timedOutResult\",\n      })\n      .pipe(Effect.option);\n    if (topLevelResult._tag === \"None\" || topLevelResult.value.code !== 0) {\n      return cacheKey;\n    }\n\n    const candidate = topLevelResult.value.stdout.trim();\n    if (candidate.length > 0) {\n      cacheKey = candidate;\n    }\n\n    return cacheKey;\n  },\n);\n\nconst resolveRepositoryIdentityFromCacheKey = Effect.fn(\n  \"RepositoryIdentityResolver.resolveFromCacheKey\",\n)(function* (\n  cacheKey: string,\n): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const remoteResult = yield* processRunner\n    .run({\n      command: \"git\",\n      args: [\"-C\", cacheKey, \"remote\", \"-v\"],\n      timeoutBehavior: \"timedOutResult\",\n    })\n    .pipe(Effect.option);\n  if (remoteResult._tag === \"None\" || remoteResult.value.code !== 0) {\n    return null;\n  }\n\n  const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));\n  return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;\n});\n\nexport const make = Effect.fn(\"RepositoryIdentityResolver.make\")(function* (\n  options: RepositoryIdentityResolverOptions = {},\n) {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n\n  const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(\n    (cacheKey) =>\n      resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(\n        Effect.provideService(ProcessRunner.ProcessRunner, processRunner),\n      ),\n    {\n      capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,\n      timeToLive: Exit.match({\n        onSuccess: (value) =>\n          value === null\n            ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)\n            : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n\n  const resolve: RepositoryIdentityResolver[\"Service\"][\"resolve\"] = Effect.fn(\n    \"RepositoryIdentityResolver.resolve\",\n  )(function* (cwd) {\n    const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(\n      Effect.provideService(ProcessRunner.ProcessRunner, processRunner),\n    );\n    return yield* Cache.get(repositoryIdentityCache, cacheKey);\n  });\n\n  return RepositoryIdentityResolver.of({ resolve });\n});\n\nexport const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(\n  Layer.provide(ProcessRunner.layer),\n);\n","import {\n  ChatAttachment,\n  CheckpointRef,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  OrchestrationCheckpointFile,\n  OrchestrationProposedPlanId,\n  OrchestrationReadModel,\n  OrchestrationThreadSearchSource,\n  OrchestrationShellSnapshot,\n  OrchestrationThread,\n  OrchestrationThreadDetailSnapshot,\n  ProjectScript,\n  TurnId,\n  type OrchestrationCheckpointSummary,\n  type OrchestrationLatestTurn,\n  type OrchestrationMessage,\n  type OrchestrationProjectShell,\n  type OrchestrationProposedPlan,\n  type OrchestrationProject,\n  type OrchestrationSession,\n  type OrchestrationThreadActivity,\n  type OrchestrationThreadShell,\n  ModelSelection,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Arr from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport {\n  isPersistenceError,\n  toPersistenceDecodeError,\n  toPersistenceSqlError,\n  type ProjectionRepositoryError,\n} from \"../../persistence/Errors.ts\";\nimport { ProjectionCheckpoint } from \"../../persistence/Services/ProjectionCheckpoints.ts\";\nimport { ThreadBackgroundLivenessService } from \"../ThreadBackgroundLiveness.ts\";\nimport { ProjectionProject } from \"../../persistence/Services/ProjectionProjects.ts\";\nimport { ProjectionState } from \"../../persistence/Services/ProjectionState.ts\";\nimport { ProjectionThreadActivity } from \"../../persistence/Services/ProjectionThreadActivities.ts\";\nimport { ProjectionThreadMessage } from \"../../persistence/Services/ProjectionThreadMessages.ts\";\nimport { ProjectionThreadProposedPlan } from \"../../persistence/Services/ProjectionThreadProposedPlans.ts\";\nimport { ProjectionThreadSession } from \"../../persistence/Services/ProjectionThreadSessions.ts\";\nimport { ProjectionThread } from \"../../persistence/Services/ProjectionThreads.ts\";\nimport * as RepositoryIdentityResolver from \"../../project/RepositoryIdentityResolver.ts\";\nimport { ORCHESTRATION_PROJECTOR_NAMES } from \"./ProjectionPipeline.ts\";\nimport {\n  ProjectionSnapshotQuery,\n  type ProjectionFullThreadDiffContext,\n  type ProjectionSnapshotCounts,\n  type ProjectionThreadCheckpointContext,\n  type ProjectionSnapshotQueryShape,\n} from \"../Services/ProjectionSnapshotQuery.ts\";\n\nconst decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);\nconst decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);\nconst decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);\nconst ProjectionProjectDbRowSchema = ProjectionProject.mapFields(\n  Struct.assign({\n    defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),\n    scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),\n  }),\n);\nconst ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(\n  Struct.assign({\n    isStreaming: Schema.Number,\n    attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),\n  }),\n);\nconst ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;\nconst ProjectionThreadDbRowSchema = ProjectionThread.mapFields(\n  Struct.assign({\n    modelSelection: Schema.fromJsonString(ModelSelection),\n  }),\n);\nconst ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(\n  Struct.assign({\n    payload: Schema.fromJsonString(Schema.Unknown),\n    sequence: Schema.NullOr(NonNegativeInt),\n  }),\n);\nconst ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;\nconst ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(\n  Struct.assign({\n    files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),\n  }),\n);\nconst ProjectionLatestTurnDbRowSchema = Schema.Struct({\n  threadId: ProjectionThread.fields.threadId,\n  turnId: TurnId,\n  state: Schema.String,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  assistantMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n});\nconst ProjectionStateDbRowSchema = ProjectionState;\nconst ProjectionCountsRowSchema = Schema.Struct({\n  projectCount: Schema.Number,\n  threadCount: Schema.Number,\n});\nconst ProjectionThreadSearchRequest = Schema.Struct({\n  pattern: Schema.String,\n  limit: Schema.Int,\n});\nconst ProjectionThreadSearchRow = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  source: OrchestrationThreadSearchSource,\n  matchText: Schema.String,\n  messageCreatedAt: Schema.NullOr(IsoDateTime),\n});\nconst WorkspaceRootLookupInput = Schema.Struct({\n  workspaceRoot: Schema.String,\n});\nconst ProjectIdLookupInput = Schema.Struct({\n  projectId: ProjectId,\n});\nconst ThreadIdLookupInput = Schema.Struct({\n  threadId: ThreadId,\n});\nconst ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;\nconst ProjectionThreadIdLookupRowSchema = Schema.Struct({\n  threadId: ThreadId,\n});\nconst ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  workspaceRoot: Schema.String,\n  worktreePath: Schema.NullOr(Schema.String),\n});\nconst FullThreadDiffContextLookupInput = Schema.Struct({\n  threadId: ThreadId,\n  checkpointTurnCount: NonNegativeInt,\n});\nconst ProjectionFullThreadDiffContextRowSchema = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  workspaceRoot: Schema.String,\n  worktreePath: Schema.NullOr(Schema.String),\n  latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),\n  toCheckpointRef: Schema.NullOr(CheckpointRef),\n});\n\nconst REQUIRED_SNAPSHOT_PROJECTORS = [\n  ORCHESTRATION_PROJECTOR_NAMES.projects,\n  ORCHESTRATION_PROJECTOR_NAMES.threads,\n  ORCHESTRATION_PROJECTOR_NAMES.threadMessages,\n  ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,\n  ORCHESTRATION_PROJECTOR_NAMES.threadActivities,\n  ORCHESTRATION_PROJECTOR_NAMES.threadSessions,\n  ORCHESTRATION_PROJECTOR_NAMES.checkpoints,\n] as const;\n\nfunction maxIso(left: string | null, right: string): string {\n  if (left === null) {\n    return right;\n  }\n  return left > right ? left : right;\n}\n\nfunction escapeLikePattern(value: string): string {\n  return value.replaceAll(\"!\", \"!!\").replaceAll(\"%\", \"!%\").replaceAll(\"_\", \"!_\");\n}\n\nfunction foldAsciiCase(value: string): string {\n  return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\nfunction buildSearchSnippet(text: string, query: string): string {\n  const normalizedText = text.replace(/\\s+/g, \" \").trim();\n  if (normalizedText.length <= 240) {\n    return normalizedText;\n  }\n\n  const normalizedQuery = foldAsciiCase(query.replace(/\\s+/g, \" \").trim());\n  const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);\n  const bodyLength = 236;\n  const idealStart = Math.max(0, matchIndex - 72);\n  const start = Math.min(idealStart, normalizedText.length - bodyLength);\n  const end = Math.min(normalizedText.length, start + bodyLength);\n  return `${start > 0 ? \"…\" : \"\"}${normalizedText.slice(start, end)}${\n    end < normalizedText.length ? \"…\" : \"\"\n  }`;\n}\n\nfunction computeSnapshotSequence(\n  stateRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionStateDbRowSchema>>,\n): number {\n  if (stateRows.length === 0) {\n    return 0;\n  }\n  const sequenceByProjector = new Map(\n    stateRows.map((row) => [row.projector, row.lastAppliedSequence] as const),\n  );\n\n  let minSequence = Number.POSITIVE_INFINITY;\n  for (const projector of REQUIRED_SNAPSHOT_PROJECTORS) {\n    const sequence = sequenceByProjector.get(projector);\n    if (sequence === undefined) {\n      return 0;\n    }\n    if (sequence < minSequence) {\n      minSequence = sequence;\n    }\n  }\n\n  return Number.isFinite(minSequence) ? minSequence : 0;\n}\n\nfunction mapLatestTurn(\n  row: Schema.Schema.Type<typeof ProjectionLatestTurnDbRowSchema>,\n): OrchestrationLatestTurn {\n  return {\n    turnId: row.turnId,\n    state:\n      row.state === \"error\"\n        ? \"error\"\n        : row.state === \"interrupted\"\n          ? \"interrupted\"\n          : row.state === \"completed\"\n            ? \"completed\"\n            : \"running\",\n    requestedAt: row.requestedAt,\n    startedAt: row.startedAt,\n    completedAt: row.completedAt,\n    assistantMessageId: row.assistantMessageId,\n    ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null\n      ? {\n          sourceProposedPlan: {\n            threadId: row.sourceProposedPlanThreadId,\n            planId: row.sourceProposedPlanId,\n          },\n        }\n      : {}),\n  };\n}\n\nfunction mapTitleRegeneration(row: Schema.Schema.Type<typeof ProjectionThreadDbRowSchema>) {\n  return row.titleRegenerationRequestId != null && row.titleRegenerationStartedAt != null\n    ? {\n        requestId: row.titleRegenerationRequestId,\n        startedAt: row.titleRegenerationStartedAt,\n      }\n    : null;\n}\n\nfunction mapSessionRow(\n  row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,\n): OrchestrationSession {\n  return {\n    threadId: row.threadId,\n    status: row.status,\n    providerName: row.providerName,\n    ...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),\n    runtimeMode: row.runtimeMode,\n    activeTurnId: row.activeTurnId,\n    lastError: row.lastError,\n    updatedAt: row.updatedAt,\n  };\n}\n\nfunction mapProjectShellRow(\n  row: Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>,\n  repositoryIdentity: OrchestrationProject[\"repositoryIdentity\"],\n): OrchestrationProjectShell {\n  return {\n    id: row.projectId,\n    title: row.title,\n    workspaceRoot: row.workspaceRoot,\n    repositoryIdentity,\n    defaultModelSelection: row.defaultModelSelection,\n    scripts: row.scripts,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n  };\n}\n\nfunction mapProposedPlanRow(\n  row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,\n): OrchestrationProposedPlan {\n  return {\n    id: row.planId,\n    turnId: row.turnId,\n    planMarkdown: row.planMarkdown,\n    implementedAt: row.implementedAt,\n    implementationThreadId: row.implementationThreadId,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n  };\n}\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown): ProjectionRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeProjectionSnapshotQuery = Effect.gen(function* () {\n  const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;\n  const sql = yield* SqlClient.SqlClient;\n  const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;\n  const repositoryIdentityResolutionConcurrency = 4;\n  const resolveRepositoryIdentitiesForProjects = Effect.fn(\n    \"ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects\",\n  )(function* (\n    projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,\n    options?: {\n      readonly includeDeleted?: boolean;\n    },\n  ) {\n    const filteredProjectRows =\n      options?.includeDeleted === true\n        ? projectRows\n        : projectRows.filter((row) => row.deletedAt === null);\n    const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];\n    const repositoryIdentityByWorkspaceRoot = new Map(\n      yield* Effect.forEach(\n        uniqueWorkspaceRoots,\n        (workspaceRoot) =>\n          repositoryIdentityResolver\n            .resolve(workspaceRoot)\n            .pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),\n        { concurrency: repositoryIdentityResolutionConcurrency },\n      ),\n    );\n\n    return new Map(\n      filteredProjectRows.map((row) => [\n        row.projectId,\n        repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,\n      ]),\n    );\n  });\n\n  const listProjectRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionProjectDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        ORDER BY created_at ASC, project_id ASC\n      `,\n  });\n\n  const listThreadRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        ORDER BY created_at ASC, thread_id ASC\n      `,\n  });\n\n  const listActiveThreadRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE deleted_at IS NULL\n          AND archived_at IS NULL\n        ORDER BY project_id ASC, created_at ASC, thread_id ASC\n      `,\n  });\n\n  const listArchivedThreadRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE deleted_at IS NULL\n          AND archived_at IS NOT NULL\n        ORDER BY project_id ASC, archived_at DESC, thread_id DESC\n      `,\n  });\n\n  const listThreadMessageRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        ORDER BY thread_id ASC, created_at ASC, message_id ASC\n      `,\n  });\n\n  const listThreadProposedPlanRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadProposedPlanDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          plan_id AS \"planId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          plan_markdown AS \"planMarkdown\",\n          implemented_at AS \"implementedAt\",\n          implementation_thread_id AS \"implementationThreadId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_proposed_plans\n        ORDER BY thread_id ASC, created_at ASC, plan_id ASC\n      `,\n  });\n\n  const listThreadActivityRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        ORDER BY\n          thread_id ASC,\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const listThreadSessionRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          status,\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          provider_session_id AS \"providerSessionId\",\n          provider_thread_id AS \"providerThreadId\",\n          runtime_mode AS \"runtimeMode\",\n          active_turn_id AS \"activeTurnId\",\n          last_error AS \"lastError\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions\n        ORDER BY thread_id ASC\n      `,\n  });\n\n  const listActiveThreadSessionRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          sessions.thread_id AS \"threadId\",\n          sessions.status,\n          sessions.provider_name AS \"providerName\",\n          sessions.provider_instance_id AS \"providerInstanceId\",\n          sessions.provider_session_id AS \"providerSessionId\",\n          sessions.provider_thread_id AS \"providerThreadId\",\n          sessions.runtime_mode AS \"runtimeMode\",\n          sessions.active_turn_id AS \"activeTurnId\",\n          sessions.last_error AS \"lastError\",\n          sessions.updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions sessions\n        INNER JOIN projection_threads threads\n          ON threads.thread_id = sessions.thread_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NULL\n        ORDER BY sessions.thread_id ASC\n      `,\n  });\n\n  const listArchivedThreadSessionRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          sessions.thread_id AS \"threadId\",\n          sessions.status,\n          sessions.provider_name AS \"providerName\",\n          sessions.provider_instance_id AS \"providerInstanceId\",\n          sessions.provider_session_id AS \"providerSessionId\",\n          sessions.provider_thread_id AS \"providerThreadId\",\n          sessions.runtime_mode AS \"runtimeMode\",\n          sessions.active_turn_id AS \"activeTurnId\",\n          sessions.last_error AS \"lastError\",\n          sessions.updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions sessions\n        INNER JOIN projection_threads threads\n          ON threads.thread_id = sessions.thread_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NOT NULL\n        ORDER BY sessions.thread_id ASC\n      `,\n  });\n\n  const listCheckpointRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionCheckpointDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"status\",\n          checkpoint_files_json AS \"files\",\n          assistant_message_id AS \"assistantMessageId\",\n          completed_at AS \"completedAt\"\n        FROM projection_turns\n        WHERE checkpoint_turn_count IS NOT NULL\n        ORDER BY thread_id ASC, checkpoint_turn_count ASC\n      `,\n  });\n\n  const listLatestTurnRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.latest_turn_id IS NOT NULL\n        ORDER BY turns.thread_id ASC\n      `,\n  });\n\n  const listActiveLatestTurnRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NULL\n          AND threads.latest_turn_id IS NOT NULL\n        ORDER BY turns.thread_id ASC\n      `,\n  });\n\n  const listArchivedLatestTurnRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NOT NULL\n          AND threads.latest_turn_id IS NOT NULL\n        ORDER BY turns.thread_id ASC\n      `,\n  });\n\n  const listProjectionStateRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionStateDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          projector,\n          last_applied_sequence AS \"lastAppliedSequence\",\n          updated_at AS \"updatedAt\"\n        FROM projection_state\n      `,\n  });\n\n  const readProjectionCounts = SqlSchema.findOne({\n    Request: Schema.Void,\n    Result: ProjectionCountsRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          (SELECT COUNT(*) FROM projection_projects) AS \"projectCount\",\n          (SELECT COUNT(*) FROM projection_threads) AS \"threadCount\"\n      `,\n  });\n\n  const searchActiveThreadRows = SqlSchema.findAll({\n    Request: ProjectionThreadSearchRequest,\n    Result: ProjectionThreadSearchRow,\n    execute: ({ pattern, limit }) =>\n      sql`\n        WITH ranked AS (\n          SELECT\n            threads.thread_id AS thread_id,\n            threads.project_id AS project_id,\n            CASE messages.role\n              WHEN 'user' THEN 'user'\n              ELSE 'assistant'\n            END AS source,\n            messages.text AS match_text,\n            messages.created_at AS message_created_at,\n            CASE messages.role\n              WHEN 'user' THEN 0\n              ELSE 1\n            END AS match_rank,\n            threads.updated_at AS thread_updated_at,\n            ROW_NUMBER() OVER (\n              PARTITION BY threads.thread_id\n              ORDER BY\n                CASE messages.role\n                  WHEN 'user' THEN 0\n                  ELSE 1\n                END ASC,\n                messages.created_at DESC,\n                messages.message_id ASC\n            ) AS thread_match_rank\n          FROM projection_thread_messages AS messages\n          INNER JOIN projection_threads AS threads\n            ON threads.thread_id = messages.thread_id\n          INNER JOIN projection_projects AS projects\n            ON projects.project_id = threads.project_id\n          WHERE threads.deleted_at IS NULL\n            AND threads.archived_at IS NULL\n            AND projects.deleted_at IS NULL\n            AND messages.is_streaming = 0\n            AND (\n              messages.role = 'user'\n              OR (\n                messages.role = 'assistant'\n                AND messages.message_id IN (\n                  SELECT turns.assistant_message_id\n                  FROM projection_turns AS turns\n                  WHERE turns.assistant_message_id IS NOT NULL\n                )\n              )\n            )\n            AND messages.text LIKE ${pattern} ESCAPE '!'\n        )\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          source,\n          match_text AS \"matchText\",\n          message_created_at AS \"messageCreatedAt\"\n        FROM ranked\n        WHERE thread_match_rank = 1\n        ORDER BY\n          match_rank ASC,\n          thread_updated_at DESC,\n          thread_id ASC\n        LIMIT ${limit}\n      `,\n  });\n\n  const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({\n    Request: WorkspaceRootLookupInput,\n    Result: ProjectionProjectLookupRowSchema,\n    execute: ({ workspaceRoot }) =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        WHERE workspace_root = ${workspaceRoot}\n          AND deleted_at IS NULL\n        ORDER BY created_at ASC, project_id ASC\n        LIMIT 1\n      `,\n  });\n\n  const getActiveProjectRowById = SqlSchema.findOneOption({\n    Request: ProjectIdLookupInput,\n    Result: ProjectionProjectLookupRowSchema,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        WHERE project_id = ${projectId}\n          AND deleted_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({\n    Request: ProjectIdLookupInput,\n    Result: ProjectionThreadIdLookupRowSchema,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\"\n        FROM projection_threads\n        WHERE project_id = ${projectId}\n          AND deleted_at IS NULL\n          AND archived_at IS NULL\n        ORDER BY created_at ASC, thread_id ASC\n        LIMIT 1\n      `,\n  });\n\n  const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadCheckpointContextThreadRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          threads.thread_id AS \"threadId\",\n          threads.project_id AS \"projectId\",\n          projects.workspace_root AS \"workspaceRoot\",\n          threads.worktree_path AS \"worktreePath\"\n        FROM projection_threads AS threads\n        INNER JOIN projection_projects AS projects\n          ON projects.project_id = threads.project_id\n        WHERE threads.thread_id = ${threadId}\n          AND threads.deleted_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const getActiveThreadRowById = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE thread_id = ${threadId}\n          AND deleted_at IS NULL\n          AND archived_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const listThreadMessageRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, message_id ASC\n      `,\n  });\n\n  const listThreadProposedPlanRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadProposedPlanDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          plan_id AS \"planId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          plan_markdown AS \"planMarkdown\",\n          implemented_at AS \"implementedAt\",\n          implementation_thread_id AS \"implementationThreadId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_proposed_plans\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, plan_id ASC\n      `,\n  });\n\n  const listThreadActivityRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n        ORDER BY\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const getThreadSessionRowByThread = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          status,\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          runtime_mode AS \"runtimeMode\",\n          active_turn_id AS \"activeTurnId\",\n          last_error AS \"lastError\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions\n        WHERE thread_id = ${threadId}\n        LIMIT 1\n      `,\n  });\n\n  const getLatestTurnRowByThread = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.thread_id = ${threadId}\n          AND threads.deleted_at IS NULL\n          AND threads.archived_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const listCheckpointRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionCheckpointDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"status\",\n          checkpoint_files_json AS \"files\",\n          assistant_message_id AS \"assistantMessageId\",\n          completed_at AS \"completedAt\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND checkpoint_turn_count IS NOT NULL\n        ORDER BY checkpoint_turn_count ASC\n      `,\n  });\n\n  const getFullThreadDiffContextRow = SqlSchema.findOneOption({\n    Request: FullThreadDiffContextLookupInput,\n    Result: ProjectionFullThreadDiffContextRowSchema,\n    execute: ({ threadId, checkpointTurnCount }) =>\n      sql`\n        SELECT\n          threads.thread_id AS \"threadId\",\n          threads.project_id AS \"projectId\",\n          projects.workspace_root AS \"workspaceRoot\",\n          threads.worktree_path AS \"worktreePath\",\n          (\n            SELECT MAX(turns.checkpoint_turn_count)\n            FROM projection_turns AS turns\n            WHERE turns.thread_id = threads.thread_id\n              AND turns.checkpoint_turn_count IS NOT NULL\n          ) AS \"latestCheckpointTurnCount\",\n          (\n            SELECT turns.checkpoint_ref\n            FROM projection_turns AS turns\n            WHERE turns.thread_id = threads.thread_id\n              AND turns.checkpoint_turn_count = ${checkpointTurnCount}\n            LIMIT 1\n          ) AS \"toCheckpointRef\"\n        FROM projection_threads AS threads\n        INNER JOIN projection_projects AS projects\n          ON projects.project_id = threads.project_id\n        WHERE threads.thread_id = ${threadId}\n          AND threads.deleted_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const getSnapshot: ProjectionSnapshotQueryShape[\"getSnapshot\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listProjects:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreads:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadMessageRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadProposedPlanRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadActivityRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listCheckpointRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows\",\n              ),\n            ),\n          ),\n          listLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(\n          ([\n            projectRows,\n            threadRows,\n            messageRows,\n            proposedPlanRows,\n            activityRows,\n            sessionRows,\n            checkpointRows,\n            latestTurnRows,\n            stateRows,\n          ]) =>\n            Effect.gen(function* () {\n              const messagesByThread = new Map<string, Array<OrchestrationMessage>>();\n              const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();\n              const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();\n              const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();\n              const sessionsByThread = new Map<string, OrchestrationSession>();\n              const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();\n\n              let updatedAt: string | null = null;\n\n              for (const row of projectRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (const row of threadRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (const row of stateRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n\n              for (const row of messageRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                const threadMessages = messagesByThread.get(row.threadId) ?? [];\n                threadMessages.push({\n                  id: row.messageId,\n                  role: row.role,\n                  text: row.text,\n                  ...(row.attachments !== null ? { attachments: row.attachments } : {}),\n                  turnId: row.turnId,\n                  streaming: row.isStreaming === 1,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                });\n                messagesByThread.set(row.threadId, threadMessages);\n              }\n\n              for (const row of proposedPlanRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];\n                threadProposedPlans.push({\n                  id: row.planId,\n                  turnId: row.turnId,\n                  planMarkdown: row.planMarkdown,\n                  implementedAt: row.implementedAt,\n                  implementationThreadId: row.implementationThreadId,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                });\n                proposedPlansByThread.set(row.threadId, threadProposedPlans);\n              }\n\n              for (const row of activityRows) {\n                updatedAt = maxIso(updatedAt, row.createdAt);\n                const threadActivities = activitiesByThread.get(row.threadId) ?? [];\n                threadActivities.push({\n                  id: row.activityId,\n                  tone: row.tone,\n                  kind: row.kind,\n                  summary: row.summary,\n                  payload: row.payload,\n                  turnId: row.turnId,\n                  ...(row.sequence !== null ? { sequence: row.sequence } : {}),\n                  createdAt: row.createdAt,\n                });\n                activitiesByThread.set(row.threadId, threadActivities);\n              }\n\n              for (const row of checkpointRows) {\n                updatedAt = maxIso(updatedAt, row.completedAt);\n                const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];\n                threadCheckpoints.push({\n                  turnId: row.turnId,\n                  checkpointTurnCount: row.checkpointTurnCount,\n                  checkpointRef: row.checkpointRef,\n                  status: row.status,\n                  files: row.files,\n                  assistantMessageId: row.assistantMessageId,\n                  completedAt: row.completedAt,\n                });\n                checkpointsByThread.set(row.threadId, threadCheckpoints);\n              }\n\n              for (const row of latestTurnRows) {\n                updatedAt = maxIso(updatedAt, row.requestedAt);\n                if (row.startedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.startedAt);\n                }\n                if (row.completedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.completedAt);\n                }\n                if (latestTurnByThread.has(row.threadId)) {\n                  continue;\n                }\n                latestTurnByThread.set(row.threadId, {\n                  turnId: row.turnId,\n                  state:\n                    row.state === \"error\"\n                      ? \"error\"\n                      : row.state === \"interrupted\"\n                        ? \"interrupted\"\n                        : row.state === \"completed\"\n                          ? \"completed\"\n                          : \"running\",\n                  requestedAt: row.requestedAt,\n                  startedAt: row.startedAt,\n                  completedAt: row.completedAt,\n                  assistantMessageId: row.assistantMessageId,\n                  ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null\n                    ? {\n                        sourceProposedPlan: {\n                          threadId: row.sourceProposedPlanThreadId,\n                          planId: row.sourceProposedPlanId,\n                        },\n                      }\n                    : {}),\n                });\n              }\n\n              for (const row of sessionRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                sessionsByThread.set(row.threadId, {\n                  threadId: row.threadId,\n                  status: row.status,\n                  providerName: row.providerName,\n                  ...(row.providerInstanceId !== null\n                    ? { providerInstanceId: row.providerInstanceId }\n                    : {}),\n                  runtimeMode: row.runtimeMode,\n                  activeTurnId: row.activeTurnId,\n                  lastError: row.lastError,\n                  updatedAt: row.updatedAt,\n                });\n              }\n\n              const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(\n                projectRows,\n                { includeDeleted: true },\n              );\n\n              const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({\n                id: row.projectId,\n                title: row.title,\n                workspaceRoot: row.workspaceRoot,\n                repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,\n                defaultModelSelection: row.defaultModelSelection,\n                scripts: row.scripts,\n                createdAt: row.createdAt,\n                updatedAt: row.updatedAt,\n                deletedAt: row.deletedAt,\n              }));\n\n              const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({\n                id: row.threadId,\n                projectId: row.projectId,\n                title: row.title,\n                modelSelection: row.modelSelection,\n                runtimeMode: row.runtimeMode,\n                interactionMode: row.interactionMode,\n                branch: row.branch,\n                worktreePath: row.worktreePath,\n                latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                createdAt: row.createdAt,\n                updatedAt: row.updatedAt,\n                archivedAt: row.archivedAt,\n                settledOverride: row.settledOverride,\n                settledAt: row.settledAt,\n                snoozedUntil: row.snoozedUntil,\n                snoozedAt: row.snoozedAt,\n                pinnedAt: row.pinnedAt,\n                titleRegeneration: mapTitleRegeneration(row),\n                deletedAt: row.deletedAt,\n                messages: messagesByThread.get(row.threadId) ?? [],\n                proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],\n                activities: activitiesByThread.get(row.threadId) ?? [],\n                checkpoints: checkpointsByThread.get(row.threadId) ?? [],\n                session: sessionsByThread.get(row.threadId) ?? null,\n              }));\n\n              const snapshot = {\n                snapshotSequence: computeSnapshotSequence(stateRows),\n                projects,\n                threads,\n                updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n              };\n\n              return yield* decodeReadModel(snapshot).pipe(\n                Effect.mapError(\n                  toPersistenceDecodeError(\"ProjectionSnapshotQuery.getSnapshot:decodeReadModel\"),\n                ),\n              );\n            }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getSnapshot:query\")(error);\n        }),\n      );\n\n  const getCommandReadModel: ProjectionSnapshotQueryShape[\"getCommandReadModel\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjects:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreads:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadProposedPlanRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(\n          ([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>\n            Effect.sync(() => {\n              let updatedAt: string | null = null;\n              const projects: OrchestrationProject[] = [];\n              const threads: OrchestrationThread[] = [];\n\n              for (let index = 0; index < projectRows.length; index += 1) {\n                const row = projectRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                projects.push({\n                  id: row.projectId,\n                  title: row.title,\n                  workspaceRoot: row.workspaceRoot,\n                  defaultModelSelection: row.defaultModelSelection,\n                  scripts: row.scripts,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                  deletedAt: row.deletedAt,\n                });\n              }\n              for (let index = 0; index < threadRows.length; index += 1) {\n                const row = threadRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (let index = 0; index < proposedPlanRows.length; index += 1) {\n                const row = proposedPlanRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (let index = 0; index < sessionRows.length; index += 1) {\n                const row = sessionRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (let index = 0; index < latestTurnRows.length; index += 1) {\n                const row = latestTurnRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.requestedAt);\n                if (row.startedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.startedAt);\n                }\n                if (row.completedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.completedAt);\n                }\n              }\n              for (let index = 0; index < stateRows.length; index += 1) {\n                const row = stateRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n\n              const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();\n              for (let index = 0; index < latestTurnRows.length; index += 1) {\n                const row = latestTurnRows[index];\n                if (!row) {\n                  continue;\n                }\n                latestTurnByThread.set(row.threadId, mapLatestTurn(row));\n              }\n              const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();\n              const sessionByThread = new Map<string, OrchestrationSession>();\n\n              for (let index = 0; index < sessionRows.length; index += 1) {\n                const row = sessionRows[index];\n                if (!row) {\n                  continue;\n                }\n                sessionByThread.set(row.threadId, mapSessionRow(row));\n              }\n\n              for (let index = 0; index < proposedPlanRows.length; index += 1) {\n                const row = proposedPlanRows[index];\n                if (!row) {\n                  continue;\n                }\n                const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];\n                threadProposedPlans.push(mapProposedPlanRow(row));\n                proposedPlansByThread.set(row.threadId, threadProposedPlans);\n              }\n\n              for (let index = 0; index < threadRows.length; index += 1) {\n                const row = threadRows[index];\n                if (!row) {\n                  continue;\n                }\n                threads.push({\n                  id: row.threadId,\n                  projectId: row.projectId,\n                  title: row.title,\n                  modelSelection: row.modelSelection,\n                  runtimeMode: row.runtimeMode,\n                  interactionMode: row.interactionMode,\n                  branch: row.branch,\n                  worktreePath: row.worktreePath,\n                  latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                  archivedAt: row.archivedAt,\n                  settledOverride: row.settledOverride,\n                  settledAt: row.settledAt,\n                  snoozedUntil: row.snoozedUntil,\n                  snoozedAt: row.snoozedAt,\n                  pinnedAt: row.pinnedAt,\n                  titleRegeneration: mapTitleRegeneration(row),\n                  deletedAt: row.deletedAt,\n                  messages: [],\n                  proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],\n                  activities: [],\n                  checkpoints: [],\n                  session: sessionByThread.get(row.threadId) ?? null,\n                });\n              }\n\n              return {\n                snapshotSequence: computeSnapshotSequence(stateRows),\n                projects,\n                threads,\n                updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n              } satisfies OrchestrationReadModel;\n            }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getCommandReadModel:query\")(error);\n        }),\n      );\n\n  const getShellSnapshot: ProjectionSnapshotQueryShape[\"getShellSnapshot\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjects:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listActiveThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listActiveThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listActiveLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>\n          Effect.gen(function* () {\n            let updatedAt: string | null = null;\n            for (const row of projectRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of threadRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of sessionRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of latestTurnRows) {\n              updatedAt = maxIso(updatedAt, row.requestedAt);\n              if (row.startedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.startedAt);\n              }\n              if (row.completedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.completedAt);\n              }\n            }\n            for (const row of stateRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n\n            const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);\n            const latestTurnByThread = new Map(\n              latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),\n            );\n            const sessionByThread = new Map(\n              sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),\n            );\n\n            const snapshot = {\n              snapshotSequence: computeSnapshotSequence(stateRows),\n              projects: Arr.filterMap(projectRows, (row) =>\n                row.deletedAt === null\n                  ? Result.succeed(\n                      mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),\n                    )\n                  : Result.failVoid,\n              ),\n              threads: Arr.filterMap(threadRows, (row) =>\n                row.deletedAt === null\n                  ? Result.succeed({\n                      id: row.threadId,\n                      projectId: row.projectId,\n                      title: row.title,\n                      modelSelection: row.modelSelection,\n                      runtimeMode: row.runtimeMode,\n                      interactionMode: row.interactionMode,\n                      branch: row.branch,\n                      worktreePath: row.worktreePath,\n                      latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                      createdAt: row.createdAt,\n                      updatedAt: row.updatedAt,\n                      archivedAt: row.archivedAt,\n                      settledOverride: row.settledOverride,\n                      settledAt: row.settledAt,\n                      snoozedUntil: row.snoozedUntil,\n                      snoozedAt: row.snoozedAt,\n                      pinnedAt: row.pinnedAt,\n                      titleRegeneration: mapTitleRegeneration(row),\n                      session: sessionByThread.get(row.threadId) ?? null,\n                      latestUserMessageAt: row.latestUserMessageAt,\n                      hasPendingApprovals: row.pendingApprovalCount > 0,\n                      hasPendingUserInput: row.pendingUserInputCount > 0,\n                      hasActionableProposedPlan: row.hasActionableProposedPlan > 0,\n                      backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(\n                        row.threadId,\n                      ),\n                    } satisfies OrchestrationThreadShell)\n                  : Result.failVoid,\n              ),\n              updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n            };\n\n            return yield* decodeShellSnapshot(snapshot).pipe(\n              Effect.mapError(\n                toPersistenceDecodeError(\n                  \"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot\",\n                ),\n              ),\n            );\n          }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getShellSnapshot:query\")(error);\n        }),\n      );\n\n  const getArchivedShellSnapshot: ProjectionSnapshotQueryShape[\"getArchivedShellSnapshot\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listArchivedThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listArchivedThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listArchivedLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>\n          Effect.gen(function* () {\n            let updatedAt: string | null = null;\n            for (const row of projectRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of threadRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of sessionRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of latestTurnRows) {\n              updatedAt = maxIso(updatedAt, row.requestedAt);\n              if (row.startedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.startedAt);\n              }\n              if (row.completedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.completedAt);\n              }\n            }\n            for (const row of stateRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n\n            const activeProjectIds = new Set(threadRows.map((row) => row.projectId));\n            const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(\n              projectRows.filter((row) => activeProjectIds.has(row.projectId)),\n            );\n            const latestTurnByThread = new Map(\n              latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),\n            );\n            const sessionByThread = new Map(\n              sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),\n            );\n\n            const snapshot = {\n              snapshotSequence: computeSnapshotSequence(stateRows),\n              projects: Arr.filterMap(projectRows, (row) =>\n                row.deletedAt === null && activeProjectIds.has(row.projectId)\n                  ? Result.succeed(\n                      mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),\n                    )\n                  : Result.failVoid,\n              ),\n              threads: threadRows.map(\n                (row): OrchestrationThreadShell => ({\n                  id: row.threadId,\n                  projectId: row.projectId,\n                  title: row.title,\n                  modelSelection: row.modelSelection,\n                  runtimeMode: row.runtimeMode,\n                  interactionMode: row.interactionMode,\n                  branch: row.branch,\n                  worktreePath: row.worktreePath,\n                  latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                  archivedAt: row.archivedAt,\n                  settledOverride: row.settledOverride,\n                  settledAt: row.settledAt,\n                  snoozedUntil: row.snoozedUntil,\n                  snoozedAt: row.snoozedAt,\n                  pinnedAt: row.pinnedAt,\n                  titleRegeneration: mapTitleRegeneration(row),\n                  session: sessionByThread.get(row.threadId) ?? null,\n                  latestUserMessageAt: row.latestUserMessageAt,\n                  hasPendingApprovals: row.pendingApprovalCount > 0,\n                  hasPendingUserInput: row.pendingUserInputCount > 0,\n                  hasActionableProposedPlan: row.hasActionableProposedPlan > 0,\n                  backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(\n                    row.threadId,\n                  ),\n                }),\n              ),\n              updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n            };\n\n            return yield* decodeShellSnapshot(snapshot).pipe(\n              Effect.mapError(\n                toPersistenceDecodeError(\n                  \"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot\",\n                ),\n              ),\n            );\n          }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getArchivedShellSnapshot:query\")(\n            error,\n          );\n        }),\n      );\n\n  const getSnapshotSequence: ProjectionSnapshotQueryShape[\"getSnapshotSequence\"] = () =>\n    listProjectionStateRows(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.getSnapshotSequence:query\",\n          \"ProjectionSnapshotQuery.getSnapshotSequence:decodeRows\",\n        ),\n      ),\n      Effect.map((stateRows) => ({\n        snapshotSequence: computeSnapshotSequence(stateRows),\n      })),\n    );\n\n  const getCounts: ProjectionSnapshotQueryShape[\"getCounts\"] = () =>\n    readProjectionCounts(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.getCounts:query\",\n          \"ProjectionSnapshotQuery.getCounts:decodeRow\",\n        ),\n      ),\n      Effect.map(\n        (row): ProjectionSnapshotCounts => ({\n          projectCount: row.projectCount,\n          threadCount: row.threadCount,\n        }),\n      ),\n    );\n\n  const searchThreads: ProjectionSnapshotQueryShape[\"searchThreads\"] = Effect.fn(\n    \"ProjectionSnapshotQuery.searchThreads\",\n  )(function* (input) {\n    const escapedQuery = escapeLikePattern(input.query);\n    const rows = yield* searchActiveThreadRows({\n      pattern: `%${escapedQuery}%`,\n      limit: input.limit ?? 50,\n    }).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.searchThreads:query\",\n          \"ProjectionSnapshotQuery.searchThreads:decodeRows\",\n        ),\n      ),\n    );\n    return {\n      matches: rows.map((row) => ({\n        threadId: row.threadId,\n        projectId: row.projectId,\n        source: row.source,\n        snippet: buildSearchSnippet(row.matchText, input.query),\n        messageCreatedAt: row.messageCreatedAt,\n      })),\n    };\n  });\n\n  const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape[\"getActiveProjectByWorkspaceRoot\"] =\n    (workspaceRoot) =>\n      getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query\",\n            \"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow\",\n          ),\n        ),\n        Effect.flatMap((option) =>\n          Option.isNone(option)\n            ? Effect.succeed(Option.none<OrchestrationProject>())\n            : repositoryIdentityResolver.resolve(option.value.workspaceRoot).pipe(\n                Effect.map((repositoryIdentity) =>\n                  Option.some({\n                    id: option.value.projectId,\n                    title: option.value.title,\n                    workspaceRoot: option.value.workspaceRoot,\n                    repositoryIdentity,\n                    defaultModelSelection: option.value.defaultModelSelection,\n                    scripts: option.value.scripts,\n                    createdAt: option.value.createdAt,\n                    updatedAt: option.value.updatedAt,\n                    deletedAt: option.value.deletedAt,\n                  } satisfies OrchestrationProject),\n                ),\n              ),\n        ),\n      );\n\n  const getProjectShellById: ProjectionSnapshotQueryShape[\"getProjectShellById\"] = (projectId) =>\n    getActiveProjectRowById({ projectId }).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.getProjectShellById:query\",\n          \"ProjectionSnapshotQuery.getProjectShellById:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((option) =>\n        Option.isNone(option)\n          ? Effect.succeed(Option.none<OrchestrationProjectShell>())\n          : repositoryIdentityResolver\n              .resolve(option.value.workspaceRoot)\n              .pipe(\n                Effect.map((repositoryIdentity) =>\n                  Option.some(mapProjectShellRow(option.value, repositoryIdentity)),\n                ),\n              ),\n      ),\n    );\n\n  const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape[\"getFirstActiveThreadIdByProjectId\"] =\n    (projectId) =>\n      getFirstActiveThreadIdByProject({ projectId }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query\",\n            \"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow\",\n          ),\n        ),\n        Effect.map(Option.map((row) => row.threadId)),\n      );\n\n  const getThreadCheckpointContext: ProjectionSnapshotQueryShape[\"getThreadCheckpointContext\"] = (\n    threadId,\n  ) =>\n    Effect.gen(function* () {\n      const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query\",\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow\",\n          ),\n        ),\n      );\n      if (Option.isNone(threadRow)) {\n        return Option.none<ProjectionThreadCheckpointContext>();\n      }\n\n      const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query\",\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows\",\n          ),\n        ),\n      );\n\n      return Option.some({\n        threadId: threadRow.value.threadId,\n        projectId: threadRow.value.projectId,\n        workspaceRoot: threadRow.value.workspaceRoot,\n        worktreePath: threadRow.value.worktreePath,\n        checkpoints: checkpointRows.map(\n          (row): OrchestrationCheckpointSummary => ({\n            turnId: row.turnId,\n            checkpointTurnCount: row.checkpointTurnCount,\n            checkpointRef: row.checkpointRef,\n            status: row.status,\n            files: row.files,\n            assistantMessageId: row.assistantMessageId,\n            completedAt: row.completedAt,\n          }),\n        ),\n      });\n    });\n\n  const getFullThreadDiffContext: NonNullable<\n    ProjectionSnapshotQueryShape[\"getFullThreadDiffContext\"]\n  > = (threadId, toTurnCount) =>\n    Effect.gen(function* () {\n      const row = yield* getFullThreadDiffContextRow({\n        threadId,\n        checkpointTurnCount: toTurnCount,\n      }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getFullThreadDiffContext:query\",\n            \"ProjectionSnapshotQuery.getFullThreadDiffContext:decodeRow\",\n          ),\n        ),\n      );\n      if (Option.isNone(row)) {\n        return Option.none<ProjectionFullThreadDiffContext>();\n      }\n\n      return Option.some({\n        threadId: row.value.threadId,\n        projectId: row.value.projectId,\n        workspaceRoot: row.value.workspaceRoot,\n        worktreePath: row.value.worktreePath,\n        latestCheckpointTurnCount: row.value.latestCheckpointTurnCount ?? 0,\n        toCheckpointRef: row.value.toCheckpointRef,\n      });\n    });\n\n  const getThreadShellById: ProjectionSnapshotQueryShape[\"getThreadShellById\"] = (threadId) =>\n    Effect.gen(function* () {\n      const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([\n        getActiveThreadRowById({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadShellById:getThread:query\",\n              \"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow\",\n            ),\n          ),\n        ),\n        getLatestTurnRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query\",\n              \"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow\",\n            ),\n          ),\n        ),\n        getThreadSessionRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadShellById:getSession:query\",\n              \"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow\",\n            ),\n          ),\n        ),\n      ]);\n\n      if (Option.isNone(threadRow)) {\n        return Option.none<OrchestrationThreadShell>();\n      }\n\n      return Option.some({\n        id: threadRow.value.threadId,\n        projectId: threadRow.value.projectId,\n        title: threadRow.value.title,\n        modelSelection: threadRow.value.modelSelection,\n        runtimeMode: threadRow.value.runtimeMode,\n        interactionMode: threadRow.value.interactionMode,\n        branch: threadRow.value.branch,\n        worktreePath: threadRow.value.worktreePath,\n        latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,\n        createdAt: threadRow.value.createdAt,\n        updatedAt: threadRow.value.updatedAt,\n        archivedAt: threadRow.value.archivedAt,\n        settledOverride: threadRow.value.settledOverride,\n        settledAt: threadRow.value.settledAt,\n        snoozedUntil: threadRow.value.snoozedUntil,\n        snoozedAt: threadRow.value.snoozedAt,\n        pinnedAt: threadRow.value.pinnedAt,\n        titleRegeneration: mapTitleRegeneration(threadRow.value),\n        session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,\n        latestUserMessageAt: threadRow.value.latestUserMessageAt,\n        hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,\n        hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,\n        hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,\n        backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(\n          threadRow.value.threadId,\n        ),\n      } satisfies OrchestrationThreadShell);\n    });\n\n  const getThreadDetailById: ProjectionSnapshotQueryShape[\"getThreadDetailById\"] = (threadId) =>\n    Effect.gen(function* () {\n      const [\n        threadRow,\n        messageRows,\n        proposedPlanRows,\n        activityRows,\n        checkpointRows,\n        latestTurnRow,\n        sessionRow,\n      ] = yield* Effect.all([\n        getActiveThreadRowById({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:getThread:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:getThread:decodeRow\",\n            ),\n          ),\n        ),\n        listThreadMessageRowsByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listMessages:decodeRows\",\n            ),\n          ),\n        ),\n        listThreadProposedPlanRowsByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listPlans:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listPlans:decodeRows\",\n            ),\n          ),\n        ),\n        listThreadActivityRowsByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows\",\n            ),\n          ),\n        ),\n        listCheckpointRowsByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:decodeRows\",\n            ),\n          ),\n        ),\n        getLatestTurnRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:decodeRow\",\n            ),\n          ),\n        ),\n        getThreadSessionRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:getSession:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:getSession:decodeRow\",\n            ),\n          ),\n        ),\n      ]);\n\n      if (Option.isNone(threadRow)) {\n        return Option.none<OrchestrationThread>();\n      }\n\n      const thread = {\n        id: threadRow.value.threadId,\n        projectId: threadRow.value.projectId,\n        title: threadRow.value.title,\n        modelSelection: threadRow.value.modelSelection,\n        runtimeMode: threadRow.value.runtimeMode,\n        interactionMode: threadRow.value.interactionMode,\n        branch: threadRow.value.branch,\n        worktreePath: threadRow.value.worktreePath,\n        latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,\n        createdAt: threadRow.value.createdAt,\n        updatedAt: threadRow.value.updatedAt,\n        archivedAt: threadRow.value.archivedAt,\n        settledOverride: threadRow.value.settledOverride,\n        settledAt: threadRow.value.settledAt,\n        snoozedUntil: threadRow.value.snoozedUntil,\n        snoozedAt: threadRow.value.snoozedAt,\n        pinnedAt: threadRow.value.pinnedAt,\n        titleRegeneration: mapTitleRegeneration(threadRow.value),\n        deletedAt: null,\n        messages: messageRows.map((row) => {\n          const message = {\n            id: row.messageId,\n            role: row.role,\n            text: row.text,\n            turnId: row.turnId,\n            streaming: row.isStreaming === 1,\n            createdAt: row.createdAt,\n            updatedAt: row.updatedAt,\n          };\n          if (row.attachments !== null) {\n            return Object.assign(message, { attachments: row.attachments });\n          }\n          return message;\n        }),\n        proposedPlans: proposedPlanRows.map(mapProposedPlanRow),\n        activities: activityRows.map((row) => {\n          const activity = {\n            id: row.activityId,\n            tone: row.tone,\n            kind: row.kind,\n            summary: row.summary,\n            payload: row.payload,\n            turnId: row.turnId,\n            createdAt: row.createdAt,\n          };\n          if (row.sequence !== null) {\n            return Object.assign(activity, { sequence: row.sequence });\n          }\n          return activity;\n        }),\n        checkpoints: checkpointRows.map((row) => ({\n          turnId: row.turnId,\n          checkpointTurnCount: row.checkpointTurnCount,\n          checkpointRef: row.checkpointRef,\n          status: row.status,\n          files: row.files,\n          assistantMessageId: row.assistantMessageId,\n          completedAt: row.completedAt,\n        })),\n        session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,\n      };\n\n      return Option.some(\n        yield* decodeThread(thread).pipe(\n          Effect.mapError(\n            toPersistenceDecodeError(\"ProjectionSnapshotQuery.getThreadDetailById:decodeThread\"),\n          ),\n        ),\n      );\n    });\n\n  const getThreadDetailSnapshot: ProjectionSnapshotQueryShape[\"getThreadDetailSnapshot\"] = (\n    threadId,\n  ) =>\n    // Read the thread detail and the snapshot sequence within a single\n    // transaction so the sequence is consistent with the returned state; a\n    // projector update landing between two separate reads could otherwise return\n    // a sequence ahead of the thread detail, causing the client to resume from\n    // too far and drop events.\n    sql\n      .withTransaction(\n        Effect.gen(function* () {\n          const thread = yield* getThreadDetailById(threadId);\n          if (Option.isNone(thread)) {\n            return Option.none<OrchestrationThreadDetailSnapshot>();\n          }\n          const { snapshotSequence } = yield* getSnapshotSequence();\n          return Option.some({ snapshotSequence, thread: thread.value });\n        }),\n      )\n      .pipe(\n        Effect.mapError((error) =>\n          isPersistenceError(error)\n            ? error\n            : toPersistenceSqlError(\"ProjectionSnapshotQuery.getThreadDetailSnapshot:transaction\")(\n                error,\n              ),\n        ),\n      );\n\n  return {\n    getCommandReadModel,\n    getSnapshot,\n    getShellSnapshot,\n    getArchivedShellSnapshot,\n    searchThreads,\n    getSnapshotSequence,\n    getCounts,\n    getActiveProjectByWorkspaceRoot,\n    getProjectShellById,\n    getFirstActiveThreadIdByProjectId,\n    getThreadCheckpointContext,\n    getFullThreadDiffContext,\n    getThreadShellById,\n    getThreadDetailById,\n    getThreadDetailSnapshot,\n  } satisfies ProjectionSnapshotQueryShape;\n});\n\nexport const OrchestrationProjectionSnapshotQueryLive = Layer.effect(\n  ProjectionSnapshotQuery,\n  makeProjectionSnapshotQuery,\n);\n","import * as Layer from \"effect/Layer\";\n\nimport { OrchestrationCommandReceiptRepositoryLive } from \"../persistence/Layers/OrchestrationCommandReceipts.ts\";\nimport { OrchestrationEventStoreLive } from \"../persistence/Layers/OrchestrationEventStore.ts\";\nimport { OrchestrationEngineLive } from \"./Layers/OrchestrationEngine.ts\";\nimport { OrchestrationProjectionPipelineLive } from \"./Layers/ProjectionPipeline.ts\";\nimport { OrchestrationProjectionSnapshotQueryLive } from \"./Layers/ProjectionSnapshotQuery.ts\";\nimport * as ThreadBackgroundLiveness from \"./ThreadBackgroundLiveness.ts\";\n\nexport const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(\n  OrchestrationEventStoreLive,\n  OrchestrationCommandReceiptRepositoryLive,\n);\n\nexport const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(\n  Layer.provide(OrchestrationEventStoreLive),\n);\n\nexport const OrchestrationInfrastructureLayerLive = Layer.mergeAll(\n  OrchestrationProjectionSnapshotQueryLive,\n  OrchestrationEventInfrastructureLayerLive,\n  OrchestrationProjectionPipelineLayerLive,\n  // Shared background-liveness registry: written by runtime ingestion,\n  // read by the snapshot query. provideMerge feeds the same instance to\n  // the snapshot query here and re-exports it for runtime ingestion.\n).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));\n\nexport const OrchestrationLayerLive = Layer.mergeAll(\n  OrchestrationInfrastructureLayerLive,\n  OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),\n);\n","import {\n  type KeybindingRule,\n  type KeybindingShortcut,\n  type KeybindingWhenNode,\n  MAX_KEYBINDINGS_COUNT,\n  MAX_WHEN_EXPRESSION_DEPTH,\n  MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,\n  type ResolvedKeybindingRule,\n  type ResolvedKeybindingsConfig,\n  THREAD_JUMP_KEYBINDING_COMMANDS,\n} from \"@t3tools/contracts\";\n\ntype WhenToken =\n  | { type: \"identifier\"; value: string }\n  | { type: \"not\" }\n  | { type: \"and\" }\n  | { type: \"or\" }\n  | { type: \"lparen\" }\n  | { type: \"rparen\" };\n\nexport const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [\n  { key: \"mod+b\", command: \"sidebar.toggle\" },\n  { key: \"mod+j\", command: \"terminal.toggle\" },\n  { key: \"mod+alt+b\", command: \"rightPanel.toggle\" },\n  { key: \"mod+d\", command: \"terminal.split\", when: \"terminalFocus\" },\n  { key: \"mod+shift+d\", command: \"terminal.splitVertical\", when: \"terminalFocus\" },\n  { key: \"mod+n\", command: \"terminal.new\", when: \"terminalFocus\" },\n  { key: \"mod+w\", command: \"terminal.close\", when: \"terminalFocus\" },\n  { key: \"mod+d\", command: \"diff.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+j\", command: \"preview.toggle\" },\n  { key: \"mod+r\", command: \"preview.refresh\", when: \"previewFocus\" },\n  { key: \"mod+l\", command: \"preview.focusUrl\", when: \"previewFocus\" },\n  { key: \"mod+=\", command: \"preview.zoomIn\", when: \"previewFocus\" },\n  { key: \"mod++\", command: \"preview.zoomIn\", when: \"previewFocus\" },\n  { key: \"mod+-\", command: \"preview.zoomOut\", when: \"previewFocus\" },\n  { key: \"mod+0\", command: \"preview.resetZoom\", when: \"previewFocus\" },\n  { key: \"mod+k\", command: \"commandPalette.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+p\", command: \"filePicker.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+f\", command: \"projectSearch.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+s\", command: \"composer.stash\", when: \"!terminalFocus\" },\n  { key: \"mod+n\", command: \"chat.new\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+o\", command: \"chat.new\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+n\", command: \"chat.newLocal\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+m\", command: \"modelPicker.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+o\", command: \"editor.openFavorite\" },\n  { key: \"mod+shift+[\", command: \"thread.previous\" },\n  { key: \"mod+shift+]\", command: \"thread.next\" },\n  ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({\n    key: `mod+${index + 1}`,\n    command,\n  })),\n  ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({\n    key: `mod+${index + 1}`,\n    command,\n    when: \"modelPickerOpen\",\n  })),\n];\n\nfunction normalizeKeyToken(token: string): string {\n  if (token === \"space\") return \" \";\n  if (token === \"esc\") return \"escape\";\n  return token;\n}\n\nexport function parseKeybindingShortcut(value: string): KeybindingShortcut | null {\n  const rawTokens = value\n    .toLowerCase()\n    .split(\"+\")\n    .map((token) => token.trim());\n  const tokens = [...rawTokens];\n  let trailingEmptyCount = 0;\n  while (tokens[tokens.length - 1] === \"\") {\n    trailingEmptyCount += 1;\n    tokens.pop();\n  }\n  if (trailingEmptyCount > 0) {\n    tokens.push(\"+\");\n  }\n  if (tokens.some((token) => token.length === 0)) {\n    return null;\n  }\n  if (tokens.length === 0) return null;\n\n  let key: string | null = null;\n  let metaKey = false;\n  let ctrlKey = false;\n  let shiftKey = false;\n  let altKey = false;\n  let modKey = false;\n\n  for (const token of tokens) {\n    switch (token) {\n      case \"cmd\":\n      case \"meta\":\n        metaKey = true;\n        break;\n      case \"ctrl\":\n      case \"control\":\n        ctrlKey = true;\n        break;\n      case \"shift\":\n        shiftKey = true;\n        break;\n      case \"alt\":\n      case \"option\":\n        altKey = true;\n        break;\n      case \"mod\":\n        modKey = true;\n        break;\n      default: {\n        if (key !== null) return null;\n        key = normalizeKeyToken(token);\n      }\n    }\n  }\n\n  if (key === null) return null;\n  return {\n    key,\n    metaKey,\n    ctrlKey,\n    shiftKey,\n    altKey,\n    modKey,\n  };\n}\n\nfunction tokenizeWhenExpression(expression: string): WhenToken[] | null {\n  const tokens: WhenToken[] = [];\n  let index = 0;\n\n  while (index < expression.length) {\n    const current = expression[index];\n    if (!current) break;\n\n    if (/\\s/.test(current)) {\n      index += 1;\n      continue;\n    }\n    if (expression.startsWith(\"&&\", index)) {\n      tokens.push({ type: \"and\" });\n      index += 2;\n      continue;\n    }\n    if (expression.startsWith(\"||\", index)) {\n      tokens.push({ type: \"or\" });\n      index += 2;\n      continue;\n    }\n    if (current === \"!\") {\n      tokens.push({ type: \"not\" });\n      index += 1;\n      continue;\n    }\n    if (current === \"(\") {\n      tokens.push({ type: \"lparen\" });\n      index += 1;\n      continue;\n    }\n    if (current === \")\") {\n      tokens.push({ type: \"rparen\" });\n      index += 1;\n      continue;\n    }\n\n    const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));\n    if (!identifier) {\n      return null;\n    }\n    tokens.push({ type: \"identifier\", value: identifier[0] });\n    index += identifier[0].length;\n  }\n\n  return tokens;\n}\n\nexport function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {\n  const tokens = tokenizeWhenExpression(expression);\n  if (!tokens || tokens.length === 0) return null;\n  let index = 0;\n\n  const parsePrimary = (depth: number): KeybindingWhenNode | null => {\n    if (depth > MAX_WHEN_EXPRESSION_DEPTH) {\n      return null;\n    }\n    const token = tokens[index];\n    if (!token) return null;\n\n    if (token.type === \"identifier\") {\n      index += 1;\n      return { type: \"identifier\", name: token.value };\n    }\n\n    if (token.type === \"lparen\") {\n      index += 1;\n      const expressionNode = parseOr(depth + 1);\n      const closeToken = tokens[index];\n      if (!expressionNode || !closeToken || closeToken.type !== \"rparen\") {\n        return null;\n      }\n      index += 1;\n      return expressionNode;\n    }\n\n    return null;\n  };\n\n  const parseUnary = (depth: number): KeybindingWhenNode | null => {\n    let notCount = 0;\n    while (tokens[index]?.type === \"not\") {\n      index += 1;\n      notCount += 1;\n      if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {\n        return null;\n      }\n    }\n\n    let node = parsePrimary(depth);\n    if (!node) return null;\n\n    while (notCount > 0) {\n      node = { type: \"not\", node };\n      notCount -= 1;\n    }\n\n    return node;\n  };\n\n  const parseAnd = (depth: number): KeybindingWhenNode | null => {\n    let left = parseUnary(depth);\n    if (!left) return null;\n\n    while (tokens[index]?.type === \"and\") {\n      index += 1;\n      const right = parseUnary(depth);\n      if (!right) return null;\n      left = { type: \"and\", left, right };\n    }\n\n    return left;\n  };\n\n  const parseOr = (depth: number): KeybindingWhenNode | null => {\n    let left = parseAnd(depth);\n    if (!left) return null;\n\n    while (tokens[index]?.type === \"or\") {\n      index += 1;\n      const right = parseAnd(depth);\n      if (!right) return null;\n      left = { type: \"or\", left, right };\n    }\n\n    return left;\n  };\n\n  const ast = parseOr(0);\n  if (!ast || index !== tokens.length) return null;\n  return ast;\n}\n\nexport function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {\n  const shortcut = parseKeybindingShortcut(rule.key);\n  if (!shortcut) return null;\n\n  if (rule.when !== undefined) {\n    const whenAst = parseKeybindingWhenExpression(rule.when);\n    if (!whenAst) return null;\n    return {\n      command: rule.command,\n      shortcut,\n      whenAst,\n    };\n  }\n\n  return {\n    command: rule.command,\n    shortcut,\n  };\n}\n\nexport function compileResolvedKeybindingsConfig(\n  config: ReadonlyArray<KeybindingRule>,\n): ResolvedKeybindingsConfig {\n  const compiled: ResolvedKeybindingRule[] = [];\n  for (const rule of config) {\n    const result = compileResolvedKeybindingRule(rule);\n    if (result) {\n      compiled.push(result);\n    }\n  }\n  return compiled.slice(-MAX_KEYBINDINGS_COUNT);\n}\n\nexport const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);\n","/**\n * Keybindings - Keybinding configuration service definitions.\n *\n * Owns parsing, validation, merge, and persistence of user keybinding\n * configuration consumed by the server runtime.\n *\n * @module Keybindings\n */\nimport {\n  KeybindingRule,\n  KeybindingsConfig,\n  KeybindingsConfigError,\n  KeybindingShortcut,\n  KeybindingWhenNode,\n  MAX_KEYBINDINGS_COUNT,\n  ResolvedKeybindingRule,\n  ResolvedKeybindingsConfig,\n  type ServerRemoveKeybindingInput,\n  type ServerUpsertKeybindingInput,\n  type ServerConfigIssue,\n} from \"@t3tools/contracts\";\nimport * as Array from \"effect/Array\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Layer from \"effect/Layer\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Ref from \"effect/Ref\";\nimport * as Context from \"effect/Context\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as ServerConfig from \"./config.ts\";\nimport { writeFileStringAtomically } from \"./atomicWrite.ts\";\nimport { fromJsonStringPretty, fromLenientJson } from \"@t3tools/shared/schemaJson\";\nimport {\n  DEFAULT_KEYBINDINGS,\n  DEFAULT_RESOLVED_KEYBINDINGS,\n  compileResolvedKeybindingRule,\n  compileResolvedKeybindingsConfig,\n  parseKeybindingShortcut,\n} from \"@t3tools/shared/keybindings\";\n\nexport {\n  DEFAULT_KEYBINDINGS,\n  compileResolvedKeybindingRule,\n  compileResolvedKeybindingsConfig,\n  parseKeybindingShortcut,\n};\n\nexport const ResolvedKeybindingFromConfig = KeybindingRule.pipe(\n  Schema.decodeTo(\n    Schema.toType(ResolvedKeybindingRule),\n    SchemaTransformation.transformOrFail({\n      decode: (rule) =>\n        Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(\n          Effect.filterOrFail(\n            Predicate.isNotNull,\n            () =>\n              new SchemaIssue.InvalidValue({\n                message: \"Invalid keybinding rule\",\n              }),\n          ),\n          Effect.map((resolved) => resolved),\n        ),\n\n      encode: (resolved) =>\n        Effect.gen(function* () {\n          const key = encodeShortcut(resolved.shortcut);\n          if (!key) {\n            return yield* Effect.fail(\n              new SchemaIssue.InvalidValue({\n                message: \"Resolved shortcut cannot be encoded to key string\",\n              }),\n            );\n          }\n\n          const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;\n          return {\n            key,\n            command: resolved.command,\n            when,\n          };\n        }),\n    }),\n  ),\n);\n\nexport const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(\n  Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),\n);\n\nfunction isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {\n  return (\n    left.command === right.command &&\n    left.key === right.key &&\n    (left.when ?? undefined) === (right.when ?? undefined)\n  );\n}\n\nfunction keybindingShortcutContext(rule: KeybindingRule): string | null {\n  const parsed = parseKeybindingShortcut(rule.key);\n  if (!parsed) return null;\n  const encoded = encodeShortcut(parsed);\n  if (!encoded) return null;\n  return `${encoded}\\u0000${rule.when ?? \"\"}`;\n}\n\nfunction hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {\n  const leftContext = keybindingShortcutContext(left);\n  const rightContext = keybindingShortcutContext(right);\n  if (!leftContext || !rightContext) return false;\n  return leftContext === rightContext;\n}\n\nfunction keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {\n  return input.when === undefined\n    ? { key: input.key, command: input.command }\n    : { key: input.key, command: input.command, when: input.when };\n}\n\nfunction replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {\n  if (!input.replace) return null;\n  return input.replace.when === undefined\n    ? { key: input.replace.key, command: input.replace.command }\n    : { key: input.replace.key, command: input.replace.command, when: input.replace.when };\n}\n\nfunction keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {\n  return input.when === undefined\n    ? { key: input.key, command: input.command }\n    : { key: input.key, command: input.command, when: input.when };\n}\n\nfunction encodeShortcut(shortcut: KeybindingShortcut): string | null {\n  const modifiers: string[] = [];\n  if (shortcut.modKey) modifiers.push(\"mod\");\n  if (shortcut.metaKey) modifiers.push(\"meta\");\n  if (shortcut.ctrlKey) modifiers.push(\"ctrl\");\n  if (shortcut.altKey) modifiers.push(\"alt\");\n  if (shortcut.shiftKey) modifiers.push(\"shift\");\n  if (!shortcut.key) return null;\n  if (shortcut.key !== \"+\" && shortcut.key.includes(\"+\")) return null;\n  const key = shortcut.key === \" \" ? \"space\" : shortcut.key;\n  return [...modifiers, key].join(\"+\");\n}\n\nfunction encodeWhenAst(node: KeybindingWhenNode): string {\n  switch (node.type) {\n    case \"identifier\":\n      return node.name;\n    case \"not\":\n      return `!(${encodeWhenAst(node.node)})`;\n    case \"and\":\n      return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;\n    case \"or\":\n      return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;\n  }\n}\n\nconst RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));\nconst KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);\nconst decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);\nconst decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);\nconst decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);\nconst encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);\n\nexport interface KeybindingsConfigState {\n  readonly keybindings: ResolvedKeybindingsConfig;\n  readonly issues: readonly ServerConfigIssue[];\n}\n\nexport interface KeybindingsChangeEvent {\n  readonly keybindings: ResolvedKeybindingsConfig;\n  readonly issues: readonly ServerConfigIssue[];\n}\n\nfunction trimIssueMessage(message: string): string {\n  const trimmed = message.trim();\n  return trimmed.length > 0 ? trimmed : \"Invalid keybindings configuration.\";\n}\n\nfunction malformedConfigIssue(detail: string): ServerConfigIssue {\n  return {\n    kind: \"keybindings.malformed-config\",\n    message: trimIssueMessage(detail),\n  };\n}\n\nfunction invalidEntryIssue(index: number, detail: string): ServerConfigIssue {\n  return {\n    kind: \"keybindings.invalid-entry\",\n    index,\n    message: trimIssueMessage(detail),\n  };\n}\n\nfunction mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {\n  if (custom.length === 0) {\n    return [...DEFAULT_RESOLVED_KEYBINDINGS];\n  }\n\n  const overriddenCommands = new Set(custom.map((binding) => binding.command));\n  const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(\n    (binding) => !overriddenCommands.has(binding.command),\n  );\n  const merged = [...retainedDefaults, ...custom];\n\n  if (merged.length <= MAX_KEYBINDINGS_COUNT) {\n    return merged;\n  }\n\n  // Keep the latest rules when the config exceeds max size; later rules have higher precedence.\n  return merged.slice(-MAX_KEYBINDINGS_COUNT);\n}\n\n/**\n * Keybindings - Service tag for keybinding configuration operations.\n */\nexport class Keybindings extends Context.Service<\n  Keybindings,\n  {\n    /**\n     * Start the keybindings runtime and attach file watching.\n     *\n     * Safe to call multiple times. The first successful call establishes the\n     * runtime; later calls await the same startup.\n     */\n    readonly start: Effect.Effect<void, KeybindingsConfigError>;\n\n    /**\n     * Await keybindings runtime readiness.\n     *\n     * Readiness means the config directory exists, the watcher is attached, the\n     * startup sync has completed, and the current snapshot has been loaded.\n     */\n    readonly ready: Effect.Effect<void, KeybindingsConfigError>;\n\n    /**\n     * Ensure the on-disk keybindings file exists and includes all default\n     * commands so newly-added defaults are backfilled on startup.\n     */\n    readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;\n\n    /**\n     * Load runtime keybindings state along with non-fatal configuration issues.\n     */\n    readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;\n\n    /**\n     * Read the latest keybindings snapshot from cache/disk.\n     */\n    readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;\n\n    /**\n     * Stream of keybindings config change events.\n     */\n    readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;\n\n    /**\n     * Upsert a keybinding rule and persist the resulting configuration.\n     *\n     * Writes config atomically and enforces the max rule count by truncating\n     * oldest entries when needed.\n     */\n    readonly upsertKeybindingRule: (\n      input: ServerUpsertKeybindingInput,\n    ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;\n\n    /**\n     * Remove a single persisted keybinding rule by exact key/command/when match.\n     */\n    readonly removeKeybindingRule: (\n      input: ServerRemoveKeybindingInput,\n    ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;\n  }\n>()(\"t3/keybindings\") {}\n\nconst make = Effect.gen(function* () {\n  const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const upsertSemaphore = yield* Semaphore.make(1);\n  const resolvedConfigCacheKey = \"resolved\" as const;\n  const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();\n  const startedRef = yield* Ref.make(false);\n  const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();\n  const watcherScope = yield* Scope.make(\"sequential\");\n  yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));\n  const emitChange = (configState: KeybindingsConfigState) =>\n    PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);\n\n  const readConfigExists = fs.exists(keybindingsConfigPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new KeybindingsConfigError({\n          configPath: keybindingsConfigPath,\n          detail: \"failed to access keybindings config\",\n          cause,\n        }),\n    ),\n  );\n\n  const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new KeybindingsConfigError({\n          configPath: keybindingsConfigPath,\n          detail: \"failed to read keybindings config\",\n          cause,\n        }),\n    ),\n  );\n\n  const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<\n    readonly KeybindingRule[],\n    KeybindingsConfigError\n  > {\n    if (!(yield* readConfigExists)) {\n      return [];\n    }\n\n    const rawConfig = yield* readRawConfig.pipe(\n      Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),\n      Effect.mapError(\n        (cause) =>\n          new KeybindingsConfigError({\n            configPath: keybindingsConfigPath,\n            detail: \"expected JSON array\",\n            cause,\n          }),\n      ),\n    );\n\n    return yield* Effect.forEach(rawConfig, (entry) =>\n      Effect.gen(function* () {\n        const decodedRule = decodeKeybindingRuleExit(entry);\n        if (decodedRule._tag === \"Failure\") {\n          yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n            path: keybindingsConfigPath,\n            entry,\n            error: Cause.pretty(decodedRule.cause),\n          });\n          return null;\n        }\n        const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);\n        if (resolved._tag === \"Failure\") {\n          yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n            path: keybindingsConfigPath,\n            entry,\n            error: Cause.pretty(resolved.cause),\n          });\n          return null;\n        }\n        return decodedRule.value;\n      }),\n    ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));\n  });\n\n  const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<\n    {\n      readonly keybindings: readonly KeybindingRule[];\n      readonly issues: readonly ServerConfigIssue[];\n    },\n    KeybindingsConfigError\n  > {\n    if (!(yield* readConfigExists)) {\n      return { keybindings: [], issues: [] };\n    }\n\n    const rawConfig = yield* readRawConfig;\n    const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);\n    if (decodedEntries._tag === \"Failure\") {\n      const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;\n      return {\n        keybindings: [],\n        issues: [malformedConfigIssue(detail)],\n      };\n    }\n\n    const keybindings: KeybindingRule[] = [];\n    const issues: ServerConfigIssue[] = [];\n    for (const [index, entry] of decodedEntries.value.entries()) {\n      const decodedRule = decodeKeybindingRuleExit(entry);\n      if (decodedRule._tag === \"Failure\") {\n        const detail = Cause.pretty(decodedRule.cause);\n        issues.push(invalidEntryIssue(index, detail));\n        yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n          path: keybindingsConfigPath,\n          index,\n          entry,\n          error: detail,\n        });\n        continue;\n      }\n\n      const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);\n      if (resolvedRule._tag === \"Failure\") {\n        const detail = Cause.pretty(resolvedRule.cause);\n        issues.push(invalidEntryIssue(index, detail));\n        yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n          path: keybindingsConfigPath,\n          index,\n          entry,\n          error: detail,\n        });\n        continue;\n      }\n      keybindings.push(decodedRule.value);\n    }\n\n    return { keybindings, issues };\n  });\n\n  const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {\n    return encodeKeybindingsConfigPrettyJson(rules).pipe(\n      Effect.map((encoded) => `${encoded}\\n`),\n      Effect.flatMap((encoded) =>\n        writeFileStringAtomically({\n          filePath: keybindingsConfigPath,\n          contents: encoded,\n        }).pipe(\n          Effect.provideService(FileSystem.FileSystem, fs),\n          Effect.provideService(Path.Path, path),\n        ),\n      ),\n      Effect.mapError(\n        (cause) =>\n          new KeybindingsConfigError({\n            configPath: keybindingsConfigPath,\n            detail: \"failed to write keybindings config\",\n            cause,\n          }),\n      ),\n    );\n  };\n\n  const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(\n    Effect.map(({ keybindings, issues }) => ({\n      keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),\n      issues,\n    })),\n  );\n\n  const resolvedConfigCache = yield* Cache.make<\n    typeof resolvedConfigCacheKey,\n    KeybindingsConfigState,\n    KeybindingsConfigError\n  >({\n    capacity: 1,\n    lookup: () => loadConfigStateFromDisk,\n  });\n\n  const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);\n\n  const revalidateAndEmit = upsertSemaphore.withPermits(1)(\n    Effect.gen(function* () {\n      yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n      const configState = yield* loadConfigStateFromCacheOrDisk;\n      yield* emitChange(configState);\n    }),\n  );\n\n  const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(\n    Effect.gen(function* () {\n      const configExists = yield* readConfigExists;\n      if (!configExists) {\n        yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n\n      const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();\n      if (runtimeConfig.issues.length > 0) {\n        yield* Effect.logWarning(\n          \"skipping startup keybindings default sync because config has issues\",\n          {\n            path: keybindingsConfigPath,\n            issues: runtimeConfig.issues,\n          },\n        );\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n      const customConfig = runtimeConfig.keybindings;\n      const existingCommands = new Set(customConfig.map((entry) => entry.command));\n      const missingDefaults: KeybindingRule[] = [];\n      const shortcutConflictWarnings: Array<{\n        defaultCommand: KeybindingRule[\"command\"];\n        conflictingCommand: KeybindingRule[\"command\"];\n        key: string;\n        when: string | null;\n      }> = [];\n      for (const defaultRule of DEFAULT_KEYBINDINGS) {\n        if (existingCommands.has(defaultRule.command)) {\n          continue;\n        }\n        const conflictingEntry = customConfig.find((entry) =>\n          hasSameShortcutContext(entry, defaultRule),\n        );\n        if (conflictingEntry) {\n          shortcutConflictWarnings.push({\n            defaultCommand: defaultRule.command,\n            conflictingCommand: conflictingEntry.command,\n            key: defaultRule.key,\n            when: defaultRule.when ?? null,\n          });\n          continue;\n        }\n        missingDefaults.push(defaultRule);\n      }\n      for (const conflict of shortcutConflictWarnings) {\n        yield* Effect.logWarning(\"skipping default keybinding due to shortcut conflict\", {\n          path: keybindingsConfigPath,\n          defaultCommand: conflict.defaultCommand,\n          conflictingCommand: conflict.conflictingCommand,\n          key: conflict.key,\n          when: conflict.when,\n          reason: \"shortcut context already used by existing rule\",\n        });\n      }\n      if (missingDefaults.length === 0) {\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n\n      const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>\n        customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))\n          ? Result.succeed(defaultRule.command)\n          : Result.failVoid,\n      );\n      if (matchingDefaults.length > 0) {\n        yield* Effect.logWarning(\"default keybinding rule already defined in user config\", {\n          path: keybindingsConfigPath,\n          commands: matchingDefaults,\n        });\n      }\n\n      // Startup backfill must never evict persisted user rules: append only\n      // the defaults that fit and skip the rest.\n      const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);\n      const defaultsToAppend = missingDefaults.slice(0, availableSlots);\n      const skippedDefaults = missingDefaults.slice(availableSlots);\n      if (skippedDefaults.length > 0) {\n        yield* Effect.logWarning(\"skipping default keybinding backfill at max entries\", {\n          path: keybindingsConfigPath,\n          maxEntries: MAX_KEYBINDINGS_COUNT,\n          commands: skippedDefaults.map((rule) => rule.command),\n        });\n      }\n      if (defaultsToAppend.length === 0) {\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n\n      yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);\n      yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n    }),\n  );\n\n  const startWatcher = Effect.gen(function* () {\n    const keybindingsConfigDir = path.dirname(keybindingsConfigPath);\n    const keybindingsConfigFile = path.basename(keybindingsConfigPath);\n    const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);\n\n    yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new KeybindingsConfigError({\n            configPath: keybindingsConfigPath,\n            detail: \"failed to prepare keybindings config directory\",\n            cause,\n          }),\n      ),\n    );\n\n    const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));\n\n    // Debounce watch events so the file is fully written before we read it.\n    // Editors emit multiple events per save (truncate, write, rename) and\n    // `fs.watch` can fire before the content has been flushed to disk.\n    const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(\n      Stream.filter((event) => {\n        return (\n          event.path === keybindingsConfigFile ||\n          event.path === keybindingsConfigPath ||\n          path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved\n        );\n      }),\n      Stream.debounce(Duration.millis(100)),\n    );\n\n    yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(\n      Effect.ignoreCause({ log: true }),\n      Effect.forkIn(watcherScope),\n      Effect.asVoid,\n    );\n  });\n\n  const start = Effect.gen(function* () {\n    const alreadyStarted = yield* Ref.get(startedRef);\n    if (alreadyStarted) {\n      return yield* Deferred.await(startedDeferred);\n    }\n\n    yield* Ref.set(startedRef, true);\n    const startup = Effect.gen(function* () {\n      yield* startWatcher;\n      yield* syncDefaultKeybindingsOnStartup;\n      yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n      yield* loadConfigStateFromCacheOrDisk;\n    });\n\n    const startupExit = yield* Effect.exit(startup);\n    if (startupExit._tag === \"Failure\") {\n      yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);\n      return yield* Effect.failCause(startupExit.cause);\n    }\n\n    yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);\n  });\n\n  return {\n    start,\n    ready: Deferred.await(startedDeferred),\n    syncDefaultKeybindingsOnStartup,\n    loadConfigState: loadConfigStateFromCacheOrDisk,\n    getSnapshot: loadConfigStateFromCacheOrDisk,\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n    upsertKeybindingRule: (input) =>\n      upsertSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const customConfig = yield* loadWritableCustomKeybindingsConfig();\n          const rule = keybindingRuleFromUpsertInput(input);\n          const replaceTarget = replaceTargetFromUpsertInput(input);\n          const nextConfig = [\n            ...customConfig.filter((entry) => {\n              if (replaceTarget) {\n                return (\n                  !isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)\n                );\n              }\n              return !isSameKeybindingRule(entry, rule);\n            }),\n            rule,\n          ];\n          const cappedConfig =\n            nextConfig.length > MAX_KEYBINDINGS_COUNT\n              ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)\n              : nextConfig;\n          if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {\n            yield* Effect.logWarning(\"truncating keybindings config to max entries\", {\n              path: keybindingsConfigPath,\n              maxEntries: MAX_KEYBINDINGS_COUNT,\n            });\n          }\n          yield* writeConfigAtomically(cappedConfig);\n          const nextResolved = mergeWithDefaultKeybindings(\n            compileResolvedKeybindingsConfig(cappedConfig),\n          );\n          yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {\n            keybindings: nextResolved,\n            issues: [],\n          });\n          yield* emitChange({\n            keybindings: nextResolved,\n            issues: [],\n          });\n          return nextResolved;\n        }),\n      ),\n    removeKeybindingRule: (input) =>\n      upsertSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const customConfig = yield* loadWritableCustomKeybindingsConfig();\n          const target = keybindingRuleFromRemoveInput(input);\n          const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));\n          yield* writeConfigAtomically(nextConfig);\n          const nextResolved = mergeWithDefaultKeybindings(\n            compileResolvedKeybindingsConfig(nextConfig),\n          );\n          yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {\n            keybindings: nextResolved,\n            issues: [],\n          });\n          yield* emitChange({\n            keybindings: nextResolved,\n            issues: [],\n          });\n          return nextResolved;\n        }),\n      ),\n  } satisfies Keybindings[\"Service\"];\n});\n\nexport const layer = Layer.effect(Keybindings, make);\n","/**\n * ExternalLauncher - external application launch service interface.\n *\n * Owns process launch helpers for browser URLs and workspace paths\n * in configured editor integrations.\n *\n * @module ExternalLauncher\n */\nimport {\n  EDITORS,\n  ExternalLauncherError,\n  ExternalLauncherBrowserSpawnError,\n  ExternalLauncherCommandNotFoundError,\n  ExternalLauncherEditorSpawnError,\n  ExternalLauncherUnknownEditorError,\n  ExternalLauncherUnsupportedEditorError,\n  type EditorId,\n  type LaunchEditorInput,\n} from \"@t3tools/contracts\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { isCommandAvailable, resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\n// ==============================\n// Definitions\n// ==============================\n\nexport {\n  ExternalLauncherError,\n  ExternalLauncherBrowserSpawnError,\n  ExternalLauncherCommandNotFoundError,\n  ExternalLauncherEditorSpawnError,\n  ExternalLauncherUnknownEditorError,\n  ExternalLauncherUnsupportedEditorError,\n  isExternalLauncherError,\n} from \"@t3tools/contracts\";\nexport type { LaunchEditorInput };\ninterface EditorLaunch {\n  readonly editor: EditorId;\n  readonly target: string;\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n}\n\ninterface ProcessLaunch {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly options: ChildProcess.CommandOptions;\n}\n\ninterface TargetPathAndPosition {\n  readonly path: string;\n  readonly line: string;\n  readonly column: Option.Option<string>;\n}\n\nconst TARGET_WITH_POSITION_PATTERN = /^(.*?):(\\d+)(?::(\\d+))?$/;\nconst POWERSHELL_ARGUMENTS_PREFIX = [\n  \"-NoProfile\",\n  \"-NonInteractive\",\n  \"-ExecutionPolicy\",\n  \"Bypass\",\n  \"-EncodedCommand\",\n] as const;\n\nconst DETACHED_IGNORE_STDIO_OPTIONS = {\n  detached: true,\n  stdin: \"ignore\",\n  stdout: \"ignore\",\n  stderr: \"ignore\",\n} as const satisfies ChildProcess.CommandOptions;\n\nconst compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>\n  Object.fromEntries(\n    Object.entries(input).flatMap(([key, value]) =>\n      Option.match(value, {\n        onNone: () => [],\n        onSome: (resolved) => [[key, resolved]],\n      }),\n    ),\n  );\n\nconst BrowserLaunchEnvConfig = Config.all({\n  SYSTEMROOT: Config.string(\"SYSTEMROOT\").pipe(Config.option),\n  windir: Config.string(\"windir\").pipe(Config.option),\n  WSL_DISTRO_NAME: Config.string(\"WSL_DISTRO_NAME\").pipe(Config.option),\n  WSL_INTEROP: Config.string(\"WSL_INTEROP\").pipe(Config.option),\n  SSH_CONNECTION: Config.string(\"SSH_CONNECTION\").pipe(Config.option),\n  SSH_TTY: Config.string(\"SSH_TTY\").pipe(Config.option),\n  container: Config.string(\"container\").pipe(Config.option),\n}).pipe(Config.map(compactEnv));\n\nconst CommandLookupEnvConfig = Config.all({\n  PATH: Config.string(\"PATH\").pipe(Config.option),\n  Path: Config.string(\"Path\").pipe(Config.option),\n  path: Config.string(\"path\").pipe(Config.option),\n  PATHEXT: Config.string(\"PATHEXT\").pipe(Config.option),\n}).pipe(Config.map(compactEnv));\n\nconst readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));\nconst readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));\n\nfunction parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {\n  const match = TARGET_WITH_POSITION_PATTERN.exec(target);\n  if (!match?.[1] || !match[2]) {\n    return Option.none();\n  }\n\n  return Option.some({\n    path: match[1],\n    line: match[2],\n    column: Option.fromUndefinedOr(match[3]),\n  });\n}\n\nfunction resolveCommandEditorArgs(\n  editor: (typeof EDITORS)[number],\n  target: string,\n): ReadonlyArray<string> {\n  const parsedTarget = parseTargetPathAndPosition(target);\n\n  switch (editor.launchStyle) {\n    case \"direct-path\":\n      return [target];\n    case \"goto\":\n      return Option.isSome(parsedTarget) ? [\"--goto\", target] : [target];\n    case \"line-column\":\n      return Option.match(parsedTarget, {\n        onNone: () => [target],\n        onSome: ({ path, line, column }) => [\n          \"--line\",\n          line,\n          ...Option.match(column, {\n            onNone: () => [],\n            onSome: (value) => [\"--column\", value],\n          }),\n          path,\n        ],\n      });\n  }\n}\n\nfunction resolveEditorArgs(\n  editor: (typeof EDITORS)[number],\n  target: string,\n): ReadonlyArray<string> {\n  const baseArgs = \"baseArgs\" in editor ? editor.baseArgs : [];\n  return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];\n}\n\nconst resolveAvailableCommand = Effect.fn(\"externalLauncher.resolveAvailableCommand\")(function* (\n  commands: ReadonlyArray<string>,\n  env: NodeJS.ProcessEnv,\n): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {\n  for (const command of commands) {\n    if (yield* isCommandAvailable(command, { env })) {\n      return Option.some(command);\n    }\n  }\n  return Option.none();\n});\n\nfunction encodeUtf16LeBase64(input: string): string {\n  const bytes = new Uint8Array(input.length * 2);\n  for (let index = 0; index < input.length; index += 1) {\n    const code = input.charCodeAt(index);\n    bytes[index * 2] = code & 0xff;\n    bytes[index * 2 + 1] = code >>> 8;\n  }\n  return Encoding.encodeBase64(bytes);\n}\n\nfunction escapePowerShellStringLiteral(input: string): string {\n  return `'${input.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {\n  return `${env.SYSTEMROOT || env.windir || String.raw`C:\\Windows`}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`;\n}\n\nfunction resolveWslPowerShellPath(): string {\n  return \"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe\";\n}\n\nfunction shouldUseWindowsBrowserFromWsl(\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv = {},\n): boolean {\n  return (\n    platform === \"linux\" &&\n    (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&\n    env.SSH_CONNECTION === undefined &&\n    env.SSH_TTY === undefined &&\n    env.container === undefined\n  );\n}\n\nfunction resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {\n  const encodedCommand = encodeUtf16LeBase64(\n    `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,\n  );\n  return {\n    command,\n    args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],\n    options: {\n      detached: true,\n      shell: false,\n      stdin: \"ignore\",\n      stdout: \"ignore\",\n      stderr: \"ignore\",\n    },\n  };\n}\n\nfunction fileManagerCommandForPlatform(platform: NodeJS.Platform): string {\n  switch (platform) {\n    case \"darwin\":\n      return \"open\";\n    case \"win32\":\n      return \"explorer\";\n    default:\n      return \"xdg-open\";\n  }\n}\n\nfunction buildBrowserLaunch(\n  target: string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv = {},\n): ProcessLaunch {\n  if (platform === \"darwin\") {\n    return {\n      command: \"open\",\n      args: [target],\n      options: DETACHED_IGNORE_STDIO_OPTIONS,\n    };\n  }\n\n  if (platform === \"win32\") {\n    return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));\n  }\n\n  if (shouldUseWindowsBrowserFromWsl(platform, env)) {\n    return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());\n  }\n\n  return {\n    command: \"xdg-open\",\n    args: [target],\n    options: DETACHED_IGNORE_STDIO_OPTIONS,\n  };\n}\n\nconst buildAvailableEditors = Effect.fn(\"externalLauncher.buildAvailableEditors\")(function* (\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {\n  const available: EditorId[] = [];\n\n  for (const editor of EDITORS) {\n    if (editor.commands === null) {\n      const command = fileManagerCommandForPlatform(platform);\n      if (yield* isCommandAvailable(command, { env })) {\n        available.push(editor.id);\n      }\n      continue;\n    }\n\n    const command = yield* resolveAvailableCommand(editor.commands, env);\n    if (Option.isSome(command)) {\n      available.push(editor.id);\n    }\n  }\n\n  return available;\n});\n\nconst resolveBrowserLaunch = Effect.fn(\"externalLauncher.resolveBrowserLaunch\")(function* (\n  target: string,\n) {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* readBrowserLaunchEnv;\n  return buildBrowserLaunch(target, platform, env);\n});\n\nconst resolveAvailableEditors = Effect.fn(\"externalLauncher.resolveAvailableEditors\")(function* () {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* readCommandLookupEnv;\n  return yield* buildAvailableEditors(platform, env);\n});\n\n/**\n * ExternalLauncher - Service tag for browser/editor launch operations.\n */\nexport class ExternalLauncher extends Context.Service<\n  ExternalLauncher,\n  {\n    readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;\n    /** Launch a URL target in the default browser. */\n    readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;\n    /**\n     * Launch a workspace path in a selected editor integration.\n     *\n     * Launches the editor as a detached process so server startup is not blocked.\n     */\n    readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;\n  }\n>()(\"t3/process/externalLauncher\") {}\n\n// ==============================\n// Implementations\n// ==============================\n\nconst resolveEditorLaunch = Effect.fn(\"resolveEditorLaunch\")(function* (\n  input: LaunchEditorInput,\n): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* readCommandLookupEnv;\n  yield* Effect.annotateCurrentSpan({\n    \"externalLauncher.editor\": input.editor,\n    \"externalLauncher.cwd\": input.cwd,\n    \"externalLauncher.platform\": platform,\n  });\n  const editorDef = EDITORS.find((editor) => editor.id === input.editor);\n  if (!editorDef) {\n    return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });\n  }\n\n  if (editorDef.commands) {\n    const command = Option.getOrElse(\n      yield* resolveAvailableCommand(editorDef.commands, env),\n      () => editorDef.commands[0],\n    );\n    return {\n      editor: editorDef.id,\n      target: input.cwd,\n      command,\n      args: resolveEditorArgs(editorDef, input.cwd),\n    };\n  }\n\n  if (editorDef.id !== \"file-manager\") {\n    return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });\n  }\n\n  return {\n    editor: editorDef.id,\n    target: input.cwd,\n    command: fileManagerCommandForPlatform(platform),\n    args: [input.cwd],\n  };\n});\n\nconst launchAndUnref = Effect.fn(\"externalLauncher.launchAndUnref\")(function* (\n  launch: ProcessLaunch,\n  onError: (cause: unknown) => ExternalLauncherError,\n): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const command = ChildProcess.make(launch.command, launch.args, launch.options);\n\n  yield* spawner.spawn(command).pipe(\n    Effect.flatMap((handle) => handle.unref),\n    Effect.asVoid,\n    Effect.scoped,\n    Effect.mapError(onError),\n  );\n});\n\nconst launchBrowser = Effect.fn(\"externalLauncher.launchBrowser\")(function* (\n  target: string,\n): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {\n  const launch = yield* resolveBrowserLaunch(target);\n  return yield* launchAndUnref(\n    launch,\n    (cause) =>\n      new ExternalLauncherBrowserSpawnError({\n        target,\n        command: launch.command,\n        args: launch.args,\n        cause,\n      }),\n  );\n});\n\nconst launchEditorProcess = Effect.fn(\"externalLauncher.launchEditorProcess\")(function* (\n  launch: EditorLaunch,\n): Effect.fn.Return<\n  void,\n  ExternalLauncherError,\n  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path\n> {\n  const env = yield* readCommandLookupEnv;\n  if (!(yield* isCommandAvailable(launch.command, { env }))) {\n    return yield* new ExternalLauncherCommandNotFoundError({\n      editor: launch.editor,\n      command: launch.command,\n    });\n  }\n\n  const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });\n  yield* launchAndUnref(\n    {\n      command: spawnCommand.command,\n      args: spawnCommand.args,\n      options: {\n        detached: true,\n        shell: spawnCommand.shell,\n        stdin: \"ignore\",\n        stdout: \"ignore\",\n        stderr: \"ignore\",\n      },\n    },\n    (cause) =>\n      new ExternalLauncherEditorSpawnError({\n        editor: launch.editor,\n        target: launch.target,\n        command: spawnCommand.command,\n        args: spawnCommand.args,\n        cause,\n      }),\n  );\n});\n\nexport const make = Effect.gen(function* () {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const provideCommandResolutionServices = <A, E, R>(\n    effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,\n  ) =>\n    effect.pipe(\n      Effect.provideService(FileSystem.FileSystem, fileSystem),\n      Effect.provideService(Path.Path, path),\n    );\n\n  return ExternalLauncher.of({\n    resolveAvailableEditors: () => provideCommandResolutionServices(resolveAvailableEditors()),\n    launchBrowser: (target) =>\n      launchBrowser(target).pipe(\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n      ),\n    launchEditor: (input) =>\n      provideCommandResolutionServices(\n        Effect.flatMap(resolveEditorLaunch(input), (launch) =>\n          launchEditorProcess(launch).pipe(\n            Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n          ),\n        ),\n      ),\n  });\n});\n\nexport const layer = Layer.effect(ExternalLauncher, make);\n","/**\n * OrchestrationReactor - Composite orchestration reactor service interface.\n *\n * Coordinates startup of orchestration runtime reactors that translate domain\n * events into downstream side effects.\n *\n * @module OrchestrationReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * OrchestrationReactorShape - Service API for orchestration reactor lifecycle.\n */\nexport interface OrchestrationReactorShape {\n  /**\n   * Start orchestration-side reactors for provider/runtime/checkpoint flows.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n}\n\n/**\n * OrchestrationReactor - Service tag for orchestration reactor coordination.\n */\nexport class OrchestrationReactor extends Context.Service<\n  OrchestrationReactor,\n  OrchestrationReactorShape\n>()(\"t3/orchestration/Services/OrchestrationReactor\") {}\n","import type { ServerLifecycleStreamEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\n\ntype LifecycleEventInput =\n  | Omit<Extract<ServerLifecycleStreamEvent, { type: \"welcome\" }>, \"sequence\">\n  | Omit<Extract<ServerLifecycleStreamEvent, { type: \"ready\" }>, \"sequence\">;\n\ninterface SnapshotState {\n  readonly sequence: number;\n  readonly events: ReadonlyArray<ServerLifecycleStreamEvent>;\n}\n\nexport class ServerLifecycleEvents extends Context.Service<\n  ServerLifecycleEvents,\n  {\n    readonly publish: (event: LifecycleEventInput) => Effect.Effect<ServerLifecycleStreamEvent>;\n    readonly snapshot: Effect.Effect<SnapshotState>;\n    readonly stream: Stream.Stream<ServerLifecycleStreamEvent>;\n  }\n>()(\"t3/serverLifecycleEvents\") {}\n\nconst make = Effect.gen(function* () {\n  const pubsub = yield* PubSub.unbounded<ServerLifecycleStreamEvent>();\n  const state = yield* Ref.make<SnapshotState>({\n    sequence: 0,\n    events: [],\n  });\n\n  return {\n    publish: (event) =>\n      Ref.modify(state, (current) => {\n        const nextSequence = current.sequence + 1;\n        const nextEvent = {\n          ...event,\n          sequence: nextSequence,\n        } satisfies ServerLifecycleStreamEvent;\n        const nextEvents =\n          nextEvent.type === \"welcome\"\n            ? [nextEvent, ...current.events.filter((entry) => entry.type !== \"welcome\")]\n            : [nextEvent, ...current.events.filter((entry) => entry.type !== \"ready\")];\n        return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const;\n      }).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))),\n    snapshot: Ref.get(state),\n    get stream() {\n      return Stream.fromPubSub(pubsub);\n    },\n  } satisfies ServerLifecycleEvents[\"Service\"];\n});\n\nexport const layer = Layer.effect(ServerLifecycleEvents, make);\n","/**\n * ServerSettings - Server-authoritative settings service.\n *\n * Owns persistence, validation, and change notification of settings that affect\n * server-side behavior (binary paths, streaming mode, env mode, custom models,\n * text generation model selection).\n *\n * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +\n * Semaphore + FileSystem.watch for concurrency and external edit detection.\n *\n * @module ServerSettings\n */\nimport {\n  DEFAULT_TEXT_GENERATION_MODEL,\n  DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,\n  DEFAULT_MODEL_BY_PROVIDER,\n  DEFAULT_SERVER_SETTINGS,\n  type ModelSelection,\n  type ProviderInstanceConfig,\n  type ProviderInstanceEnvironmentVariable,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  ServerSettings,\n  ServerSettingsError,\n  type ServerSettingsPatch,\n} from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Equal from \"effect/Equal\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { writeFileStringAtomically } from \"./atomicWrite.ts\";\nimport * as ServerConfig from \"./config.ts\";\nimport { type DeepPartial, deepMerge } from \"@t3tools/shared/Struct\";\nimport { fromJsonStringPretty, fromLenientJson } from \"@t3tools/shared/schemaJson\";\nimport {\n  applyServerSettingsPatch,\n  isModelSelectionProviderEnabled,\n} from \"@t3tools/shared/serverSettings\";\nimport * as ServerSecretStore from \"./auth/ServerSecretStore.ts\";\n\nexport { resolveSourceControlWriterModelSelection } from \"@t3tools/shared/serverSettings\";\n\nconst encodeServerSettings = Schema.encodeEffect(ServerSettings);\nconst encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));\nconst decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nconst normalizeServerSettings = (\n  settings: ServerSettings,\n): Effect.Effect<ServerSettings, ServerSettingsError> =>\n  encodeServerSettings(settings).pipe(\n    Effect.flatMap(decodeServerSettings),\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath: \"<memory>\",\n          operation: \"normalize\",\n          cause,\n        }),\n    ),\n  );\n\nfunction providerEnvironmentSecretName(input: {\n  readonly instanceId: string;\n  readonly name: string;\n}): string {\n  return `provider-env-${Buffer.from(input.instanceId, \"utf8\").toString(\"base64url\")}-${Buffer.from(input.name, \"utf8\").toString(\"base64url\")}`;\n}\n\nfunction redactProviderEnvironmentVariable(\n  variable: ProviderInstanceEnvironmentVariable,\n): ProviderInstanceEnvironmentVariable {\n  if (!variable.sensitive) {\n    const { valueRedacted: _omit, ...rest } = variable;\n    return rest;\n  }\n  return {\n    ...variable,\n    value: \"\",\n    ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),\n  };\n}\n\nexport function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {\n  const providerInstances = Object.fromEntries(\n    Object.entries(settings.providerInstances).map(([instanceId, instance]) => [\n      instanceId,\n      instance.environment\n        ? {\n            ...instance,\n            environment: instance.environment.map(redactProviderEnvironmentVariable),\n          }\n        : instance,\n    ]),\n  );\n  return { ...settings, providerInstances };\n}\n\nexport class ServerSettingsService extends Context.Service<\n  ServerSettingsService,\n  {\n    /** Start the settings runtime and attach file watching. */\n    readonly start: Effect.Effect<void, ServerSettingsError>;\n\n    /** Await settings runtime readiness. */\n    readonly ready: Effect.Effect<void, ServerSettingsError>;\n\n    /** Read the current settings. */\n    readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;\n\n    /** Patch settings and persist. Returns the new full settings object. */\n    readonly updateSettings: (\n      patch: ServerSettingsPatch,\n    ) => Effect.Effect<ServerSettings, ServerSettingsError>;\n\n    /** Stream of settings change events. */\n    readonly streamChanges: Stream.Stream<ServerSettings>;\n\n    /**\n     * Acquire a settings change subscription synchronously in the current\n     * fiber. Use this before reading a snapshot when changes between the\n     * snapshot and a lazily started stream must not be lost.\n     */\n    readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;\n  }\n>()(\"t3/serverSettings/ServerSettingsService\") {\n  /** @deprecated Import and use `layerTest` from this module. */\n  static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);\n}\n\nconst makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>\n  Effect.gen(function* () {\n    const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =\n      overrides;\n    const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);\n    const initialSettings = yield* normalizeServerSettings({\n      ...merged,\n      ...(automaticGitFetchInterval !== undefined\n        ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }\n        : {}),\n      ...(providerHealthRefreshInterval !== undefined\n        ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }\n        : {}),\n    });\n    const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);\n\n    return {\n      start: Effect.void,\n      ready: Effect.void,\n      getSettings: Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)),\n      updateSettings: (patch) =>\n        Ref.get(currentSettingsRef).pipe(\n          Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),\n          Effect.flatMap(normalizeServerSettings),\n          Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),\n          Effect.map(resolveTextGenerationProvider),\n        ),\n      streamChanges: Stream.empty,\n      subscribeChanges: Effect.succeed(Stream.empty),\n    } satisfies ServerSettingsService[\"Service\"];\n  });\n\nexport const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>\n  Layer.effect(ServerSettingsService, makeTest(overrides));\n\nconst ServerSettingsJson = fromLenientJson(ServerSettings);\nconst decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);\n\nfunction resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {\n  return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)\n    ? settings\n    : fallbackTextGenerationProvider(settings);\n}\n\nfunction fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {\n  const fallbackEntry = Object.entries(settings.providers).find(([, provider]) => provider.enabled);\n  const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;\n  if (!fallback) {\n    return settings;\n  }\n\n  return {\n    ...settings,\n    textGenerationModelSelection: {\n      instanceId: ProviderInstanceId.make(fallback),\n      model:\n        DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??\n        DEFAULT_MODEL_BY_PROVIDER[fallback] ??\n        DEFAULT_TEXT_GENERATION_MODEL,\n    } satisfies ModelSelection,\n  };\n}\n\n// Values under these keys are compared as a whole — never stripped field-by-field.\nconst ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([\n  \"backgroundActivity\",\n  \"automaticGitFetchInterval\",\n  \"providerHealthRefreshInterval\",\n  \"sourceControlWriterModelSelection\",\n  \"textGenerationModelSelection\",\n]);\n\nfunction stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {\n  if (Array.isArray(current) || Array.isArray(defaults)) {\n    return Equal.equals(current, defaults) ? undefined : current;\n  }\n\n  if (\n    current !== null &&\n    defaults !== null &&\n    typeof current === \"object\" &&\n    typeof defaults === \"object\"\n  ) {\n    const currentRecord = current as Record<string, unknown>;\n    const defaultsRecord = defaults as Record<string, unknown>;\n    const next: Record<string, unknown> = {};\n\n    for (const key of Object.keys(currentRecord)) {\n      if (ATOMIC_SETTINGS_KEYS.has(key)) {\n        if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {\n          next[key] = currentRecord[key];\n        }\n      } else {\n        const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);\n        if (stripped !== undefined) {\n          next[key] = stripped;\n        }\n      }\n    }\n\n    return Object.keys(next).length > 0 ? next : undefined;\n  }\n\n  return Object.is(current, defaults) ? undefined : current;\n}\n\nconst make = Effect.gen(function* () {\n  const { settingsPath } = yield* ServerConfig.ServerConfig;\n  const fs = yield* FileSystem.FileSystem;\n  const pathService = yield* Path.Path;\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const writeSemaphore = yield* Semaphore.make(1);\n  const cacheKey = \"settings\" as const;\n  const changesPubSub = yield* PubSub.unbounded<ServerSettings>();\n  const startedRef = yield* Ref.make(false);\n  const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();\n  const watcherScope = yield* Scope.make(\"sequential\");\n  yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));\n\n  const emitChange = (settings: ServerSettings) =>\n    PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);\n\n  const readConfigExists = fs.exists(settingsPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath,\n          operation: \"check-exists\",\n          cause,\n        }),\n    ),\n  );\n\n  const readRawConfig = fs.readFileString(settingsPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath,\n          operation: \"read-file\",\n          cause,\n        }),\n    ),\n  );\n\n  const loadSettingsFromDisk = Effect.gen(function* () {\n    if (!(yield* readConfigExists)) {\n      return DEFAULT_SERVER_SETTINGS;\n    }\n\n    const raw = yield* readRawConfig;\n    const decoded = decodeServerSettingsJsonExit(raw);\n    if (decoded._tag === \"Failure\") {\n      yield* Effect.logWarning(\"failed to parse settings.json, using defaults\", {\n        path: settingsPath,\n        issues: Cause.pretty(decoded.cause),\n        cause: decoded.cause,\n      });\n      return DEFAULT_SERVER_SETTINGS;\n    }\n    return decoded.value;\n  });\n\n  const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({\n    capacity: 1,\n    lookup: () => loadSettingsFromDisk,\n  });\n\n  const getSettingsFromCache = Cache.get(settingsCache, cacheKey);\n\n  const materializeProviderEnvironmentSecrets = (\n    settings: ServerSettings,\n  ): Effect.Effect<ServerSettings, ServerSettingsError> =>\n    Effect.gen(function* () {\n      const providerInstances: Record<string, ProviderInstanceConfig> = {\n        ...settings.providerInstances,\n      };\n      for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {\n        if (!instance.environment) continue;\n        const environment: ProviderInstanceEnvironmentVariable[] = [];\n        for (const variable of instance.environment) {\n          if (!variable.sensitive || !variable.valueRedacted) {\n            environment.push(variable);\n            continue;\n          }\n          const secret = yield* secretStore\n            .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))\n            .pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ServerSettingsError({\n                    settingsPath,\n                    operation: \"read-secret\",\n                    providerInstanceId: instanceId,\n                    environmentVariable: variable.name,\n                    cause,\n                  }),\n              ),\n            );\n          environment.push({\n            ...variable,\n            value: Option.isSome(secret) ? textDecoder.decode(secret.value) : \"\",\n          });\n        }\n        providerInstances[instanceId] = {\n          ...instance,\n          environment,\n        } satisfies ProviderInstanceConfig;\n      }\n      return {\n        ...settings,\n        providerInstances: providerInstances as ServerSettings[\"providerInstances\"],\n      };\n    });\n\n  const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>\n    changes.pipe(\n      Stream.mapEffect((settings) =>\n        materializeProviderEnvironmentSecrets(settings).pipe(\n          Effect.catch((error: ServerSettingsError) =>\n            Effect.logWarning(\"failed to materialize provider environment secrets\", {\n              operation: error.operation,\n              providerInstanceId: error.providerInstanceId,\n              environmentVariable: error.environmentVariable,\n              cause: error.cause,\n            }).pipe(Effect.as(settings)),\n          ),\n        ),\n      ),\n      Stream.map(resolveTextGenerationProvider),\n    );\n\n  const persistProviderEnvironmentSecrets = (\n    current: ServerSettings,\n    next: ServerSettings,\n  ): Effect.Effect<ServerSettings, ServerSettingsError> =>\n    Effect.gen(function* () {\n      const providerInstances: Record<string, ProviderInstanceConfig> = {\n        ...next.providerInstances,\n      };\n\n      const nextSecretKeys = new Set<string>();\n      for (const [instanceId, instance] of Object.entries(next.providerInstances)) {\n        if (!instance.environment) continue;\n        const environment: ProviderInstanceEnvironmentVariable[] = [];\n        for (const variable of instance.environment) {\n          const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });\n          if (!variable.sensitive) {\n            yield* secretStore.remove(secretName).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ServerSettingsError({\n                    settingsPath,\n                    operation: \"remove-secret\",\n                    providerInstanceId: instanceId,\n                    environmentVariable: variable.name,\n                    cause,\n                  }),\n              ),\n            );\n            environment.push(redactProviderEnvironmentVariable(variable));\n            continue;\n          }\n\n          nextSecretKeys.add(secretName);\n          if (!variable.valueRedacted) {\n            if (variable.value.length > 0) {\n              yield* secretStore.set(secretName, textEncoder.encode(variable.value)).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new ServerSettingsError({\n                      settingsPath,\n                      operation: \"write-secret\",\n                      providerInstanceId: instanceId,\n                      environmentVariable: variable.name,\n                      cause,\n                    }),\n                ),\n              );\n              environment.push({ ...variable, value: \"\", valueRedacted: true });\n            } else {\n              yield* secretStore.remove(secretName).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new ServerSettingsError({\n                      settingsPath,\n                      operation: \"remove-secret\",\n                      providerInstanceId: instanceId,\n                      environmentVariable: variable.name,\n                      cause,\n                    }),\n                ),\n              );\n              const { valueRedacted: _omit, ...rest } = variable;\n              environment.push(rest);\n            }\n            continue;\n          }\n\n          environment.push(redactProviderEnvironmentVariable(variable));\n        }\n        providerInstances[instanceId] = {\n          ...instance,\n          environment,\n        } satisfies ProviderInstanceConfig;\n      }\n\n      for (const [instanceId, instance] of Object.entries(current.providerInstances)) {\n        for (const variable of instance.environment ?? []) {\n          if (!variable.sensitive) continue;\n          const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });\n          if (nextSecretKeys.has(secretName)) continue;\n          yield* secretStore.remove(secretName).pipe(\n            Effect.mapError(\n              (cause) =>\n                new ServerSettingsError({\n                  settingsPath,\n                  operation: \"remove-stale-secret\",\n                  providerInstanceId: instanceId,\n                  environmentVariable: variable.name,\n                  cause,\n                }),\n            ),\n          );\n        }\n      }\n\n      return {\n        ...next,\n        providerInstances: providerInstances as ServerSettings[\"providerInstances\"],\n      };\n    });\n\n  const writeSettingsAtomically = Effect.fnUntraced(\n    function* (settings: ServerSettings) {\n      const sparseSettingsJson = yield* encodeServerSettingsJson(\n        stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},\n      );\n\n      return yield* writeFileStringAtomically({\n        filePath: settingsPath,\n        contents: `${sparseSettingsJson}\\n`,\n      }).pipe(\n        Effect.provideService(FileSystem.FileSystem, fs),\n        Effect.provideService(Path.Path, pathService),\n      );\n    },\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath,\n          operation: \"write-file\",\n          cause,\n        }),\n    ),\n  );\n\n  const revalidateAndEmit = writeSemaphore.withPermits(1)(\n    Effect.gen(function* () {\n      yield* Cache.invalidate(settingsCache, cacheKey);\n      const settings = yield* getSettingsFromCache;\n      yield* emitChange(settings);\n    }),\n  );\n\n  const startWatcher = Effect.gen(function* () {\n    const settingsDir = pathService.dirname(settingsPath);\n    const settingsFile = pathService.basename(settingsPath);\n    const settingsPathResolved = pathService.resolve(settingsPath);\n\n    yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerSettingsError({\n            settingsPath,\n            operation: \"prepare-directory\",\n            cause,\n          }),\n      ),\n    );\n\n    const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));\n\n    // Debounce watch events so the file is fully written before we read it.\n    // Editors emit multiple events per save (truncate, write, rename) and\n    // `fs.watch` can fire before the content has been flushed to disk.\n    const debouncedSettingsEvents = fs.watch(settingsDir).pipe(\n      Stream.filter((event) => {\n        return (\n          event.path === settingsFile ||\n          event.path === settingsPath ||\n          pathService.resolve(settingsDir, event.path) === settingsPathResolved\n        );\n      }),\n      Stream.debounce(Duration.millis(100)),\n    );\n\n    yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(\n      Effect.ignoreCause({ log: true }),\n      Effect.forkIn(watcherScope),\n      Effect.asVoid,\n    );\n  });\n\n  const start = Effect.gen(function* () {\n    const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);\n    if (!shouldStart) {\n      return yield* Deferred.await(startedDeferred);\n    }\n\n    const startup = Effect.gen(function* () {\n      yield* startWatcher;\n      yield* Cache.invalidate(settingsCache, cacheKey);\n      yield* getSettingsFromCache;\n    });\n\n    const startupExit = yield* Effect.exit(startup);\n    if (startupExit._tag === \"Failure\") {\n      yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);\n      return yield* Effect.failCause(startupExit.cause);\n    }\n\n    yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);\n  });\n\n  return {\n    start,\n    ready: Deferred.await(startedDeferred),\n    getSettings: getSettingsFromCache.pipe(\n      Effect.flatMap(materializeProviderEnvironmentSecrets),\n      Effect.map(resolveTextGenerationProvider),\n    ),\n    updateSettings: (patch) =>\n      writeSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const current = yield* getSettingsFromCache;\n          const nextPersisted = yield* persistProviderEnvironmentSecrets(\n            current,\n            applyServerSettingsPatch(current, patch),\n          );\n          const next = yield* normalizeServerSettings(nextPersisted);\n          yield* writeSettingsAtomically(next);\n          yield* Cache.set(settingsCache, cacheKey, next);\n          yield* emitChange(next);\n          const materialized = yield* materializeProviderEnvironmentSecrets(next);\n          return resolveTextGenerationProvider(materialized);\n        }),\n      ),\n    get streamChanges() {\n      return materializeChanges(Stream.fromPubSub(changesPubSub));\n    },\n    get subscribeChanges() {\n      return PubSub.subscribe(changesPubSub).pipe(\n        Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),\n      );\n    },\n  } satisfies ServerSettingsService[\"Service\"];\n});\n\nexport const layer = Layer.effect(ServerSettingsService, make);\n","import * as NodeOS from \"node:os\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ServerConfig from \"../config.ts\";\n\nconst CodexAuthJsonSchema = Schema.Struct({\n  tokens: Schema.Struct({\n    account_id: Schema.String,\n  }),\n});\n\nconst ClaudeJsonSchema = Schema.Struct({\n  userID: Schema.String,\n});\n\nexport const TelemetryIdentitySource = Schema.Literals([\"codex\", \"claude\", \"anonymous\"]);\nexport type TelemetryIdentitySource = typeof TelemetryIdentitySource.Type;\n\nexport class TelemetryIdentityReadError extends Schema.TaggedErrorClass<TelemetryIdentityReadError>()(\n  \"TelemetryIdentityReadError\",\n  {\n    source: TelemetryIdentitySource,\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.source} telemetry identity at '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryIdentityDecodeError extends Schema.TaggedErrorClass<TelemetryIdentityDecodeError>()(\n  \"TelemetryIdentityDecodeError\",\n  {\n    source: Schema.Literals([\"codex\", \"claude\"]),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to decode ${this.source} telemetry identity at '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryAnonymousIdGenerationError extends Schema.TaggedErrorClass<TelemetryAnonymousIdGenerationError>()(\n  \"TelemetryAnonymousIdGenerationError\",\n  {\n    source: Schema.Literal(\"anonymous\"),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to generate anonymous telemetry identity for '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryAnonymousIdPersistenceError extends Schema.TaggedErrorClass<TelemetryAnonymousIdPersistenceError>()(\n  \"TelemetryAnonymousIdPersistenceError\",\n  {\n    source: Schema.Literal(\"anonymous\"),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to persist anonymous telemetry identity at '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryIdentityHashError extends Schema.TaggedErrorClass<TelemetryIdentityHashError>()(\n  \"TelemetryIdentityHashError\",\n  {\n    source: TelemetryIdentitySource,\n    algorithm: Schema.Literal(\"SHA-256\"),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to hash ${this.source} telemetry identity with ${this.algorithm}.`;\n  }\n}\n\ntype TelemetryIdentityError =\n  | TelemetryIdentityReadError\n  | TelemetryIdentityDecodeError\n  | TelemetryAnonymousIdGenerationError\n  | TelemetryAnonymousIdPersistenceError\n  | TelemetryIdentityHashError;\n\nconst decodeCodexAuthJson = Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema));\nconst decodeClaudeJson = Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema));\n\nfunction isNotFoundError(error: PlatformError.PlatformError): boolean {\n  return error.reason._tag === \"NotFound\";\n}\n\nconst getTelemetryIdentityCauseAnnotations = (cause: unknown) => {\n  if (cause instanceof PlatformError.PlatformError) {\n    return {\n      causeKind: \"platform\",\n      platformReason: cause.reason._tag,\n    };\n  }\n  if (cause instanceof Schema.SchemaError) {\n    return { causeKind: \"schema\" };\n  }\n  return { causeKind: \"other\" };\n};\n\nconst logTelemetryIdentityError = (error: TelemetryIdentityError) =>\n  Effect.logWarning(error.message).pipe(\n    Effect.annotateLogs({\n      errorTag: error._tag,\n      source: error.source,\n      ...(\"filePath\" in error ? { filePath: error.filePath } : {}),\n      ...getTelemetryIdentityCauseAnnotations(error.cause),\n      ...(error.stack === undefined ? {} : { errorStack: error.stack }),\n    }),\n  );\n\nconst readIdentityFile = (\n  fileSystem: FileSystem.FileSystem,\n  source: TelemetryIdentitySource,\n  filePath: string,\n) =>\n  fileSystem.readFileString(filePath).pipe(\n    Effect.map(Option.some),\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        isNotFoundError(cause)\n          ? Effect.succeed(Option.none<string>())\n          : Effect.fail(\n              new TelemetryIdentityReadError({\n                source,\n                filePath,\n                cause,\n              }),\n            ),\n    }),\n  );\n\nconst hash = (source: TelemetryIdentitySource, value: string) =>\n  Crypto.Crypto.pipe(\n    Effect.flatMap((crypto) => crypto.digest(\"SHA-256\", new TextEncoder().encode(value))),\n    Effect.map(Encoding.encodeHex),\n    Effect.mapError(\n      (cause) =>\n        new TelemetryIdentityHashError({\n          source,\n          algorithm: \"SHA-256\",\n          cause,\n        }),\n    ),\n  );\n\nconst getCodexAccountId = Effect.fn(\"TelemetryIdentity.getCodexAccountId\")(function* (\n  homeDirectory: string,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const authJsonPath = path.join(homeDirectory, \".codex\", \"auth.json\");\n  const encoded = yield* readIdentityFile(fileSystem, \"codex\", authJsonPath);\n  if (Option.isNone(encoded)) {\n    return Option.none<string>();\n  }\n  const authJson = yield* decodeCodexAuthJson(encoded.value).pipe(\n    Effect.mapError(\n      (cause) =>\n        new TelemetryIdentityDecodeError({\n          source: \"codex\",\n          filePath: authJsonPath,\n          cause,\n        }),\n    ),\n  );\n\n  return Option.some(authJson.tokens.account_id);\n});\n\nconst getClaudeUserId = Effect.fn(\"TelemetryIdentity.getClaudeUserId\")(function* (\n  homeDirectory: string,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const claudeJsonPath = path.join(homeDirectory, \".claude.json\");\n  const encoded = yield* readIdentityFile(fileSystem, \"claude\", claudeJsonPath);\n  if (Option.isNone(encoded)) {\n    return Option.none<string>();\n  }\n  const claudeJson = yield* decodeClaudeJson(encoded.value).pipe(\n    Effect.mapError(\n      (cause) =>\n        new TelemetryIdentityDecodeError({\n          source: \"claude\",\n          filePath: claudeJsonPath,\n          cause,\n        }),\n    ),\n  );\n\n  return Option.some(claudeJson.userID);\n});\n\nconst upsertAnonymousId = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const { anonymousIdPath } = yield* ServerConfig.ServerConfig;\n\n  const existing = yield* readIdentityFile(fileSystem, \"anonymous\", anonymousIdPath);\n  if (Option.isSome(existing)) {\n    return existing.value;\n  }\n\n  const anonymousId = yield* Crypto.Crypto.pipe(\n    Effect.flatMap((crypto) => crypto.randomUUIDv4),\n    Effect.mapError(\n      (cause) =>\n        new TelemetryAnonymousIdGenerationError({\n          source: \"anonymous\",\n          filePath: anonymousIdPath,\n          cause,\n        }),\n    ),\n  );\n  yield* fileSystem.writeFileString(anonymousIdPath, anonymousId).pipe(\n    Effect.mapError(\n      (cause) =>\n        new TelemetryAnonymousIdPersistenceError({\n          source: \"anonymous\",\n          filePath: anonymousIdPath,\n          cause,\n        }),\n    ),\n  );\n\n  return anonymousId;\n});\n\n/**\n * getTelemetryIdentifier - Users are \"identified\" by finding the first match of the following, then hashing the value.\n * 1. ~/.codex/auth.json tokens.account_id\n * 2. ~/.claude.json userID\n * 3. ~/.t3/telemetry/anonymous-id\n */\nexport const getTelemetryIdentifierForHome = Effect.fn(\"getTelemetryIdentifierForHome\")(\n  function* (homeDirectory: string) {\n    const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe(\n      Effect.catchTags({\n        TelemetryIdentityReadError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryIdentityDecodeError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n      }),\n    );\n    if (Option.isSome(codexAccountId)) {\n      return yield* hash(\"codex\", codexAccountId.value);\n    }\n\n    const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe(\n      Effect.catchTags({\n        TelemetryIdentityReadError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryIdentityDecodeError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n      }),\n    );\n    if (Option.isSome(claudeUserId)) {\n      return yield* hash(\"claude\", claudeUserId.value);\n    }\n\n    const anonymousId = yield* upsertAnonymousId.pipe(\n      Effect.map(Option.some),\n      Effect.catchTags({\n        TelemetryIdentityReadError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryAnonymousIdGenerationError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryAnonymousIdPersistenceError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n      }),\n    );\n    if (Option.isSome(anonymousId)) {\n      return yield* hash(\"anonymous\", anonymousId.value);\n    }\n\n    return null;\n  },\n  Effect.tapError(logTelemetryIdentityError),\n  Effect.orElseSucceed(() => null),\n);\n\nexport const getTelemetryIdentifier = Effect.suspend(() =>\n  getTelemetryIdentifierForHome(NodeOS.homedir()),\n);\n","/**\n * Anonymous PostHog telemetry service.\n *\n * Persists an installation-scoped anonymous identifier, buffers events in\n * memory, and flushes batches over Effect's HTTP client.\n *\n * @module AnalyticsService\n */\nimport { HostProcessArchitecture, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/unstable/http/HttpClientRequest\";\nimport * as HttpClientResponse from \"effect/unstable/http/HttpClientResponse\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport * as ServerConfig from \"../config.ts\";\nimport { getTelemetryIdentifier } from \"./Identify.ts\";\n\ninterface BufferedAnalyticsEvent {\n  readonly event: string;\n  readonly properties?: Readonly<Record<string, unknown>>;\n  readonly capturedAt: string;\n}\n\nconst TelemetryEnvConfig = Config.all({\n  posthogKey: Config.string(\"T3CODE_POSTHOG_KEY\").pipe(\n    Config.withDefault(\"phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m\"),\n  ),\n  posthogHost: Config.string(\"T3CODE_POSTHOG_HOST\").pipe(\n    Config.withDefault(\"https://us.i.posthog.com\"),\n  ),\n  enabled: Config.boolean(\"T3CODE_TELEMETRY_ENABLED\").pipe(Config.withDefault(true)),\n  flushBatchSize: Config.number(\"T3CODE_TELEMETRY_FLUSH_BATCH_SIZE\").pipe(Config.withDefault(20)),\n  maxBufferedEvents: Config.number(\"T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS\").pipe(\n    Config.withDefault(1_000),\n  ),\n  wslDistroName: Config.string(\"WSL_DISTRO_NAME\").pipe(Config.option),\n});\n\nexport class AnalyticsService extends Context.Service<\n  AnalyticsService,\n  {\n    /** Record an anonymous event for best-effort buffered delivery. */\n    readonly record: (\n      event: string,\n      properties?: Readonly<Record<string, unknown>>,\n    ) => Effect.Effect<void>;\n\n    /** Flush all currently queued telemetry events. */\n    readonly flush: Effect.Effect<void>;\n  }\n>()(\"t3/telemetry/AnalyticsService\") {\n  /** No-op layer for callers that intentionally disable telemetry. */\n  static readonly layerTest = Layer.succeed(\n    AnalyticsService,\n    AnalyticsService.of({\n      record: () => Effect.void,\n      flush: Effect.void,\n    }),\n  );\n}\n\nexport const make = Effect.gen(function* () {\n  const telemetryConfig = yield* TelemetryEnvConfig;\n  const httpClient = yield* HttpClient.HttpClient;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const identifier = yield* getTelemetryIdentifier;\n  const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);\n  const clientType = serverConfig.mode === \"desktop\" ? \"desktop-app\" : \"cli-web-client\";\n  const hostPlatform = yield* HostProcessPlatform;\n  const hostArchitecture = yield* HostProcessArchitecture;\n\n  const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>\n    Effect.flatMap(DateTime.now, (now) =>\n      Ref.modify(bufferRef, (current) => {\n        const appended = [\n          ...current,\n          {\n            event,\n            ...(properties ? { properties } : {}),\n            capturedAt: DateTime.formatIso(now),\n          } satisfies BufferedAnalyticsEvent,\n        ];\n\n        const next =\n          appended.length > telemetryConfig.maxBufferedEvents\n            ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)\n            : appended;\n\n        return [\n          {\n            size: next.length,\n            dropped: next.length !== appended.length,\n          } as const,\n          next,\n        ] as const;\n      }),\n    );\n\n  const sendBatch = Effect.fn(\"AnalyticsService.sendBatch\")(function* (\n    events: ReadonlyArray<BufferedAnalyticsEvent>,\n  ) {\n    if (!telemetryConfig.enabled || !identifier) return;\n\n    const payload = {\n      api_key: telemetryConfig.posthogKey,\n      batch: events.map((event) => ({\n        event: event.event,\n        distinct_id: identifier,\n        properties: {\n          ...event.properties,\n          $process_person_profile: false,\n          platform: hostPlatform,\n          wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),\n          arch: hostArchitecture,\n          t3CodeVersion: packageJson.version,\n          clientType,\n        },\n        timestamp: event.capturedAt,\n      })),\n    };\n\n    yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(\n      HttpClientRequest.bodyJson(payload),\n      Effect.flatMap(httpClient.execute),\n      Effect.flatMap(HttpClientResponse.filterStatusOk),\n    );\n  });\n\n  const flush: AnalyticsService[\"Service\"][\"flush\"] = Effect.gen(function* () {\n    while (true) {\n      const batch = yield* Ref.modify(bufferRef, (current) => {\n        if (current.length === 0) {\n          return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;\n        }\n        const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);\n        const remaining = current.slice(nextBatch.length);\n        return [nextBatch, remaining] as const;\n      });\n\n      if (batch.length === 0) {\n        return;\n      }\n\n      yield* sendBatch(batch).pipe(\n        Effect.catch((error) =>\n          Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(\n            Effect.flatMap(() => Effect.fail(error)),\n          ),\n        ),\n      );\n    }\n  }).pipe(Effect.catch((cause) => Effect.logError(\"Failed to flush telemetry\", { cause })));\n\n  const record: AnalyticsService[\"Service\"][\"record\"] = Effect.fn(\"AnalyticsService.record\")(\n    function* (event, properties) {\n      if (!telemetryConfig.enabled || !identifier) return;\n\n      const enqueueResult = yield* enqueueBufferedEvent(event, properties);\n      if (enqueueResult.dropped) {\n        yield* Effect.logDebug(\"analytics buffer full; dropping oldest event\", {\n          size: enqueueResult.size,\n          event,\n        });\n      }\n    },\n  );\n\n  yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {\n    disableYield: true,\n  }).pipe(Effect.forkScoped);\n\n  yield* Effect.addFinalizer(() => flush);\n\n  return AnalyticsService.of({ record, flush });\n});\n\nexport const layer = Layer.effect(AnalyticsService, make);\n\nexport const layerTest = AnalyticsService.layerTest;\n","import { HostProcessHostname, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\ninterface ResolveServerEnvironmentLabelInput {\n  readonly cwdBaseName: string;\n}\n\nconst ServerEnvironmentLabelCommandProbe = Schema.Literals([\n  \"macos-computer-name\",\n  \"linux-pretty-hostname\",\n]);\ntype ServerEnvironmentLabelCommandProbe = typeof ServerEnvironmentLabelCommandProbe.Type;\n\nexport class ServerEnvironmentLabelFileError extends Schema.TaggedErrorClass<ServerEnvironmentLabelFileError>()(\n  \"ServerEnvironmentLabelFileError\",\n  {\n    operation: Schema.Literals([\"inspect\", \"read\"]),\n    path: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} environment-label file at ${this.path}.`;\n  }\n}\n\nexport class ServerEnvironmentLabelCommandError extends Schema.TaggedErrorClass<ServerEnvironmentLabelCommandError>()(\n  \"ServerEnvironmentLabelCommandError\",\n  {\n    probe: ServerEnvironmentLabelCommandProbe,\n    executable: Schema.String,\n    argumentCount: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to run environment-label probe '${this.probe}' with ${this.executable}.`;\n  }\n}\n\nfunction normalizeLabel(value: string | null | undefined): string | null {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : null;\n}\n\nfunction parseMachineInfoValue(raw: string, key: string): string | null {\n  for (const line of raw.split(/\\r?\\n/g)) {\n    const trimmed = line.trim();\n    if (trimmed.length === 0 || trimmed.startsWith(\"#\") || !trimmed.startsWith(`${key}=`)) {\n      continue;\n    }\n    const value = trimmed.slice(key.length + 1).trim();\n    if (\n      (value.startsWith('\"') && value.endsWith('\"')) ||\n      (value.startsWith(\"'\") && value.endsWith(\"'\"))\n    ) {\n      return normalizeLabel(value.slice(1, -1));\n    }\n    return normalizeLabel(value);\n  }\n  return null;\n}\n\nconst readLinuxMachineInfo = Effect.fn(\"readLinuxMachineInfo\")(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const machineInfoPath = \"/etc/machine-info\";\n  return yield* fileSystem.exists(machineInfoPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerEnvironmentLabelFileError({\n          operation: \"inspect\",\n          path: machineInfoPath,\n          cause,\n        }),\n    ),\n    Effect.flatMap((exists) =>\n      exists\n        ? fileSystem.readFileString(machineInfoPath).pipe(\n            Effect.mapError(\n              (cause) =>\n                new ServerEnvironmentLabelFileError({\n                  operation: \"read\",\n                  path: machineInfoPath,\n                  cause,\n                }),\n            ),\n          )\n        : Effect.succeed(null),\n    ),\n    Effect.catchTags({\n      ServerEnvironmentLabelFileError: (error) =>\n        Effect.logDebug(error.message).pipe(\n          Effect.annotateLogs({\n            operation: error.operation,\n            path: error.path,\n            cause: error,\n          }),\n          Effect.as(null),\n        ),\n    }),\n  );\n});\n\nconst runFriendlyLabelCommand = Effect.fn(\"runFriendlyLabelCommand\")(function* (input: {\n  readonly probe: ServerEnvironmentLabelCommandProbe;\n  readonly command: string;\n  readonly args: readonly string[];\n}) {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const result = yield* processRunner\n    .run({\n      command: input.command,\n      args: input.args,\n      timeoutBehavior: \"timedOutResult\",\n    })\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentLabelCommandError({\n            probe: input.probe,\n            executable: input.command,\n            argumentCount: input.args.length,\n            cause,\n          }),\n      ),\n      Effect.map(Option.some),\n      Effect.catchTags({\n        ServerEnvironmentLabelCommandError: (error) =>\n          Effect.logDebug(error.message).pipe(\n            Effect.annotateLogs({\n              probe: error.probe,\n              executable: error.executable,\n              argumentCount: error.argumentCount,\n              cause: error,\n            }),\n            Effect.as(Option.none()),\n          ),\n      }),\n    );\n\n  if (Option.isNone(result) || result.value.code !== 0) {\n    return null;\n  }\n\n  return normalizeLabel(result.value.stdout);\n});\n\nconst resolveFriendlyHostLabel = Effect.fn(\"resolveFriendlyHostLabel\")(function* () {\n  const platform = yield* HostProcessPlatform;\n  if (platform === \"darwin\") {\n    return yield* runFriendlyLabelCommand({\n      probe: \"macos-computer-name\",\n      command: \"scutil\",\n      args: [\"--get\", \"ComputerName\"],\n    });\n  }\n\n  if (platform === \"linux\") {\n    const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());\n    if (machineInfo) {\n      const prettyHostname = parseMachineInfoValue(machineInfo, \"PRETTY_HOSTNAME\");\n      if (prettyHostname) {\n        return prettyHostname;\n      }\n    }\n\n    return yield* runFriendlyLabelCommand({\n      probe: \"linux-pretty-hostname\",\n      command: \"hostnamectl\",\n      args: [\"--pretty\"],\n    });\n  }\n\n  return null;\n});\n\nexport const resolveServerEnvironmentLabel = Effect.fn(\"resolveServerEnvironmentLabel\")(function* (\n  input: ResolveServerEnvironmentLabelInput,\n) {\n  const friendlyHostLabel = yield* resolveFriendlyHostLabel();\n  if (friendlyHostLabel) {\n    return friendlyHostLabel;\n  }\n\n  const hostname = normalizeLabel(yield* HostProcessHostname);\n  if (hostname) {\n    return hostname;\n  }\n\n  return normalizeLabel(input.cwdBaseName) ?? \"T3 environment\";\n});\n","import { EnvironmentId, type ExecutionEnvironmentDescriptor } from \"@t3tools/contracts\";\nimport { HostProcessArchitecture, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport * as ServerConfig from \"../config.ts\";\nimport * as ProcessRunner from \"../processRunner.ts\";\nimport { resolveServerEnvironmentLabel } from \"./ServerEnvironmentLabel.ts\";\n\nexport class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(\n  \"ServerEnvironmentIdPersistenceError\",\n  {\n    operation: Schema.Literals([\"check\", \"read\", \"write\"]),\n    environmentIdPath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;\n  }\n}\n\nexport class ServerEnvironment extends Context.Service<\n  ServerEnvironment,\n  {\n    readonly getEnvironmentId: Effect.Effect<EnvironmentId>;\n    readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;\n  }\n>()(\"t3/environment/ServerEnvironment\") {}\n\nfunction platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor[\"platform\"][\"os\"] {\n  switch (platform) {\n    case \"darwin\":\n      return \"darwin\";\n    case \"linux\":\n      return \"linux\";\n    case \"win32\":\n      return \"windows\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction platformArch(\n  architecture: NodeJS.Architecture,\n): ExecutionEnvironmentDescriptor[\"platform\"][\"arch\"] {\n  switch (architecture) {\n    case \"arm64\":\n      return \"arm64\";\n    case \"x64\":\n      return \"x64\";\n    default:\n      return \"other\";\n  }\n}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const crypto = yield* Crypto.Crypto;\n  const hostPlatform = yield* HostProcessPlatform;\n  const hostArchitecture = yield* HostProcessArchitecture;\n\n  const readPersistedEnvironmentId = Effect.gen(function* () {\n    const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentIdPersistenceError({\n            operation: \"check\",\n            environmentIdPath: serverConfig.environmentIdPath,\n            cause,\n          }),\n      ),\n    );\n    if (!exists) {\n      return null;\n    }\n\n    const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(\n      Effect.map((value) => value.trim()),\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentIdPersistenceError({\n            operation: \"read\",\n            environmentIdPath: serverConfig.environmentIdPath,\n            cause,\n          }),\n      ),\n    );\n\n    return raw.length > 0 ? raw : null;\n  });\n\n  const persistEnvironmentId = (value: string) =>\n    fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\\n`).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentIdPersistenceError({\n            operation: \"write\",\n            environmentIdPath: serverConfig.environmentIdPath,\n            cause,\n          }),\n      ),\n    );\n\n  const environmentIdRaw = yield* Effect.gen(function* () {\n    const persisted = yield* readPersistedEnvironmentId;\n    if (persisted) {\n      return persisted;\n    }\n\n    const generated = yield* crypto.randomUUIDv4;\n    yield* persistEnvironmentId(generated);\n    return generated;\n  });\n\n  const environmentId = EnvironmentId.make(environmentIdRaw);\n  const cwdBaseName = path.basename(serverConfig.cwd).trim();\n  const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });\n\n  const descriptor: ExecutionEnvironmentDescriptor = {\n    environmentId,\n    label,\n    platform: {\n      os: platformOs(hostPlatform),\n      arch: platformArch(hostArchitecture),\n    },\n    serverVersion: packageJson.version,\n    capabilities: {\n      repositoryIdentity: true,\n      connectionProbe: true,\n      threadSettlement: true,\n      threadSnooze: true,\n      threadPinning: true,\n      threadTitleRegeneration: true,\n      portProxy: true,\n    },\n  };\n\n  return ServerEnvironment.of({\n    getEnvironmentId: Effect.succeed(environmentId),\n    getDescriptor: Effect.succeed(descriptor),\n  });\n});\n\n/**\n * ServerEnvironment is acquired from persisted filesystem and host-process\n * state. It intentionally has no fallback Layer.succeed value: callers must\n * provide the external platform services and a ServerConfig.\n */\nexport const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));\n","import * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\nexport interface ProviderSessionReaperShape {\n  /**\n   * Start the background provider session reaper within the provided scope.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n}\n\nexport class ProviderSessionReaper extends Context.Service<\n  ProviderSessionReaper,\n  ProviderSessionReaperShape\n>()(\"t3/provider/Services/ProviderSessionReaper\") {}\n","import * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\nexport class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(\n  \"t3/serverActivation\",\n  { defaultValue: () => undefined },\n) {}\n\n/** Forks a long-running root before commit and proves it is parked at the activation boundary. */\nexport const forkParked = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n): Effect.Effect<void, never, Scope.Scope | R> =>\n  Effect.gen(function* () {\n    const activation = yield* ServerActivation;\n    if (activation === undefined) {\n      yield* Effect.forkScoped(effect);\n      return;\n    }\n    const parked = yield* Deferred.make<void>();\n    yield* Effect.forkScoped(\n      Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),\n    );\n    yield* Deferred.await(parked);\n  });\n","import {\n  CommandId,\n  DEFAULT_MODEL,\n  DEFAULT_PROVIDER_INTERACTION_MODE,\n  type ModelSelection,\n  ProjectId,\n  ProviderInstanceId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Console from \"effect/Console\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\n\nimport * as ServerConfig from \"./config.ts\";\nimport * as Keybindings from \"./keybindings.ts\";\nimport * as ExternalLauncher from \"./process/externalLauncher.ts\";\nimport * as OrchestrationEngine from \"./orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"./orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport * as OrchestrationReactor from \"./orchestration/Services/OrchestrationReactor.ts\";\nimport * as ServerLifecycleEvents from \"./serverLifecycleEvents.ts\";\nimport * as ServerSettings from \"./serverSettings.ts\";\nimport * as AnalyticsService from \"./telemetry/AnalyticsService.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport * as ProviderSessionReaper from \"./provider/Services/ProviderSessionReaper.ts\";\nimport { forkParked } from \"./serverActivation.ts\";\nimport {\n  formatHeadlessServeOutput,\n  formatHostForUrl,\n  isWildcardHost,\n  issueHeadlessServeAccessInfo,\n} from \"./startupAccess.ts\";\n\nexport class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(\n  \"ServerRuntimeStartupError\",\n  {\n    mode: ServerConfig.RuntimeMode,\n    host: Schema.NullOr(Schema.String),\n    port: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Server runtime startup failed before command readiness.\";\n  }\n}\n\nexport class ServerRuntimeStartup extends Context.Service<\n  ServerRuntimeStartup,\n  {\n    readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;\n    readonly markHttpListening: Effect.Effect<void>;\n    readonly enqueueCommand: <A, E>(\n      effect: Effect.Effect<A, E>,\n    ) => Effect.Effect<A, E | ServerRuntimeStartupError>;\n  }\n>()(\"t3/serverRuntimeStartup\") {}\n\ninterface QueuedCommand {\n  readonly run: Effect.Effect<void, never>;\n}\n\ntype CommandReadinessState = \"pending\" | \"ready\" | ServerRuntimeStartupError;\n\ninterface CommandGate {\n  readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;\n  readonly signalCommandReady: Effect.Effect<void>;\n  readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;\n  readonly enqueueCommand: <A, E>(\n    effect: Effect.Effect<A, E>,\n  ) => Effect.Effect<A, E | ServerRuntimeStartupError>;\n}\n\nconst settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>\n  Exit.isSuccess(exit)\n    ? Deferred.succeed(deferred, exit.value)\n    : Deferred.failCause(deferred, exit.cause);\n\nexport const makeCommandGate = Effect.gen(function* () {\n  const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();\n  const commandQueue = yield* Queue.unbounded<QueuedCommand>();\n  const commandReadinessState = yield* Ref.make<CommandReadinessState>(\"pending\");\n\n  const commandWorker = Effect.forever(\n    Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),\n  );\n  yield* Effect.forkScoped(commandWorker);\n\n  return {\n    awaitCommandReady: Deferred.await(commandReady),\n    signalCommandReady: Effect.gen(function* () {\n      yield* Ref.set(commandReadinessState, \"ready\");\n      yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);\n    }),\n    failCommandReady: (error) =>\n      Effect.gen(function* () {\n        yield* Ref.set(commandReadinessState, error);\n        yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);\n      }),\n    enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>\n      Effect.gen(function* () {\n        const readinessState = yield* Ref.get(commandReadinessState);\n        if (readinessState === \"ready\") {\n          return yield* effect;\n        }\n        if (readinessState !== \"pending\") {\n          return yield* readinessState;\n        }\n\n        const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();\n        yield* Queue.offer(commandQueue, {\n          run: Deferred.await(commandReady).pipe(\n            Effect.flatMap(() => effect),\n            Effect.exit,\n            Effect.flatMap((exit) => settleQueuedCommand(result, exit)),\n          ),\n        });\n        return yield* Deferred.await(result);\n      }),\n  } satisfies CommandGate;\n});\n\nexport const recordStartupHeartbeat = Effect.gen(function* () {\n  const analytics = yield* AnalyticsService.AnalyticsService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n\n  const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(\n    Effect.catch((cause) =>\n      Effect.logWarning(\"failed to gather startup projection counts for telemetry\", {\n        cause,\n      }).pipe(\n        Effect.as({\n          threadCount: 0,\n          projectCount: 0,\n        }),\n      ),\n    ),\n  );\n\n  yield* analytics.record(\"server.boot.heartbeat\", {\n    threadCount,\n    projectCount,\n  });\n});\n\nexport const launchStartupHeartbeat = recordStartupHeartbeat.pipe(\n  Effect.annotateSpans({ \"startup.phase\": \"heartbeat.record\" }),\n  Effect.withSpan(\"server.startup.heartbeat.record\"),\n  Effect.ignoreCause({ log: true }),\n  Effect.forkScoped,\n  Effect.asVoid,\n);\n\nexport const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({\n  instanceId: ProviderInstanceId.make(\"codex\"),\n  model: DEFAULT_MODEL,\n});\n\nexport const resolveWelcomeBase = Effect.gen(function* () {\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const segments = serverConfig.cwd.split(/[/\\\\]/).filter(Boolean);\n  const projectName = segments[segments.length - 1] ?? \"project\";\n\n  return {\n    cwd: serverConfig.cwd,\n    projectName,\n  } as const;\n});\n\nexport const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const randomUUID = crypto.randomUUIDv4;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const projectionReadModelQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;\n  const path = yield* Path.Path;\n\n  let bootstrapProjectId: ProjectId | undefined;\n  let bootstrapThreadId: ThreadId | undefined;\n\n  if (serverConfig.autoBootstrapProjectFromCwd) {\n    yield* Effect.gen(function* () {\n      const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(\n        serverConfig.cwd,\n      );\n      let nextProjectId: ProjectId;\n      let nextProjectDefaultModelSelection: ModelSelection;\n\n      if (Option.isNone(existingProject)) {\n        const createdAt = DateTime.formatIso(yield* DateTime.now);\n        nextProjectId = ProjectId.make(yield* randomUUID);\n        const bootstrapProjectTitle = path.basename(serverConfig.cwd) || \"project\";\n        nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection();\n        yield* orchestrationEngine.dispatch({\n          type: \"project.create\",\n          commandId: CommandId.make(yield* randomUUID),\n          projectId: nextProjectId,\n          title: bootstrapProjectTitle,\n          workspaceRoot: serverConfig.cwd,\n          defaultModelSelection: nextProjectDefaultModelSelection,\n          createdAt,\n        });\n      } else {\n        nextProjectId = existingProject.value.id;\n        nextProjectDefaultModelSelection =\n          existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection();\n      }\n\n      const existingThreadId =\n        yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);\n      if (Option.isNone(existingThreadId)) {\n        const createdAt = DateTime.formatIso(yield* DateTime.now);\n        const createdThreadId = ThreadId.make(yield* randomUUID);\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.create\",\n          commandId: CommandId.make(yield* randomUUID),\n          threadId: createdThreadId,\n          projectId: nextProjectId,\n          title: \"New thread\",\n          modelSelection: nextProjectDefaultModelSelection,\n          interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n          runtimeMode: \"full-access\",\n          branch: null,\n          worktreePath: null,\n          createdAt,\n        });\n        bootstrapProjectId = nextProjectId;\n        bootstrapThreadId = createdThreadId;\n      } else {\n        bootstrapProjectId = nextProjectId;\n        bootstrapThreadId = existingThreadId.value;\n      }\n    });\n  }\n\n  return {\n    ...(bootstrapProjectId ? { bootstrapProjectId } : {}),\n    ...(bootstrapThreadId ? { bootstrapThreadId } : {}),\n  } as const;\n});\n\nconst resolveStartupBrowserTarget = Effect.gen(function* () {\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n  const localUrl = `http://localhost:${serverConfig.port}`;\n  const bindUrl =\n    serverConfig.host && !isWildcardHost(serverConfig.host)\n      ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`\n      : localUrl;\n  const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;\n  return yield* Effect.succeed(serverConfig.mode === \"desktop\" ? baseTarget : undefined).pipe(\n    Effect.flatMap((target) =>\n      target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),\n    ),\n  );\n});\n\nconst maybeOpenBrowser = (target: string) =>\n  Effect.gen(function* () {\n    const serverConfig = yield* ServerConfig.ServerConfig;\n    if (serverConfig.noBrowser) {\n      return;\n    }\n    const externalLauncher = yield* ExternalLauncher.ExternalLauncher;\n\n    yield* externalLauncher.launchBrowser(target).pipe(\n      Effect.catch(() =>\n        Effect.logInfo(\"browser auto-open unavailable\", {\n          hint: `Open ${target} in your browser.`,\n        }),\n      ),\n    );\n  });\n\nconst runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>\n  effect.pipe(\n    Effect.annotateSpans({ \"startup.phase\": phase }),\n    Effect.withSpan(`server.startup.${phase}`),\n  );\n\ninterface StartupOptions {\n  readonly activate?: Effect.Effect<void>;\n  readonly awaitAuxiliaryParked?: Effect.Effect<void>;\n  readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;\n}\n\nexport const make = (options?: StartupOptions) =>\n  Effect.gen(function* () {\n    const serverConfig = yield* ServerConfig.ServerConfig;\n    const keybindings = yield* Keybindings.Keybindings;\n    const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;\n    const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;\n    const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;\n    const serverSettings = yield* ServerSettings.ServerSettingsService;\n    const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;\n    const crypto = yield* Crypto.Crypto;\n\n    const commandGate = yield* makeCommandGate;\n    const httpListening = yield* Deferred.make<void>();\n    const reactorScope = yield* Scope.make(\"sequential\");\n\n    yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));\n\n    const startup = Effect.gen(function* () {\n      yield* Effect.logDebug(\"startup phase: starting keybindings runtime\");\n      yield* runStartupPhase(\n        \"keybindings.start\",\n        keybindings.start.pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"failed to start keybindings runtime\", {\n              path: error.configPath,\n              detail: error.detail,\n              cause: error.cause,\n            }),\n          ),\n        ),\n      );\n\n      yield* Effect.logDebug(\"startup phase: starting server settings runtime\");\n      yield* runStartupPhase(\n        \"settings.start\",\n        serverSettings.start.pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"failed to start server settings runtime\", {\n              path: error.settingsPath,\n              operation: error.operation,\n              providerInstanceId: error.providerInstanceId,\n              environmentVariable: error.environmentVariable,\n              cause: error.cause,\n            }),\n          ),\n        ),\n      );\n\n      yield* Effect.logDebug(\"startup phase: parking orchestration roots at activation\");\n      yield* runStartupPhase(\n        \"reactors.start\",\n        Effect.gen(function* () {\n          yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));\n          yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));\n        }),\n      );\n\n      const welcomeBase = yield* resolveWelcomeBase;\n      const environment = yield* serverEnvironment.getDescriptor;\n      yield* Effect.logDebug(\"startup phase: preparing welcome payload\");\n\n      if (serverConfig.autoBootstrapProjectFromCwd) {\n        yield* forkParked(\n          runStartupPhase(\n            \"welcome.autobootstrap\",\n            Effect.gen(function* () {\n              const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe(\n                Effect.provideService(Crypto.Crypto, crypto),\n              );\n              if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {\n                return;\n              }\n\n              yield* Effect.logDebug(\"startup phase: publishing bootstrapped welcome event\", {\n                environmentId: environment.environmentId,\n                cwd: welcomeBase.cwd,\n                projectName: welcomeBase.projectName,\n                bootstrapProjectId: bootstrapTargets.bootstrapProjectId,\n                bootstrapThreadId: bootstrapTargets.bootstrapThreadId,\n              });\n              yield* lifecycleEvents.publish({\n                version: 1,\n                type: \"welcome\",\n                payload: {\n                  environment,\n                  ...welcomeBase,\n                  ...bootstrapTargets,\n                },\n              });\n            }).pipe(\n              Effect.catch((cause) =>\n                Effect.logWarning(\"startup auto-bootstrap welcome failed\", {\n                  cause,\n                }),\n              ),\n            ),\n          ),\n        );\n      }\n\n      yield* forkParked(\n        Effect.gen(function* () {\n          yield* Effect.logDebug(\"startup phase: recording startup heartbeat\");\n          yield* recordStartupHeartbeat.pipe(\n            Effect.annotateSpans({ \"startup.phase\": \"heartbeat.record\" }),\n            Effect.withSpan(\"server.startup.heartbeat.record\"),\n            Effect.ignoreCause({ log: true }),\n          );\n          if (serverConfig.startupPresentation === \"headless\") {\n            const accessInfo = yield* issueHeadlessServeAccessInfo();\n            yield* runStartupPhase(\n              \"headless.output\",\n              Console.log(formatHeadlessServeOutput(accessInfo)),\n            );\n          } else {\n            const startupBrowserTarget = yield* resolveStartupBrowserTarget;\n            if (serverConfig.mode !== \"desktop\") {\n              yield* Effect.logInfo(\n                \"Authentication required. Open T3 Code using the pairing URL.\",\n              ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));\n            }\n            yield* runStartupPhase(\"browser.open\", maybeOpenBrowser(startupBrowserTarget));\n          }\n        }),\n      );\n\n      yield* Effect.logDebug(\"startup phase: waiting for http listener\");\n      yield* runStartupPhase(\"http.wait\", Deferred.await(httpListening));\n      yield* runStartupPhase(\n        \"auxiliary-roots.parked\",\n        options?.awaitAuxiliaryParked ?? Effect.void,\n      );\n\n      // This is the prepared boundary. Every dependency has been acquired and\n      // every runtime root has confirmed that it is parked before this request.\n      yield* runStartupPhase(\n        \"welcome.publish\",\n        lifecycleEvents.publish({\n          version: 1,\n          type: \"welcome\",\n          payload: { environment, ...welcomeBase },\n        }),\n      );\n      yield* options?.activate ?? Effect.void;\n\n      yield* Effect.logDebug(\"Accepting commands\");\n      yield* commandGate.signalCommandReady;\n      yield* runStartupPhase(\n        \"ready.publish\",\n        lifecycleEvents.publish({\n          version: 1,\n          type: \"ready\",\n          payload: {\n            at: DateTime.formatIso(yield* DateTime.now),\n            environment,\n          },\n        }),\n      );\n      yield* Effect.logDebug(\"startup phase: complete\");\n    }).pipe(\n      Effect.annotateSpans({\n        \"server.mode\": serverConfig.mode,\n        \"server.port\": serverConfig.port,\n        \"server.host\": serverConfig.host ?? \"default\",\n      }),\n      Effect.withSpan(\"server.startup\", { kind: \"server\", root: true }),\n    );\n\n    yield* Effect.forkScoped(\n      Effect.exit(startup).pipe(\n        Effect.flatMap((startupExit) => {\n          if (Exit.isSuccess(startupExit)) return Effect.void;\n          const error = new ServerRuntimeStartupError({\n            mode: serverConfig.mode,\n            host: serverConfig.host ?? null,\n            port: serverConfig.port,\n            cause: startupExit.cause,\n          });\n          return Effect.logError(\"server runtime startup failed\", {\n            cause: startupExit.cause,\n          }).pipe(\n            Effect.andThen(commandGate.failCommandReady(error)),\n            Effect.andThen(options?.abort?.(error) ?? Effect.void),\n          );\n        }),\n      ),\n    );\n\n    return {\n      awaitCommandReady: commandGate.awaitCommandReady,\n      markHttpListening: Deferred.succeed(httpListening, undefined),\n      enqueueCommand: commandGate.enqueueCommand,\n    } satisfies ServerRuntimeStartup[\"Service\"];\n  });\n\nexport const layerWithOptions = (options?: StartupOptions) =>\n  Layer.effect(ServerRuntimeStartup, make(options));\n\nexport const layer = layerWithOptions();\n","/**\n * WorkspacePaths - Effect service contract for workspace path handling.\n *\n * Owns normalization and validation of workspace roots plus safe resolution of\n * workspace-root-relative paths.\n *\n * @module WorkspacePaths\n */\nimport * as NodeOS from \"node:os\";\n\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nexport class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<WorkspaceRootNotExistsError>()(\n  \"WorkspaceRootNotExistsError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`;\n  }\n}\n\nexport class WorkspaceRootCreateFailedError extends Schema.TaggedErrorClass<WorkspaceRootCreateFailedError>()(\n  \"WorkspaceRootCreateFailedError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to create workspace root: ${this.normalizedWorkspaceRoot}`;\n  }\n}\n\nexport class WorkspaceRootStatFailedError extends Schema.TaggedErrorClass<WorkspaceRootStatFailedError>()(\n  \"WorkspaceRootStatFailedError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n    phase: Schema.Literals([\"validate-existing\", \"verify-created\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to stat workspace root '${this.normalizedWorkspaceRoot}' during '${this.phase}'.`;\n  }\n}\n\nexport class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(\n  \"WorkspaceRootNotDirectoryError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`;\n  }\n}\n\nexport class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<WorkspacePathOutsideRootError>()(\n  \"WorkspacePathOutsideRootError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace file path must be relative to the project root: ${this.relativePath}`;\n  }\n}\n\nexport const WorkspacePathsError = Schema.Union([\n  WorkspaceRootNotExistsError,\n  WorkspaceRootCreateFailedError,\n  WorkspaceRootStatFailedError,\n  WorkspaceRootNotDirectoryError,\n  WorkspacePathOutsideRootError,\n]);\nexport type WorkspacePathsError = typeof WorkspacePathsError.Type;\n\n/** Service tag for workspace path normalization and resolution. */\nexport class WorkspacePaths extends Context.Service<\n  WorkspacePaths,\n  {\n    /** Normalize a user-provided workspace root and verify it exists as a directory. */\n    readonly normalizeWorkspaceRoot: (\n      workspaceRoot: string,\n      options?: { readonly createIfMissing?: boolean },\n    ) => Effect.Effect<\n      string,\n      | WorkspaceRootNotExistsError\n      | WorkspaceRootCreateFailedError\n      | WorkspaceRootStatFailedError\n      | WorkspaceRootNotDirectoryError\n    >;\n    /**\n     * Resolve a relative path within a validated workspace root.\n     *\n     * Rejects absolute paths and traversal attempts outside the workspace root.\n     */\n    readonly resolveRelativePathWithinRoot: (input: {\n      workspaceRoot: string;\n      relativePath: string;\n    }) => Effect.Effect<\n      { absolutePath: string; relativePath: string },\n      WorkspacePathOutsideRootError\n    >;\n  }\n>()(\"t3/workspace/WorkspacePaths\") {}\n\nfunction toPosixRelativePath(input: string): string {\n  return input.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction expandHomePath(input: string, path: Path.Path): string {\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return path.join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const statWorkspaceRoot = Effect.fn(\"WorkspacePaths.statWorkspaceRoot\")(function* (\n    workspaceRoot: string,\n    normalizedWorkspaceRoot: string,\n    phase: WorkspaceRootStatFailedError[\"phase\"],\n  ) {\n    return yield* fileSystem.stat(normalizedWorkspaceRoot).pipe(\n      Effect.matchEffect({\n        onFailure: (cause) =>\n          cause.reason._tag === \"NotFound\"\n            ? Effect.succeed(null)\n            : Effect.fail(\n                new WorkspaceRootStatFailedError({\n                  workspaceRoot,\n                  normalizedWorkspaceRoot,\n                  phase,\n                  cause,\n                }),\n              ),\n        onSuccess: Effect.succeed,\n      }),\n    );\n  });\n\n  const normalizeWorkspaceRoot: WorkspacePaths[\"Service\"][\"normalizeWorkspaceRoot\"] = Effect.fn(\n    \"WorkspacePaths.normalizeWorkspaceRoot\",\n  )(function* (workspaceRoot, options) {\n    const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));\n    let workspaceStat = yield* statWorkspaceRoot(\n      workspaceRoot,\n      normalizedWorkspaceRoot,\n      \"validate-existing\",\n    );\n    if (!workspaceStat && options?.createIfMissing) {\n      yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new WorkspaceRootCreateFailedError({\n              workspaceRoot,\n              normalizedWorkspaceRoot,\n              cause,\n            }),\n        ),\n      );\n      workspaceStat = yield* statWorkspaceRoot(\n        workspaceRoot,\n        normalizedWorkspaceRoot,\n        \"verify-created\",\n      );\n    }\n    if (!workspaceStat) {\n      return yield* new WorkspaceRootNotExistsError({\n        workspaceRoot,\n        normalizedWorkspaceRoot,\n      });\n    }\n    if (workspaceStat.type !== \"Directory\") {\n      return yield* new WorkspaceRootNotDirectoryError({\n        workspaceRoot,\n        normalizedWorkspaceRoot,\n      });\n    }\n    return normalizedWorkspaceRoot;\n  });\n\n  const resolveRelativePathWithinRoot: WorkspacePaths[\"Service\"][\"resolveRelativePathWithinRoot\"] =\n    Effect.fn(\"WorkspacePaths.resolveRelativePathWithinRoot\")(function* (input) {\n      const normalizedInputPath = input.relativePath.trim();\n      if (path.isAbsolute(normalizedInputPath)) {\n        return yield* new WorkspacePathOutsideRootError({\n          workspaceRoot: input.workspaceRoot,\n          relativePath: input.relativePath,\n        });\n      }\n\n      const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath);\n      const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath));\n      if (\n        relativeToRoot.length === 0 ||\n        relativeToRoot === \".\" ||\n        relativeToRoot.startsWith(\"../\") ||\n        relativeToRoot === \"..\" ||\n        path.isAbsolute(relativeToRoot)\n      ) {\n        return yield* new WorkspacePathOutsideRootError({\n          workspaceRoot: input.workspaceRoot,\n          relativePath: input.relativePath,\n        });\n      }\n\n      return {\n        absolutePath,\n        relativePath: relativeToRoot,\n      };\n    });\n\n  return WorkspacePaths.of({ normalizeWorkspaceRoot, resolveRelativePathWithinRoot });\n});\n\nexport const layer = Layer.effect(WorkspacePaths, make);\n","import {\n  CommandId,\n  AuthAdministrativeScopes,\n  EnvironmentHttpApi,\n  EnvironmentHttpCommonError,\n  type OrchestrationReadModel,\n  ProjectId,\n  type ClientOrchestrationCommand,\n} from \"@t3tools/contracts\";\nimport * as Console from \"effect/Console\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport { Argument, Command, Flag, GlobalFlag } from \"effect/unstable/cli\";\nimport { FetchHttpClient, HttpClient, HttpClientError } from \"effect/unstable/http\";\nimport * as HttpApiClient from \"effect/unstable/httpapi/HttpApiClient\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as OrchestrationEngine from \"../orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport { OrchestrationLayerLive } from \"../orchestration/runtimeLayer.ts\";\nimport { layerConfig as SqlitePersistenceLayerLive } from \"../persistence/Layers/Sqlite.ts\";\nimport * as RepositoryIdentityResolver from \"../project/RepositoryIdentityResolver.ts\";\nimport * as ServerRuntimeStartup from \"../serverRuntimeStartup.ts\";\nimport {\n  clearPersistedServerRuntimeState,\n  readPersistedServerRuntimeState,\n} from \"../serverRuntimeState.ts\";\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\nimport { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from \"./config.ts\";\n\ntype ProjectMutationTarget = {\n  readonly id: ProjectId;\n  readonly title: string;\n  readonly workspaceRoot: string;\n};\n\ntype ProjectCommandExecutionMode = \"live\" | \"offline\";\ntype ProjectCliDispatchCommand = Extract<\n  ClientOrchestrationCommand,\n  { type: \"project.create\" | \"project.meta.update\" | \"project.delete\" }\n>;\n\nconst isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);\n\nexport class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(\n  \"ProjectCommandIdGenerationError\",\n  {\n    operation: Schema.Literal(\"generateProjectCommandId\"),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to generate a project command identifier.\";\n  }\n}\n\nexport class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(\n  \"ProjectLiveServerDeclaredResponseError\",\n  {\n    operation: Schema.Literal(\"callLiveServer\"),\n    code: Schema.String,\n    traceId: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Server request failed (${this.code}, trace ${this.traceId}).`;\n  }\n}\n\nexport class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(\n  \"ProjectLiveServerUndeclaredStatusError\",\n  {\n    operation: Schema.Literal(\"callLiveServer\"),\n    status: Schema.Int,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Server request failed with undeclared status ${this.status}.`;\n  }\n}\n\nexport class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(\n  \"ProjectLiveServerRequestError\",\n  {\n    operation: Schema.Literal(\"callLiveServer\"),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to call the running server.\";\n  }\n}\n\nexport class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(\n  \"ProjectTitleEmptyError\",\n  {\n    operation: Schema.Literal(\"validateProjectTitle\"),\n    title: Schema.String,\n  },\n) {\n  override get message(): string {\n    return \"Project title cannot be empty.\";\n  }\n}\n\nexport class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(\n  \"ProjectIdentifierEmptyError\",\n  {\n    operation: Schema.Literal(\"resolveProjectTarget\"),\n    identifier: Schema.String,\n  },\n) {\n  override get message(): string {\n    return \"Project identifier cannot be empty.\";\n  }\n}\n\nexport class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(\n  \"ProjectNotFoundError\",\n  {\n    operation: Schema.Literal(\"resolveProjectTarget\"),\n    identifier: Schema.String,\n    normalizedWorkspaceRoot: Schema.optional(Schema.String),\n    activeProjectCount: Schema.Number,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `No active project found for '${this.identifier}'.`;\n  }\n}\n\nexport class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(\n  \"ProjectAlreadyExistsError\",\n  {\n    operation: Schema.Literal(\"addProject\"),\n    projectId: ProjectId,\n    workspaceRoot: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `An active project already exists for '${this.workspaceRoot}'.`;\n  }\n}\n\nexport const ProjectCommandError = Schema.Union([\n  ProjectCommandIdGenerationError,\n  ProjectLiveServerDeclaredResponseError,\n  ProjectLiveServerUndeclaredStatusError,\n  ProjectLiveServerRequestError,\n  ProjectTitleEmptyError,\n  ProjectIdentifierEmptyError,\n  ProjectNotFoundError,\n  ProjectAlreadyExistsError,\n]);\nexport type ProjectCommandError = typeof ProjectCommandError.Type;\n\nexport function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {\n  if (isEnvironmentHttpCommonError(cause)) {\n    return new ProjectLiveServerDeclaredResponseError({\n      operation: \"callLiveServer\",\n      code: cause.code,\n      traceId: cause.traceId,\n      cause,\n    });\n  }\n  if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {\n    return new ProjectLiveServerUndeclaredStatusError({\n      operation: \"callLiveServer\",\n      status: cause.response.status,\n      cause,\n    });\n  }\n\n  return new ProjectLiveServerRequestError({ operation: \"callLiveServer\", cause });\n}\n\nconst projectCommandUuid = Crypto.Crypto.pipe(\n  Effect.flatMap((crypto) => crypto.randomUUIDv4),\n  Effect.mapError(\n    (cause) =>\n      new ProjectCommandIdGenerationError({\n        operation: \"generateProjectCommandId\",\n        cause,\n      }),\n  ),\n);\n\nconst ProjectCliRuntimeLive = Layer.mergeAll(\n  WorkspacePaths.layer,\n  OrchestrationLayerLive.pipe(\n    Layer.provideMerge(RepositoryIdentityResolver.layer),\n    Layer.provideMerge(SqlitePersistenceLayerLive),\n  ),\n);\n\nconst PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);\nconst withProjectCliSessionToken = <A, E, R>(\n  environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"],\n  run: (token: string) => Effect.Effect<A, E, R>,\n) =>\n  Effect.acquireUseRelease(\n    environmentAuth.issueSession({\n      scopes: AuthAdministrativeScopes,\n      label: \"t3 project cli\",\n    }),\n    (issued) => run(issued.token),\n    (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),\n  );\n\nconst withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n  effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));\n\nconst makeLiveServerClient = (origin: string) =>\n  HttpApiClient.make(EnvironmentHttpApi, {\n    baseUrl: origin,\n  });\n\nconst normalizeWorkspaceRootForProjectCommand = Effect.fn(\n  \"normalizeWorkspaceRootForProjectCommand\",\n)(function* (workspaceRoot: string) {\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);\n});\n\nconst resolveProjectTitle = Effect.fn(\"resolveProjectTitle\")(function* (\n  workspaceRoot: string,\n  explicitTitle?: string,\n) {\n  if (explicitTitle !== undefined) {\n    const trimmed = explicitTitle.trim();\n    if (trimmed.length > 0) {\n      return trimmed;\n    }\n    return yield* new ProjectTitleEmptyError({\n      operation: \"validateProjectTitle\",\n      title: explicitTitle,\n    });\n  }\n\n  const path = yield* Path.Path;\n  const basename = path.basename(workspaceRoot).trim();\n  return basename.length > 0 ? basename : \"project\";\n});\n\nconst findActiveProjectTarget = Effect.fn(\"findActiveProjectTarget\")(function* (input: {\n  readonly snapshot: OrchestrationReadModel;\n  readonly identifier: string;\n}) {\n  const trimmedIdentifier = input.identifier.trim();\n  if (trimmedIdentifier.length === 0) {\n    return yield* new ProjectIdentifierEmptyError({\n      operation: \"resolveProjectTarget\",\n      identifier: input.identifier,\n    });\n  }\n\n  const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);\n  const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);\n  if (exactIdMatch) {\n    return {\n      id: exactIdMatch.id,\n      title: exactIdMatch.title,\n      workspaceRoot: exactIdMatch.workspaceRoot,\n    } satisfies ProjectMutationTarget;\n  }\n\n  const normalizedWorkspaceRootResult = yield* Effect.result(\n    normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),\n  );\n  const normalizedWorkspaceRoot =\n    normalizedWorkspaceRootResult._tag === \"Success\" ? normalizedWorkspaceRootResult.success : null;\n\n  const exactWorkspaceMatch =\n    normalizedWorkspaceRoot === null\n      ? undefined\n      : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);\n\n  const resolved = exactWorkspaceMatch;\n  if (!resolved) {\n    return yield* new ProjectNotFoundError({\n      operation: \"resolveProjectTarget\",\n      identifier: trimmedIdentifier,\n      activeProjectCount: activeProjects.length,\n      ...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),\n      ...(normalizedWorkspaceRootResult._tag === \"Failure\"\n        ? { cause: normalizedWorkspaceRootResult.failure }\n        : {}),\n    });\n  }\n\n  return {\n    id: resolved.id,\n    title: resolved.title,\n    workspaceRoot: resolved.workspaceRoot,\n  } satisfies ProjectMutationTarget;\n});\n\nconst fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>\n  Effect.gen(function* () {\n    const client = yield* makeLiveServerClient(origin);\n    return yield* client.orchestration.snapshot({\n      headers: { authorization: `Bearer ${bearerToken}` },\n    });\n  }).pipe(\n    withProjectCliLiveServerTimeout,\n    Effect.mapError(projectCommandErrorFromLiveServerRequest),\n  );\n\nconst dispatchLiveOrchestrationCommand = (\n  origin: string,\n  bearerToken: string,\n  command: ProjectCliDispatchCommand,\n) =>\n  Effect.gen(function* () {\n    const client = yield* makeLiveServerClient(origin);\n    yield* client.orchestration.dispatch({\n      headers: { authorization: `Bearer ${bearerToken}` },\n      payload: command,\n    } as Parameters<typeof client.orchestration.dispatch>[0]);\n  }).pipe(\n    withProjectCliLiveServerTimeout,\n    Effect.mapError(projectCommandErrorFromLiveServerRequest),\n  );\n\nconst getOfflineSnapshot = Effect.fn(\"getOfflineSnapshot\")(function* () {\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  // Project commands only read the project list, so use the lightweight\n  // command read model instead of hydrating every thread body in the database.\n  return yield* projectionSnapshotQuery.getCommandReadModel();\n});\n\nconst tryResolveLiveProjectExecutionMode = Effect.fn(\"tryResolveLiveProjectExecutionMode\")(\n  function* (\n    environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"],\n    config: ServerConfig.ServerConfig[\"Service\"],\n  ) {\n    const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);\n    if (Option.isNone(runtimeState)) {\n      return Option.none<{ readonly origin: string }>();\n    }\n\n    const attempt = withProjectCliSessionToken(environmentAuth, (token) =>\n      fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(\n        Effect.as({\n          origin: runtimeState.value.origin,\n        }),\n      ),\n    );\n\n    const attempted = yield* Effect.result(attempt);\n    if (attempted._tag === \"Success\") {\n      return Option.some(attempted.success);\n    }\n\n    yield* Effect.logDebug(\"Failed to connect to the persisted project CLI server.\", {\n      origin: runtimeState.value.origin,\n      cause: attempted.failure,\n    });\n    yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);\n    return Option.none<{ readonly origin: string }>();\n  },\n);\n\nconst runProjectMutation = Effect.fn(\"runProjectMutation\")(function* (\n  flags: CliAuthLocationFlags,\n  run: (input: {\n    readonly snapshot: OrchestrationReadModel;\n    readonly dispatch: (\n      command: ProjectCliDispatchCommand,\n    ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n    readonly mode: ProjectCommandExecutionMode;\n  }) => Effect.Effect<\n    string,\n    Error,\n    | Crypto.Crypto\n    | FileSystem.FileSystem\n    | HttpClient.HttpClient\n    | Path.Path\n    | WorkspacePaths.WorkspacePaths\n  >,\n) {\n  const logLevel = yield* GlobalFlag.LogLevel;\n  const config = yield* resolveCliAuthConfig(flags, logLevel);\n  const minimumLogLevel = config.logLevel;\n\n  return yield* Effect.gen(function* () {\n    const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);\n\n    if (Option.isSome(liveMode)) {\n      return yield* withProjectCliSessionToken(environmentAuth, (token) =>\n        Effect.gen(function* () {\n          const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);\n          const output = yield* run({\n            snapshot,\n            dispatch: (command) =>\n              dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),\n            mode: \"live\",\n          });\n          yield* Console.log(output);\n        }),\n      );\n    }\n\n    const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(\n      Layer.provide(ServerConfig.layer(config)),\n      Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),\n    );\n\n    return yield* Effect.gen(function* () {\n      const snapshot = yield* getOfflineSnapshot();\n      const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;\n      const output = yield* run({\n        snapshot,\n        dispatch: (command) => orchestrationEngine.dispatch(command),\n        mode: \"offline\",\n      });\n      yield* Console.log(output);\n    }).pipe(Effect.provide(offlineRuntimeLayer));\n  }).pipe(\n    Effect.provide(\n      Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(\n        Layer.provideMerge(FetchHttpClient.layer),\n        Layer.provide(ServerConfig.layer(config)),\n        Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),\n      ),\n    ),\n  );\n});\n\nconst projectAddCommand = Command.make(\"add\", {\n  ...projectLocationFlags,\n  workspaceRoot: Argument.string(\"path\").pipe(\n    Argument.withDescription(\"Workspace root to add as a project.\"),\n  ),\n  title: Flag.string(\"title\").pipe(Flag.withDescription(\"Optional project title.\"), Flag.optional),\n}).pipe(\n  Command.withDescription(\"Add a project.\"),\n  Command.withHandler((flags) =>\n    runProjectMutation(\n      flags,\n      Effect.fn(\"projectAddMutation\")(function* ({\n        snapshot,\n        dispatch,\n      }: {\n        readonly snapshot: OrchestrationReadModel;\n        readonly dispatch: (\n          command: ProjectCliDispatchCommand,\n        ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n      }) {\n        const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);\n        const existingProject = snapshot.projects.find(\n          (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,\n        );\n        if (existingProject) {\n          return yield* new ProjectAlreadyExistsError({\n            operation: \"addProject\",\n            projectId: existingProject.id,\n            workspaceRoot,\n          });\n        }\n\n        const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));\n        const projectId = ProjectId.make(yield* projectCommandUuid);\n        yield* dispatch({\n          type: \"project.create\",\n          commandId: CommandId.make(yield* projectCommandUuid),\n          projectId,\n          title,\n          workspaceRoot,\n          defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),\n          createdAt: DateTime.formatIso(yield* DateTime.now),\n        });\n        return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;\n      }),\n    ),\n  ),\n);\n\nconst projectRemoveCommand = Command.make(\"remove\", {\n  ...projectLocationFlags,\n  project: Argument.string(\"project\").pipe(\n    Argument.withDescription(\"Project id or workspace root to remove.\"),\n  ),\n  force: Flag.boolean(\"force\").pipe(\n    Flag.withDescription(\"Delete the project and all of its threads.\"),\n    Flag.withDefault(false),\n  ),\n}).pipe(\n  Command.withDescription(\"Remove a project.\"),\n  Command.withHandler((flags) =>\n    runProjectMutation(\n      flags,\n      Effect.fn(\"projectRemoveMutation\")(function* ({\n        snapshot,\n        dispatch,\n      }: {\n        readonly snapshot: OrchestrationReadModel;\n        readonly dispatch: (\n          command: ProjectCliDispatchCommand,\n        ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n      }) {\n        const project = yield* findActiveProjectTarget({\n          snapshot,\n          identifier: flags.project,\n        });\n        yield* dispatch({\n          type: \"project.delete\",\n          commandId: CommandId.make(yield* projectCommandUuid),\n          projectId: project.id,\n          force: flags.force,\n        });\n        return `Removed project ${project.id} (${project.title}).`;\n      }),\n    ),\n  ),\n);\n\nconst projectRenameCommand = Command.make(\"rename\", {\n  ...projectLocationFlags,\n  project: Argument.string(\"project\").pipe(\n    Argument.withDescription(\"Project id or workspace root to rename.\"),\n  ),\n  title: Argument.string(\"title\").pipe(Argument.withDescription(\"New project title.\")),\n}).pipe(\n  Command.withDescription(\"Rename a project.\"),\n  Command.withHandler((flags) =>\n    runProjectMutation(\n      flags,\n      Effect.fn(\"projectRenameMutation\")(function* ({\n        snapshot,\n        dispatch,\n      }: {\n        readonly snapshot: OrchestrationReadModel;\n        readonly dispatch: (\n          command: ProjectCliDispatchCommand,\n        ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n      }) {\n        const project = yield* findActiveProjectTarget({\n          snapshot,\n          identifier: flags.project,\n        });\n        const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);\n        if (nextTitle === project.title) {\n          return `Project ${project.id} is already named ${nextTitle}.`;\n        }\n\n        yield* dispatch({\n          type: \"project.meta.update\",\n          commandId: CommandId.make(yield* projectCommandUuid),\n          projectId: project.id,\n          title: nextTitle,\n        });\n        return `Renamed project ${project.id} to ${nextTitle}.`;\n      }),\n    ),\n  ),\n);\n\nexport const projectCommand = Command.make(\"project\").pipe(\n  Command.withDescription(\"Manage projects.\"),\n  Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),\n);\n","import { randomUUID } from \"node:crypto\";\nimport {\n  closeSync,\n  mkdirSync,\n  openSync,\n  readFileSync,\n  rmSync,\n  writeSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nconst LOCK_FILE = \"daemon.lock\";\n\ntype LockRecord = {\n  pid: number;\n  token: string;\n};\n\nfunction isProcessAlive(pid: number): boolean {\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return (error as NodeJS.ErrnoException).code === \"EPERM\";\n  }\n}\n\nfunction readLock(path: string): LockRecord | undefined {\n  try {\n    const record = JSON.parse(readFileSync(path, \"utf8\")) as Partial<LockRecord>;\n    const pid = typeof record.pid === \"number\" ? record.pid : -1;\n    return Number.isInteger(pid) && pid > 0 && typeof record.token === \"string\"\n      ? { pid, token: record.token }\n      : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function acquireDaemonLock(stateDir: string): () => void {\n  mkdirSync(stateDir, { recursive: true });\n  const path = join(stateDir, LOCK_FILE);\n  const token = randomUUID();\n\n  for (;;) {\n    try {\n      const fd = openSync(path, \"wx\", 0o600);\n      writeSync(fd, JSON.stringify({ pid: process.pid, token } satisfies LockRecord));\n      let released = false;\n      return () => {\n        if (released) return;\n        released = true;\n        try {\n          if (readLock(path)?.token === token) rmSync(path, { force: true });\n        } finally {\n          closeSync(fd);\n        }\n      };\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n      const owner = readLock(path);\n      if (owner && isProcessAlive(owner.pid)) {\n        throw new Error(`已有 AgentLink daemon 正在运行（pid ${owner.pid}）。请先停止它再启动。`);\n      }\n      rmSync(path, { force: true });\n    }\n  }\n}\n","import * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Encoding from \"../../Encoding.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { identity } from \"../../Function.js\";\nimport { stringOrRedacted } from \"../../internal/redacted.js\";\nimport * as Layer from \"../../Layer.js\";\nimport { pipeArguments } from \"../../Pipeable.js\";\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Redacted from \"../../Redacted.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaAST from \"../../SchemaAST.js\";\nimport * as SchemaIssue from \"../../SchemaIssue.js\";\nimport * as SchemaTransformation from \"../../SchemaTransformation.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as UndefinedOr from \"../../UndefinedOr.js\";\nimport * as Sse from \"../encoding/Sse.js\";\nimport * as HttpEffect from \"../http/HttpEffect.js\";\nimport * as HttpMethod from \"../http/HttpMethod.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as Request from \"../http/HttpServerRequest.js\";\nimport { HttpServerRequest } from \"../http/HttpServerRequest.js\";\nimport * as Response from \"../http/HttpServerResponse.js\";\nimport * as Multipart from \"../http/Multipart.js\";\nimport * as UrlParams from \"../http/UrlParams.js\";\nimport * as HttpApiEndpoint from \"./HttpApiEndpoint.js\";\nimport { HttpApiSchemaError } from \"./HttpApiError.js\";\nimport * as HttpApiMiddleware from \"./HttpApiMiddleware.js\";\nimport * as HttpApiSchema from \"./HttpApiSchema.js\";\nimport * as MediaType from \"./internal/mediaType.js\";\nimport * as OpenApi from \"./OpenApi.js\";\n/**\n * Registers an `HttpApi` with a `HttpRouter`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (api, options) => HttpRouter.use(Effect.fnUntraced(function* (router) {\n  const services = yield* Effect.context();\n  const routes = [];\n  const availableGroups = Array.from(services.mapUnsafe.keys()).filter(key => key.startsWith(\"effect/httpapi/HttpApiGroup/\"));\n  const groups = Object.values(api.groups);\n  for (const group of groups) {\n    const groupRoutes = services.mapUnsafe.get(group.key)?.routes;\n    if (groupRoutes === undefined) {\n      const available = availableGroups.length === 0 ? \"none\" : availableGroups.join(\", \");\n      return yield* Effect.die(`HttpApiGroup \"${group.identifier}\" not found (key: \"${group.key}\"). Did you forget to provide HttpApiBuilder.group(api, \"${group.identifier}\", ...)? Available groups: ${available}`);\n    }\n    routes.push(...groupRoutes);\n  }\n  yield* router.addAll(routes);\n  if (options?.openapiPath) {\n    const spec = OpenApi.fromApi(api);\n    yield* router.add(\"GET\", options.openapiPath, Effect.succeed(Response.jsonUnsafe(spec)));\n  }\n}));\n/**\n * Create a `Layer` that implements all endpoints in an `HttpApi` group.\n *\n * **Details**\n *\n * The `build` function receives an unimplemented `Handlers` instance that can\n * be used to add handlers to the group. Implement endpoints with\n * `handlers.handle`.\n *\n * @category handlers\n * @since 4.0.0\n */\nexport const group = (api, groupIdentifier, build) => Layer.effectContext(Effect.gen(function* () {\n  const services = (yield* Effect.context()).pipe(Context.omit(Scope.Scope));\n  const group = api.groups[groupIdentifier];\n  const result = build(makeHandlers(group));\n  const handlers = Effect.isEffect(result) ? yield* result : result;\n  const routes = [];\n  for (const item of handlers.handlers.values()) {\n    routes.push(handlerToRoute(group, item, services));\n  }\n  return Context.makeUnsafe(new Map([[group.key, {\n    routes,\n    handlers: handlers.handlers\n  }]]));\n}));\nconst HandlersTypeId = \"~effect/httpapi/HttpApiBuilder/Handlers\";\n/**\n * Builds the server-side HTTP effect for a single endpoint in an API group using\n * the endpoint metadata, middleware, codecs, and supplied handler.\n *\n * @category handlers\n * @since 4.0.0\n */\nexport const endpoint = (api, groupIdentifier, endpointIdentifier, handler) => Effect.contextWith(context => {\n  const group = api.groups[groupIdentifier];\n  const endpoint = group.endpoints[endpointIdentifier];\n  return Effect.succeed(handlerToHttpEffect(group, endpoint, Context.omit(Scope.Scope)(context), handler, false));\n});\n/**\n * Decodes credentials for an HTTP API security scheme from the current request,\n * supporting bearer, API key, and basic authentication inputs.\n *\n * @category security\n * @since 4.0.0\n */\nexport const securityDecode = self => {\n  switch (self._tag) {\n    case \"Http\":\n      {\n        return Effect.map(HttpServerRequest, request => Redacted.make(getAuthorizationCredential(request.headers.authorization, self.scheme) ?? \"\"));\n      }\n    case \"ApiKey\":\n      {\n        const key = self.in === \"header\" ? self.key.toLowerCase() : self.key;\n        const schema = Schema.Struct({\n          [key]: Schema.String\n        });\n        const decode = self.in === \"query\" ? Request.schemaSearchParams(schema) : self.in === \"cookie\" ? Request.schemaCookies(schema) : Request.schemaHeaders(schema);\n        return Effect.match(decode, {\n          onFailure: () => Redacted.make(\"\"),\n          onSuccess: match => Redacted.make(match[key])\n        });\n      }\n    case \"Basic\":\n      {\n        const empty = {\n          username: \"\",\n          password: Redacted.make(\"\")\n        };\n        return Effect.map(HttpServerRequest, request => {\n          const encoded = getAuthorizationCredential(request.headers.authorization, basicScheme);\n          if (encoded === undefined) return empty;\n          const decoded = Result.getOrUndefined(Encoding.decodeBase64String(encoded));\n          if (decoded === undefined) return empty;\n          // RFC 7617, Section 2: only the first colon separates the user-id from the password.\n          // https://www.rfc-editor.org/rfc/rfc7617.html#section-2\n          const separator = decoded.indexOf(\":\");\n          if (separator === -1) return empty;\n          return {\n            username: decoded.slice(0, separator),\n            password: Redacted.make(decoded.slice(separator + 1))\n          };\n        });\n      }\n  }\n};\n/**\n * Registers a pre-response handler that sets an API-key cookie on the outgoing\n * response, defaulting the cookie to `secure` and `httpOnly` unless overridden.\n *\n * @category security\n * @since 4.0.0\n */\nexport const securitySetCookie = (self, value, options) => HttpEffect.appendPreResponseHandler((_req, response) => Effect.orDie(Response.setCookie(response, self.key, stringOrRedacted(value), {\n  secure: true,\n  httpOnly: true,\n  ...options\n})));\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\nconst basicScheme = \"Basic\";\nfunction getAuthorizationCredential(authorization, scheme) {\n  const schemeLength = scheme.length;\n  // RFC 9110, Section 11.1: schemes are case-insensitive and credentials follow 1*SP.\n  // https://www.rfc-editor.org/rfc/rfc9110.html#section-11.1\n  if (authorization === undefined || authorization.length <= schemeLength || authorization.charCodeAt(schemeLength) !== 32 || authorization.slice(0, schemeLength).toLowerCase() !== scheme.toLowerCase()) {\n    return undefined;\n  }\n  let credentialStart = schemeLength + 1;\n  while (authorization.charCodeAt(credentialStart) === 32) {\n    credentialStart++;\n  }\n  return credentialStart === authorization.length ? undefined : authorization.slice(credentialStart);\n}\nconst registerHandler = (self, identifier, handler, isRaw, options) => {\n  if (!Object.hasOwn(self.group.endpoints, identifier)) {\n    throw new Error(`HttpApiEndpoint \"${identifier}\" not found in HttpApiGroup \"${self.group.identifier}\"`);\n  }\n  if (self.handlers.has(identifier)) {\n    throw new Error(`Handler for HttpApiEndpoint \"${identifier}\" is already registered in HttpApiGroup \"${self.group.identifier}\"`);\n  }\n  const endpoint = self.group.endpoints[identifier];\n  self.handlers.set(identifier, {\n    endpoint,\n    handler,\n    isRaw,\n    uninterruptible: options?.uninterruptible ?? false\n  });\n  return self;\n};\nconst HandlersProto = {\n  [HandlersTypeId]: HandlersTypeId,\n  pipe() {\n    return pipeArguments(this, arguments);\n  },\n  handle(identifier, handler, options) {\n    return registerHandler(this, identifier, handler, false, options);\n  },\n  handleAll(handlers) {\n    for (const [identifier, entry] of Object.entries(handlers)) {\n      const handler = typeof entry === \"function\" ? entry : entry.handler;\n      const options = typeof entry === \"function\" ? undefined : entry.options;\n      registerHandler(this, identifier, handler, false, options);\n    }\n    return this;\n  },\n  handleRaw(identifier, handler, options) {\n    return registerHandler(this, identifier, handler, true, options);\n  }\n};\nconst makeHandlers = group => {\n  const self = Object.create(HandlersProto);\n  self.group = group;\n  self.handlers = new Map();\n  return self;\n};\nfunction buildPayloadDecoders(payloadMap) {\n  const result = new Map();\n  payloadMap.forEach(({\n    encoding,\n    schemas\n  }, contentType) => {\n    const decode = Schema.decodeUnknownEffect(Schema.Union(schemas));\n    if (encoding._tag === \"Multipart\") {\n      result.set(contentType, {\n        _tag: \"Multipart\",\n        mode: encoding.mode,\n        limits: encoding.limits,\n        decode\n      });\n    } else {\n      result.set(contentType, {\n        _tag: encoding._tag,\n        decode,\n        nullOnEmpty: schemas.some(s => SchemaAST.isNull(SchemaAST.toEncoded(s.ast)))\n      });\n    }\n  });\n  return result;\n}\nfunction decodePayload(payloadBy, httpRequest, query) {\n  const hasBody = HttpMethod.hasBody(httpRequest.method);\n  const contentType = hasBody ? MediaType.normalize(httpRequest.headers[\"content-type\"] ?? \"application/json\") : \"application/x-www-form-urlencoded\";\n  const existing = payloadBy.get(contentType);\n  if (!existing) {\n    return Response.text(`Unsupported content-type: ${contentType}`, {\n      status: 415\n    });\n  }\n  const {\n    _tag,\n    decode\n  } = existing;\n  switch (_tag) {\n    case \"Multipart\":\n      {\n        if (existing.mode === \"buffered\") {\n          let eff = Effect.orDie(httpRequest.multipart);\n          if (existing.limits) {\n            eff = Effect.provideContext(eff, Multipart.limitsServices(existing.limits));\n          }\n          return Effect.flatMap(eff, decode);\n        }\n        return Effect.succeed(existing.limits ? Stream.provideContext(httpRequest.multipartStream, Multipart.limitsServices(existing.limits)) : httpRequest.multipartStream);\n      }\n    case \"Json\":\n      return Effect.flatMap(Effect.orDie(httpRequest.text), text => {\n        if (text === \"\") {\n          return decode(existing.nullOnEmpty ? null : undefined);\n        }\n        try {\n          return decode(JSON.parse(text));\n        } catch {\n          return Effect.fail(new Schema.SchemaError(new SchemaIssue.InvalidValue({\n            message: \"Expected a valid JSON body\"\n          })));\n        }\n      });\n    case \"Text\":\n      return Effect.flatMap(Effect.orDie(httpRequest.text), decode);\n    case \"FormUrlEncoded\":\n      {\n        const source = hasBody ? Effect.map(Effect.orDie(httpRequest.urlParamsBody), UrlParams.toRecord) : Effect.succeed(query);\n        return Effect.flatMap(source, decode);\n      }\n    case \"Uint8Array\":\n      return Effect.flatMap(Effect.map(Effect.orDie(httpRequest.arrayBuffer), buffer => new Uint8Array(buffer)), decode);\n  }\n}\nfunction handlerToHttpEffect(group, endpoint, context, handler, isRaw) {\n  const encodeSuccess = Schema.encodeUnknownEffect(makeSuccessSchema(endpoint));\n  const encodeError = Schema.encodeUnknownEffect(makeErrorSchema(endpoint));\n  const decodeParams = UndefinedOr.map(endpoint.params, Schema.decodeUnknownEffect);\n  const decodeHeaders = UndefinedOr.map(endpoint.headers, Schema.decodeUnknownEffect);\n  const decodeQuery = UndefinedOr.map(endpoint.query, Schema.decodeUnknownEffect);\n  const encodeStream = makeStreamEncoder(endpoint);\n  const shouldParsePayload = endpoint.payload.size > 0 && !isRaw;\n  const payloadBy = shouldParsePayload ? buildPayloadDecoders(endpoint.payload) : undefined;\n  return applyMiddleware(group, endpoint, context, Effect.gen(function* () {\n    const fiber = Fiber.getCurrent();\n    const context = fiber.context;\n    const httpRequest = Context.getUnsafe(context, HttpServerRequest);\n    const routeContext = Context.getUnsafe(context, HttpRouter.RouteContext);\n    const query = Context.getUnsafe(context, Request.ParsedSearchParams);\n    const request = {\n      request: httpRequest,\n      endpoint,\n      group\n    };\n    if (decodeParams) {\n      request.params = yield* HttpApiSchemaError.wrap(\"Params\", decodeParams(routeContext.params));\n    }\n    if (decodeHeaders) {\n      request.headers = yield* HttpApiSchemaError.wrap(\"Headers\", decodeHeaders(httpRequest.headers));\n    }\n    if (decodeQuery) {\n      request.query = yield* HttpApiSchemaError.wrap(\"Query\", decodeQuery(query));\n    }\n    if (payloadBy) {\n      const result = decodePayload(payloadBy, httpRequest, query);\n      if (Response.isHttpServerResponse(result)) {\n        return result;\n      }\n      if (result !== undefined) {\n        request.payload = yield* HttpApiSchemaError.wrap(\"Payload\", result);\n      }\n    }\n    const response = yield* handler(request);\n    if (Response.isHttpServerResponse(response)) {\n      return response;\n    }\n    const streamResponse = encodeStream?.(response, context);\n    if (streamResponse !== undefined) {\n      return yield* HttpApiSchemaError.wrap(\"Body\", streamResponse);\n    }\n    return yield* HttpApiSchemaError.wrap(\"Body\", encodeSuccess(response));\n  })).pipe(Effect.withErrorReporting, Effect.catch(error => {\n    if (HttpApiSchemaError.is(error)) return Effect.die(error);\n    return Effect.orDie(encodeError(error));\n  }), Effect.provideContext(context));\n}\n/** @internal */\nexport function handlerToRoute(group, handler, context) {\n  const endpoint = handler.endpoint;\n  return HttpRouter.route(endpoint.method, endpoint.path, handlerToHttpEffect(group, endpoint, context, handler.handler, handler.isRaw), {\n    uninterruptible: handler.uninterruptible\n  });\n}\nconst applyMiddleware = (group, endpoint, context, handler) => {\n  const options = {\n    group,\n    endpoint\n  };\n  for (const key_ of endpoint.middlewares) {\n    const key = key_;\n    const service = Context.getUnsafe(context, key);\n    const apply = HttpApiMiddleware.isSecurity(key) ? makeSecurityMiddleware(key, service) : service;\n    handler = apply(handler, options);\n  }\n  return handler;\n};\nconst securityMiddlewareCache = /*#__PURE__*/new WeakMap();\nconst makeSecurityMiddleware = (key, service) => {\n  const cached = securityMiddlewareCache.get(service);\n  if (cached !== undefined) {\n    return cached;\n  }\n  const entries = Object.entries(key.security).map(([securityKey, security]) => ({\n    decode: securityDecode(security),\n    middleware: service[securityKey]\n  }));\n  if (entries.length === 0) {\n    return identity;\n  }\n  const middleware = Effect.fnUntraced(function* (handler, options) {\n    handler = Effect.mapError(handler, error => new HandlerError(error));\n    let lastResult;\n    for (let i = 0; i < entries.length; i++) {\n      const {\n        decode,\n        middleware\n      } = entries[i];\n      const result = yield* Effect.result(Effect.flatMap(decode, credential => middleware(handler, {\n        credential,\n        endpoint: options.endpoint,\n        group: options.group\n      })));\n      if (Result.isFailure(result)) {\n        if (isHandlerError(result.failure)) {\n          return yield* Effect.fail(result.failure.error);\n        }\n        lastResult = result;\n        continue;\n      }\n      return result.success;\n    }\n    return yield* Effect.fromResult(lastResult);\n  });\n  securityMiddlewareCache.set(service, middleware);\n  return middleware;\n};\nconst HandlerErrorTypeId = \"~effect/httpapi/HttpApiBuilder/HandlerError\";\nclass HandlerError {\n  [HandlerErrorTypeId] = HandlerErrorTypeId;\n  error;\n  constructor(error) {\n    this.error = error;\n  }\n}\nconst isHandlerError = value => hasProperty(value, HandlerErrorTypeId);\nconst $HttpServerResponse = /*#__PURE__*/Schema.declare(Response.isHttpServerResponse);\nfunction makeStreamEncoder(endpoint) {\n  const streamSchema = getStreamSuccessSchema(endpoint);\n  if (streamSchema === undefined) {\n    return undefined;\n  }\n  const hasBuffered = hasBufferedSuccess(endpoint);\n  const status = HttpApiSchema.getStatusStream(streamSchema);\n  const contentType = streamSchema.contentType;\n  if (HttpApiSchema.isStreamUint8Array(streamSchema)) {\n    return (response, context) => {\n      if (!Stream.isStream(response)) {\n        return hasBuffered ? undefined : new Schema.SchemaError(new SchemaIssue.InvalidValue({\n          message: \"Expected a streaming response\"\n        }));\n      }\n      return Effect.succeed(Response.stream(Stream.provideContext(response, context), {\n        status,\n        contentType\n      }));\n    };\n  }\n  const sseEncoder = makeSseEncoder(streamSchema);\n  return (response, context) => {\n    if (!Stream.isStream(response)) {\n      return hasBuffered ? undefined : new Schema.SchemaError(new SchemaIssue.InvalidValue({\n        message: \"Expected a streaming response\"\n      }));\n    }\n    return Effect.succeed(Response.stream(Stream.provideContext(encodeSseStream(response, sseEncoder), context), {\n      status,\n      contentType\n    }));\n  };\n}\nfunction getStreamSuccessSchema(endpoint) {\n  for (const schema of endpoint.success) {\n    if (HttpApiSchema.isStreamSchema(schema)) {\n      return schema;\n    }\n  }\n}\nfunction hasBufferedSuccess(endpoint) {\n  for (const schema of endpoint.success) {\n    if (Schema.isSchema(schema) && !HttpApiSchema.isStreamSchema(schema)) return true;\n  }\n  return endpoint.success.size === 0;\n}\nfunction makeSseEncoder(streamSchema) {\n  const CauseSchema = Schema.toCodecJson(Schema.Cause(streamSchema.error, Schema.Defect()));\n  return {\n    sseMode: streamSchema.sseMode,\n    encodeEvents: Schema.encodeUnknownEffect(Schema.Array(streamSchema.events)),\n    encodeCause: Schema.encodeUnknownEffect(Schema.fromJsonString(CauseSchema))\n  };\n}\nfunction encodeSseStream(stream, encoder) {\n  return stream.pipe(encoder.sseMode === \"data\" ? Stream.map(value => ({\n    id: undefined,\n    event: \"message\",\n    data: value\n  })) : identity, Stream.mapArrayEffect(chunk => Effect.orDie(encoder.encodeEvents(chunk))), Stream.catchCause(cause => Stream.fromEffect(encodeFailureEvent(cause, encoder))), Stream.map(renderSseEvent), Stream.encodeText);\n}\nfunction encodeFailureEvent(cause, encoder) {\n  return encoder.encodeCause(cause).pipe(Effect.orDie, Effect.map(encodedCause => ({\n    id: undefined,\n    event: reservedStreamFailureEvent,\n    data: encodedCause\n  })));\n}\nconst reservedStreamFailureEvent = \"effect/httpapi/stream/failure\";\nfunction renderSseEvent(event) {\n  return Sse.encoder.write({\n    _tag: \"Event\",\n    event: event.event,\n    id: event.id,\n    data: event.data\n  });\n}\nconst toResponseSuccessSchema = /*#__PURE__*/toResponseSchema(HttpApiSchema.getStatusSuccess);\nconst toResponseErrorSchema = /*#__PURE__*/toResponseSchema(HttpApiSchema.getStatusError);\nfunction makeSuccessSchema(endpoint) {\n  const schemas = HttpApiEndpoint.getSuccessSchemas(endpoint).map(toResponseSuccessSchema);\n  return schemas.length === 1 ? schemas[0] : Schema.Union(schemas);\n}\nfunction makeErrorSchema(endpoint) {\n  const schemas = HttpApiEndpoint.getErrorSchemas(endpoint).map(toResponseErrorSchema);\n  if (schemas.length === 0) return Schema.Never;\n  return schemas.length === 1 ? schemas[0] : Schema.Union(schemas);\n}\nfunction toResponseSchema(getStatus) {\n  const cache = new WeakMap();\n  return schema => {\n    const cached = cache.get(schema.ast);\n    if (cached !== undefined) {\n      return cached;\n    }\n    const responseSchema = $HttpServerResponse.pipe(Schema.decodeTo(schema, getResponseTransformation(getStatus, schema)));\n    cache.set(schema.ast, responseSchema);\n    return responseSchema;\n  };\n}\nfunction getResponseTransformation(getStatus, schema) {\n  const ast = schema.ast;\n  const encode = getResponseEncode(getStatus(ast), HttpApiSchema.getResponseEncoding(ast), HttpApiSchema.isNoContent(ast));\n  return SchemaTransformation.transformOrFail({\n    decode: () => Effect.fail(new SchemaIssue.Forbidden({\n      message: \"Encode only schema\"\n    })),\n    encode\n  });\n}\nfunction getResponseEncode(status, encoding, isNoContent) {\n  switch (encoding._tag) {\n    case \"Json\":\n      {\n        return e => {\n          if (e === undefined || isNoContent) {\n            return Effect.succeed(Response.empty({\n              status\n            }));\n          }\n          try {\n            const s = JSON.stringify(e);\n            return Effect.succeed(Response.text(s, {\n              status,\n              contentType: encoding.contentType\n            }));\n          } catch {\n            return Effect.fail(new SchemaIssue.InvalidValue({\n              message: \"Expected a JSON-serializable response body\"\n            }));\n          }\n        };\n      }\n    case \"Text\":\n      return e => Effect.succeed(Response.text(e, {\n        status,\n        contentType: encoding.contentType\n      }));\n    case \"Uint8Array\":\n      return e => Effect.succeed(Response.uint8Array(e, {\n        status,\n        contentType: encoding.contentType\n      }));\n    case \"FormUrlEncoded\":\n      return e => Effect.succeed(Response.urlParams(e, {\n        status\n      }).pipe(Response.setHeader(\"content-type\", encoding.contentType)));\n  }\n}\n//# sourceMappingURL=HttpApiBuilder.js.map","import * as Effect from \"effect/Effect\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\n\nexport interface SnapshotSubscription<A> {\n  readonly latest: A;\n  readonly changes: Stream.Stream<A>;\n}\n\nexport const subscribeBeforeSnapshot = Effect.fn(\"subscribeBeforeSnapshot\")(function* <A, E, R>(\n  changes: PubSub.PubSub<A>,\n  snapshot: Effect.Effect<A, E, R>,\n  mutex: Semaphore.Semaphore,\n) {\n  return yield* mutex.withPermits(1)(\n    Effect.gen(function* () {\n      const latest = yield* snapshot;\n      const subscription = yield* PubSub.subscribe(changes);\n      return {\n        latest,\n        changes: Stream.fromSubscription(subscription),\n      } satisfies SnapshotSubscription<A>;\n    }),\n  );\n});\n\nexport const subscribeBeforeSnapshotWithoutMutex = Effect.fn(\"subscribeBeforeSnapshotWithoutMutex\")(\n  function* <A, E, R>(changes: PubSub.PubSub<A>, snapshot: Effect.Effect<A, E, R>) {\n    const subscription = yield* PubSub.subscribe(changes);\n    const latest = yield* snapshot;\n    return {\n      latest,\n      changes: Stream.fromSubscription(subscription),\n    } satisfies SnapshotSubscription<A>;\n  },\n);\n","/**\n * Encodes and decodes newline-delimited JSON streams in Effect channels.\n *\n * NDJSON stores one complete JSON value on each line. This module has helpers\n * for byte streams, string streams, and schema-checked records, so streaming\n * code can read or write one JSON record at a time.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport * as Channel from \"../../Channel.js\";\nimport * as ChannelSchema from \"../../ChannelSchema.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { dual, identity } from \"../../Function.js\";\nconst NdjsonErrorTypeId = \"~effect/encoding/Ndjson/NdjsonError\";\nconst encoder = /*#__PURE__*/new TextEncoder();\n/**\n * Error raised when NDJSON encoding or decoding fails.\n *\n * **Details**\n *\n * The `kind` field identifies whether the failure happened while packing or\n * unpacking, and `cause` preserves the original error.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class NdjsonError extends /*#__PURE__*/Data.TaggedError(\"NdjsonError\") {\n  /**\n   * Marks this value as an NDJSON encoding or decoding error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [NdjsonErrorTypeId] = NdjsonErrorTypeId;\n  /**\n   * Uses the failed NDJSON operation as the public message.\n   *\n   * @since 4.0.0\n   */\n  get message() {\n    return this.kind;\n  }\n}\n/**\n * Creates a channel that encodes chunks of values as NDJSON strings.\n *\n * **Details**\n *\n * Each input item is `JSON.stringify`-encoded, separated by newlines, and the\n * output chunk ends with a trailing newline.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const encodeString = () => Channel.fromTransform((upstream, _scope) => Effect.succeed(Effect.flatMap(upstream, input => {\n  try {\n    return Effect.succeed(Arr.of(input.map(item => JSON.stringify(item)).join(\"\\n\") + \"\\n\"));\n  } catch (cause) {\n    return Effect.fail(new NdjsonError({\n      kind: \"Pack\",\n      cause\n    }));\n  }\n})));\n/**\n * Creates a channel that encodes chunks of values as UTF-8 NDJSON bytes.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const encode = () => Channel.map(encodeString(), Arr.map(_ => encoder.encode(_)));\n/**\n * Creates an NDJSON byte encoder channel for values of a schema.\n *\n * **Details**\n *\n * Values are first encoded with the schema and then written as UTF-8\n * newline-delimited JSON.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const encodeSchema = schema => () => Channel.pipeTo(ChannelSchema.encode(schema)(), encode());\n/**\n * Creates an NDJSON string encoder channel for values of a schema.\n *\n * **Details**\n *\n * Values are first encoded with the schema and then written as newline-delimited\n * JSON strings.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const encodeSchemaString = schema => () => Channel.pipeTo(ChannelSchema.encode(schema)(), encodeString());\n/**\n * Creates a channel that parses NDJSON string chunks into values.\n *\n * **When to use**\n *\n * Use when NDJSON input arrives as string chunks and each complete line should\n * be parsed into a JSON value.\n *\n * **Details**\n *\n * Lines may span input chunks.\n *\n * **Gotchas**\n *\n * Set `ignoreEmptyLines` to skip blank lines before calling `JSON.parse`;\n * otherwise blank lines are parsed and fail as invalid JSON.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const decodeString = options => {\n  const lines = Channel.splitLines().pipe(options?.ignoreEmptyLines === true ? Channel.filterArray(line => line.length > 0) : identity);\n  return Channel.mapEffect(lines, chunk => {\n    try {\n      return Effect.succeed(Arr.map(chunk, line => JSON.parse(line)));\n    } catch (cause) {\n      return Effect.fail(new NdjsonError({\n        kind: \"Unpack\",\n        cause\n      }));\n    }\n  });\n};\n/**\n * Creates a channel that decodes UTF-8 byte chunks and parses them as NDJSON.\n *\n * **Details**\n *\n * Lines may span input chunks, and `ignoreEmptyLines` controls whether blank\n * lines are skipped before JSON parsing.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const decode = options => {\n  return Channel.pipeTo(Channel.decodeText(), decodeString(options));\n};\n/**\n * Creates an NDJSON byte decoder channel for values of a schema.\n *\n * **Details**\n *\n * The channel decodes UTF-8 bytes, parses each NDJSON line, and then decodes\n * each parsed value with the schema.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const decodeSchema = schema => options => Channel.pipeTo(decode(options), ChannelSchema.decodeUnknown(schema)());\n/**\n * Creates an NDJSON string decoder channel for values of a schema.\n *\n * **Details**\n *\n * The channel parses each line as JSON and then decodes each parsed value with\n * the schema.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const decodeSchemaString = schema => options => Channel.pipeTo(decodeString(options), ChannelSchema.decodeUnknown(schema)());\n/**\n * Wraps a bidirectional byte channel with NDJSON encoding and decoding.\n *\n * **Details**\n *\n * Outgoing values are written as UTF-8 NDJSON bytes, and incoming bytes are\n * parsed as NDJSON values.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const duplex = /*#__PURE__*/dual(args => Channel.isChannel(args[0]), (self, options) => Channel.pipeTo(Channel.pipeTo(encode(), self), decode(options)));\n/**\n * Wraps a bidirectional string channel with NDJSON encoding and decoding.\n *\n * **Details**\n *\n * Outgoing values are written as NDJSON strings, and incoming strings are parsed\n * as NDJSON values.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const duplexString = /*#__PURE__*/dual(args => Channel.isChannel(args[0]), (self, options) => Channel.pipeTo(Channel.pipeTo(encodeString(), self), decodeString(options)));\n/**\n * Wraps a bidirectional byte channel with schema-aware NDJSON encoding and\n * decoding.\n *\n * **Details**\n *\n * Values sent to the wrapped channel are encoded with `inputSchema`; bytes\n * received from it are parsed as NDJSON and decoded with `outputSchema`.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const duplexSchema = /*#__PURE__*/dual(2, (self, options) => ChannelSchema.duplexUnknown(duplex(self, options), options));\n/**\n * Wraps a bidirectional string channel with schema-aware NDJSON encoding and\n * decoding.\n *\n * **Details**\n *\n * Values sent to the wrapped channel are encoded with `inputSchema`; strings\n * received from it are parsed as NDJSON and decoded with `outputSchema`.\n *\n * @category combinators\n * @since 4.0.0\n */\nexport const duplexSchemaString = /*#__PURE__*/dual(2, (self, options) => ChannelSchema.duplexUnknown(duplexString(self, options), options));\n//# sourceMappingURL=Ndjson.js.map","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\n\nimport * as NodeStream from \"@effect/platform-node/NodeStream\";\nimport {\n  DesktopHostTelemetryMessage,\n  type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,\n  type DesktopHostTelemetrySnapshot,\n  DesktopTelemetryControlMessage,\n  type ResourceTelemetrySourceStatus,\n} from \"@t3tools/contracts\";\nimport { resolveServerBackgroundActivitySettings } from \"@t3tools/shared/backgroundActivitySettings\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Ndjson from \"effect/unstable/encoding/Ndjson\";\n\nimport { ServerConfig } from \"../config.ts\";\nimport { ServerSettingsService } from \"../serverSettings.ts\";\nimport { subscribeBeforeSnapshotWithoutMutex } from \"../utils/subscribeBeforeSnapshot.ts\";\n\nconst INITIAL_SAMPLE_DEADLINE_MS = 90_000;\nconst MIN_SNAPSHOT_STALE_AFTER_MS = 90_000;\nconst STALE_GRACE_MS = 30_000;\nconst DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS = 30_000;\nconst DEFAULT_HOST_POWER_IDLE_INTERVAL_MS = 120_000;\nconst STALE_CHECK_INTERVAL = Duration.seconds(30);\n\nexport class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedErrorClass<DesktopTelemetryDescriptorUnavailable>()(\n  \"DesktopTelemetryDescriptorUnavailable\",\n  {\n    mode: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry descriptor is unavailable in '${this.mode}' mode.`;\n  }\n}\n\nexport class DesktopTelemetryProtocolMismatch extends Schema.TaggedErrorClass<DesktopTelemetryProtocolMismatch>()(\n  \"DesktopTelemetryProtocolMismatch\",\n  {\n    expectedVersion: Schema.Number,\n    receivedVersion: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;\n  }\n}\n\nexport class DesktopTelemetryDecodeFailed extends Schema.TaggedErrorClass<DesktopTelemetryDecodeFailed>()(\n  \"DesktopTelemetryDecodeFailed\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to decode desktop telemetry.\";\n  }\n}\n\nexport class DesktopTelemetryStreamFailed extends Schema.TaggedErrorClass<DesktopTelemetryStreamFailed>()(\n  \"DesktopTelemetryStreamFailed\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry stream on fd ${this.fd} failed.`;\n  }\n}\n\nexport class DesktopTelemetryStreamClosed extends Schema.TaggedErrorClass<DesktopTelemetryStreamClosed>()(\n  \"DesktopTelemetryStreamClosed\",\n  {\n    fd: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry stream on fd ${this.fd} closed.`;\n  }\n}\n\nexport class DesktopTelemetryStale extends Schema.TaggedErrorClass<DesktopTelemetryStale>()(\n  \"DesktopTelemetryStale\",\n  {\n    fd: Schema.Number,\n    staleAfterMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`;\n  }\n}\n\nexport type DesktopTelemetryReceiverError =\n  | DesktopTelemetryDescriptorUnavailable\n  | DesktopTelemetryProtocolMismatch\n  | DesktopTelemetryDecodeFailed\n  | DesktopTelemetryStreamFailed\n  | DesktopTelemetryStreamClosed;\n\nexport class DesktopTelemetryControlFailed extends Schema.TaggedErrorClass<DesktopTelemetryControlFailed>()(\n  \"DesktopTelemetryControlFailed\",\n  {\n    fd: Schema.Number,\n    operation: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`;\n  }\n}\n\nexport class DesktopTelemetryControlStalled extends Schema.TaggedErrorClass<DesktopTelemetryControlStalled>()(\n  \"DesktopTelemetryControlStalled\",\n  {\n    fd: Schema.Number,\n    remainingBytes: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry control stalled on fd ${this.fd} with ${this.remainingBytes} bytes remaining.`;\n  }\n}\n\nexport type DesktopTelemetryControlError =\n  | DesktopTelemetryControlFailed\n  | DesktopTelemetryControlStalled;\n\nexport interface DesktopTelemetryReceiverHealth {\n  readonly status: ResourceTelemetrySourceStatus;\n  readonly lastSampleAt: Option.Option<DateTime.Utc>;\n  readonly lastError: Option.Option<string>;\n}\n\nexport class DesktopTelemetryReceiver extends Context.Service<\n  DesktopTelemetryReceiver,\n  {\n    readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;\n    readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;\n    readonly subscribe: Effect.Effect<\n      {\n        readonly latest: Option.Option<DesktopHostTelemetrySnapshot>;\n        readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>;\n    readonly subscribeHealth: Effect.Effect<\n      {\n        readonly latest: DesktopTelemetryReceiverHealth;\n        readonly changes: Stream.Stream<DesktopTelemetryReceiverHealth>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly setDiagnosticsDemand: (\n      enabled: boolean,\n    ) => Effect.Effect<void, DesktopTelemetryControlError>;\n  }\n>()(\"t3/resourceTelemetry/DesktopTelemetryReceiver\") {}\n\nconst decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);\nconst encodeControlMessage = Schema.encodeEffect(\n  Schema.fromJsonString(DesktopTelemetryControlMessage),\n);\nconst isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable);\nconst isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch);\nconst isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed);\nconst isStreamFailed = Schema.is(DesktopTelemetryStreamFailed);\n\nexport function isDesktopTelemetryContactStale(\n  lastContactAtMs: Option.Option<number>,\n  nowMs: number,\n): boolean {\n  return Option.exists(\n    lastContactAtMs,\n    (lastContact) => nowMs - lastContact >= INITIAL_SAMPLE_DEADLINE_MS,\n  );\n}\n\nexport function resolveDesktopTelemetrySnapshotStaleAfterMs(\n  activeIntervalMs: number,\n  idleIntervalMs: number,\n): number {\n  return Math.max(\n    MIN_SNAPSHOT_STALE_AFTER_MS,\n    Math.max(activeIntervalMs, idleIntervalMs) + STALE_GRACE_MS,\n  );\n}\n\nexport function initialDesktopTelemetryContactAt(\n  desktopTelemetryFd: number | undefined,\n  nowMs: number,\n): Option.Option<number> {\n  return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs);\n}\n\nexport const recordDesktopTelemetrySampleHealth = Effect.fn(\n  \"resourceTelemetry.desktopTelemetryReceiver.recordSampleHealth\",\n)(function* (\n  health: Ref.Ref<DesktopTelemetryReceiverHealth>,\n  healthChanges: PubSub.PubSub<DesktopTelemetryReceiverHealth>,\n  sampledAt: DateTime.Utc,\n) {\n  const next: DesktopTelemetryReceiverHealth = {\n    status: \"healthy\",\n    lastSampleAt: Option.some(sampledAt),\n    lastError: Option.none(),\n  };\n  yield* Ref.set(health, next);\n  yield* PubSub.publish(healthChanges, next);\n});\n\nfunction normalizeReceiverError(error: unknown): DesktopTelemetryReceiverError {\n  if (\n    isDescriptorUnavailable(error) ||\n    isProtocolMismatch(error) ||\n    isDecodeFailed(error) ||\n    isStreamFailed(error)\n  ) {\n    return error;\n  }\n  return new DesktopTelemetryDecodeFailed({ cause: error });\n}\n\nfunction messageVersion(value: unknown): number | undefined {\n  if (typeof value !== \"object\" || value === null) return undefined;\n  const version = Reflect.get(value, \"version\");\n  return typeof version === \"number\" ? version : undefined;\n}\n\nexport const writeAllToFileDescriptor = Effect.fn(\n  \"resourceTelemetry.desktopTelemetryReceiver.writeAllToFileDescriptor\",\n)(function* (fd: number, payload: Buffer) {\n  let offset = 0;\n  while (offset < payload.byteLength) {\n    const written = yield* Effect.callback<number, DesktopTelemetryControlFailed>(\n      (resume, signal) => {\n        if (signal.aborted) return;\n        try {\n          NodeFS.write(\n            fd,\n            payload,\n            offset,\n            payload.byteLength - offset,\n            null,\n            (error, bytesWritten) => {\n              if (error) {\n                resume(\n                  Effect.fail(\n                    new DesktopTelemetryControlFailed({\n                      fd,\n                      operation: \"write\",\n                      cause: error,\n                    }),\n                  ),\n                );\n                return;\n              }\n              resume(Effect.succeed(bytesWritten));\n            },\n          );\n        } catch (cause) {\n          resume(\n            Effect.fail(\n              new DesktopTelemetryControlFailed({\n                fd,\n                operation: \"write\",\n                cause,\n              }),\n            ),\n          );\n        }\n      },\n    );\n    yield* requireDesktopTelemetryWriteProgress(fd, payload.byteLength - offset, written);\n    offset += written;\n  }\n});\n\nexport function requireDesktopTelemetryWriteProgress(\n  fd: number,\n  remainingBytes: number,\n  written: number,\n): Effect.Effect<void, DesktopTelemetryControlStalled> {\n  return written > 0\n    ? Effect.void\n    : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes }));\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.desktopTelemetryReceiver.make\")(function* () {\n  const config = yield* ServerConfig;\n  const serverSettings = yield* ServerSettingsService;\n  const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());\n  const receiverStartedAt = yield* DateTime.now;\n  const lastContactAtMs = yield* Ref.make(\n    initialDesktopTelemetryContactAt(\n      config.desktopTelemetryFd,\n      DateTime.toEpochMillis(receiverStartedAt),\n    ),\n  );\n  const snapshotStaleAfterMs = yield* Ref.make(\n    resolveDesktopTelemetrySnapshotStaleAfterMs(\n      DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS,\n      DEFAULT_HOST_POWER_IDLE_INTERVAL_MS,\n    ),\n  );\n  const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);\n  const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);\n  const controlMutex = yield* Semaphore.make(1);\n  const snapshotMutex = yield* Semaphore.make(1);\n  const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({\n    status: config.desktopTelemetryFd === undefined ? \"unavailable\" : \"starting\",\n    lastSampleAt: Option.none(),\n    lastError:\n      config.desktopTelemetryFd === undefined\n        ? Option.some(\n            new DesktopTelemetryDescriptorUnavailable({\n              mode: config.mode,\n            }).message,\n          )\n        : Option.none(),\n  });\n  const updateHealth = (\n    update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth,\n  ) =>\n    Ref.modify(health, (current) => {\n      const next = update(current);\n      return [next, next];\n    }).pipe(\n      Effect.flatMap((next) => PubSub.publish(healthChanges, next)),\n      Effect.asVoid,\n    );\n  const updateSampleHealth = (sampledAt: DateTime.Utc) =>\n    recordDesktopTelemetrySampleHealth(health, healthChanges, sampledAt);\n\n  const sendControlMessage = (message: DesktopTelemetryControlMessage) =>\n    controlMutex.withPermits(1)(\n      Effect.gen(function* () {\n        const fd = config.desktopTelemetryControlFd;\n        if (fd === undefined) return;\n        const encoded = yield* encodeControlMessage(message).pipe(\n          Effect.mapError(\n            (cause) =>\n              new DesktopTelemetryControlFailed({\n                fd,\n                operation: \"encode\",\n                cause,\n              }),\n          ),\n        );\n        yield* writeAllToFileDescriptor(fd, Buffer.from(`${encoded}\\n`)).pipe(\n          Effect.tapError((error) =>\n            updateHealth((current) => ({\n              ...current,\n              status: \"degraded\",\n              lastError: Option.some(error.message),\n            })),\n          ),\n        );\n      }),\n    );\n  const setDiagnosticsDemand: DesktopTelemetryReceiver[\"Service\"][\"setDiagnosticsDemand\"] = (\n    enabled,\n  ) =>\n    sendControlMessage({\n      version: 1,\n      type: \"setDiagnosticsDemand\",\n      enabled,\n    });\n\n  const sendHostPowerIntervals = (\n    settings: Parameters<typeof resolveServerBackgroundActivitySettings>[0],\n  ) => {\n    const resolved = resolveServerBackgroundActivitySettings(settings);\n    const activeIntervalMs = Math.max(\n      1,\n      Math.round(Duration.toMillis(resolved.hostPowerMonitorActiveInterval)),\n    );\n    const idleIntervalMs = Math.max(\n      1,\n      Math.round(Duration.toMillis(resolved.hostPowerMonitorIdleInterval)),\n    );\n    return sendControlMessage({\n      version: 1,\n      type: \"setHostPowerIntervals\",\n      activeIntervalMs,\n      idleIntervalMs,\n    }).pipe(\n      Effect.andThen(\n        Ref.set(\n          snapshotStaleAfterMs,\n          resolveDesktopTelemetrySnapshotStaleAfterMs(activeIntervalMs, idleIntervalMs),\n        ),\n      ),\n    );\n  };\n  if (config.desktopTelemetryControlFd !== undefined) {\n    const settingsChanges = yield* serverSettings.subscribeChanges;\n    const settings = yield* serverSettings.getSettings;\n    yield* sendHostPowerIntervals(settings).pipe(\n      Effect.catchCause((cause) =>\n        Effect.logWarning(\"Failed to configure desktop host-power intervals\", {\n          cause: String(cause),\n        }),\n      ),\n    );\n    yield* settingsChanges.pipe(\n      Stream.runForEach((settings) =>\n        sendHostPowerIntervals(settings).pipe(\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"Failed to update desktop host-power intervals\", {\n              cause: String(cause),\n            }),\n          ),\n        ),\n      ),\n      Effect.forkScoped,\n    );\n  }\n\n  if (config.desktopTelemetryFd !== undefined) {\n    const fd = config.desktopTelemetryFd;\n    const readable = yield* Effect.acquireRelease(\n      Effect.try({\n        try: () =>\n          NodeFS.createReadStream(\"\", {\n            fd,\n            autoClose: true,\n          }),\n        catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),\n      }),\n      (stream) =>\n        Effect.sync(() => {\n          stream.destroy();\n        }),\n    );\n\n    const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> =\n      NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({\n        evaluate: () => readable,\n        closeOnDone: true,\n        onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),\n      }).pipe(\n        Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),\n        Stream.mapEffect(\n          (\n            value,\n          ): Effect.Effect<\n            DesktopHostTelemetryMessageValue,\n            DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed\n          > => {\n            const version = messageVersion(value);\n            if (version !== undefined && version !== 1) {\n              return Effect.fail(\n                new DesktopTelemetryProtocolMismatch({\n                  expectedVersion: 1,\n                  receivedVersion: version,\n                }),\n              );\n            }\n            return decodeMessage(value).pipe(\n              Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),\n            );\n          },\n        ),\n        Stream.mapError(normalizeReceiverError),\n      );\n\n    yield* messages.pipe(\n      Stream.runForEach((message) => {\n        const recordContact = DateTime.now.pipe(\n          Effect.flatMap((now) =>\n            Ref.set(lastContactAtMs, Option.some(DateTime.toEpochMillis(now))),\n          ),\n        );\n        if (message.type === \"desktopTelemetryHello\") {\n          return recordContact.pipe(\n            Effect.andThen(\n              updateHealth(\n                (current): DesktopTelemetryReceiverHealth => ({\n                  ...current,\n                  status: \"healthy\",\n                  lastError: Option.none(),\n                }),\n              ),\n            ),\n          );\n        }\n\n        const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);\n        return snapshotMutex.withPermits(1)(\n          recordContact.pipe(\n            Effect.andThen(Ref.set(latest, Option.some(message))),\n            Effect.andThen(updateSampleHealth(sampledAt)),\n            Effect.andThen(PubSub.publish(changes, message)),\n            Effect.asVoid,\n          ),\n        );\n      }),\n      Effect.andThen(\n        updateHealth(\n          (current): DesktopTelemetryReceiverHealth => ({\n            ...current,\n            status: \"stopped\",\n            lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),\n          }),\n        ),\n      ),\n      Effect.catch((error) =>\n        updateHealth(\n          (current): DesktopTelemetryReceiverHealth => ({\n            ...current,\n            status: \"degraded\",\n            lastError: Option.some(error.message),\n          }),\n        ),\n      ),\n      Effect.forkScoped,\n    );\n\n    yield* Effect.forever(\n      Effect.sleep(STALE_CHECK_INTERVAL).pipe(\n        Effect.andThen(\n          snapshotMutex.withPermits(1)(\n            Effect.gen(function* () {\n              const now = yield* DateTime.now;\n              const nowMs = DateTime.toEpochMillis(now);\n              const staleAfterMs = yield* Ref.get(snapshotStaleAfterMs);\n              const staleSnapshot = yield* Ref.modify(latest, (current) => {\n                if (\n                  Option.isNone(current) ||\n                  current.value.power.stale ||\n                  nowMs - current.value.sampledAtUnixMs < staleAfterMs\n                ) {\n                  return [Option.none<DesktopHostTelemetrySnapshot>(), current] as const;\n                }\n                const stale: DesktopHostTelemetrySnapshot = {\n                  ...current.value,\n                  power: { ...current.value.power, stale: true },\n                };\n                return [Option.some(stale), Option.some(stale)] as const;\n              });\n              if (Option.isNone(staleSnapshot)) {\n                const lastContact = yield* Ref.get(lastContactAtMs);\n                if (!isDesktopTelemetryContactStale(lastContact, nowMs)) return;\n                const staleMessage = new DesktopTelemetryStale({\n                  fd,\n                  staleAfterMs: INITIAL_SAMPLE_DEADLINE_MS,\n                }).message;\n                const changed = yield* Ref.modify(health, (current) => {\n                  if (\n                    current.status === \"stopped\" ||\n                    Option.isSome(current.lastSampleAt) ||\n                    (current.status === \"degraded\" &&\n                      Option.contains(current.lastError, staleMessage))\n                  ) {\n                    return [Option.none<DesktopTelemetryReceiverHealth>(), current] as const;\n                  }\n                  const next: DesktopTelemetryReceiverHealth = {\n                    ...current,\n                    status: \"degraded\",\n                    lastError: Option.some(staleMessage),\n                  };\n                  return [Option.some(next), next] as const;\n                });\n                if (Option.isSome(changed)) {\n                  yield* PubSub.publish(healthChanges, changed.value);\n                }\n                return;\n              }\n              yield* updateHealth((currentHealth) => ({\n                ...currentHealth,\n                status: currentHealth.status === \"stopped\" ? \"stopped\" : \"degraded\",\n                lastError:\n                  currentHealth.status === \"stopped\"\n                    ? currentHealth.lastError\n                    : Option.some(new DesktopTelemetryStale({ fd, staleAfterMs }).message),\n              }));\n              yield* PubSub.publish(changes, staleSnapshot.value);\n            }),\n          ),\n        ),\n      ),\n    ).pipe(Effect.forkScoped);\n  }\n\n  return DesktopTelemetryReceiver.of({\n    latest: Ref.get(latest),\n    changes: Stream.fromPubSub(changes),\n    subscribe: snapshotMutex.withPermits(1)(\n      Effect.gen(function* () {\n        const initial = yield* Ref.get(latest);\n        const subscription = yield* PubSub.subscribe(changes);\n        return {\n          latest: initial,\n          changes: Stream.fromSubscription(subscription),\n        };\n      }),\n    ),\n    health: Ref.get(health),\n    subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),\n    setDiagnosticsDemand,\n  });\n});\n\nexport const layer = Layer.effect(DesktopTelemetryReceiver, make());\n\nexport const layerTest = (\n  overrides: Partial<DesktopTelemetryReceiver[\"Service\"]> = {},\n): Layer.Layer<DesktopTelemetryReceiver> => {\n  const latest = overrides.latest ?? Effect.succeedNone;\n  const changes = overrides.changes ?? Stream.empty;\n  const health =\n    overrides.health ??\n    Effect.succeed({\n      status: \"unavailable\" as const,\n      lastSampleAt: Option.none<DateTime.Utc>(),\n      lastError: Option.some(\"Desktop telemetry test implementation is unavailable.\"),\n    });\n  return Layer.succeed(\n    DesktopTelemetryReceiver,\n    DesktopTelemetryReceiver.of({\n      latest,\n      changes,\n      subscribe:\n        overrides.subscribe ??\n        latest.pipe(\n          Effect.map((initial) => ({\n            latest: initial,\n            changes,\n          })),\n        ),\n      health,\n      subscribeHealth:\n        overrides.subscribeHealth ??\n        health.pipe(\n          Effect.map((initial) => ({\n            latest: initial,\n            changes: Stream.empty,\n          })),\n        ),\n      setDiagnosticsDemand: () => Effect.void,\n      ...overrides,\n    }),\n  );\n};\n","import type { HostPowerSnapshot } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as DesktopTelemetryReceiver from \"../resourceTelemetry/DesktopTelemetryReceiver.ts\";\n\nexport class HostPowerMonitor extends Context.Service<\n  HostPowerMonitor,\n  {\n    readonly snapshot: Effect.Effect<HostPowerSnapshot>;\n    readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;\n    readonly streamChanges: Stream.Stream<HostPowerSnapshot>;\n  }\n>()(\"t3/background/HostPowerMonitor\") {}\n\nexport const makeUnknownSnapshot = (\n  source: HostPowerSnapshot[\"source\"],\n  updatedAt: HostPowerSnapshot[\"updatedAt\"],\n): HostPowerSnapshot => ({\n  source,\n  idle: \"unknown\",\n  idleSeconds: null,\n  locked: \"unknown\",\n  suspended: false,\n  onBattery: \"unknown\",\n  lowPowerMode: \"unknown\",\n  thermalState: \"unknown\",\n  stale: true,\n  updatedAt,\n});\n\nfunction samePowerState(left: HostPowerSnapshot, right: HostPowerSnapshot): boolean {\n  return (\n    left.source === right.source &&\n    left.idle === right.idle &&\n    left.locked === right.locked &&\n    left.suspended === right.suspended &&\n    left.onBattery === right.onBattery &&\n    left.lowPowerMode === right.lowPowerMode &&\n    left.thermalState === right.thermalState &&\n    left.stale === right.stale\n  );\n}\n\nexport const make = Effect.fn(\"background.hostPower.make\")(function* (\n  initialSnapshot?: HostPowerSnapshot,\n) {\n  const initial = initialSnapshot ?? makeUnknownSnapshot(\"unknown\", yield* DateTime.now);\n  const latestRef = yield* Ref.make(initial);\n  const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);\n\n  const report: HostPowerMonitor[\"Service\"][\"report\"] = (snapshot) =>\n    Ref.modify(latestRef, (current) => {\n      if (DateTime.isLessThan(snapshot.updatedAt, current.updatedAt)) {\n        return [Option.none<HostPowerSnapshot>(), current] as const;\n      }\n      return [\n        samePowerState(current, snapshot) ? Option.none() : Option.some(snapshot),\n        snapshot,\n      ] as const;\n    }).pipe(\n      Effect.flatMap(\n        Option.match({\n          onNone: () => Effect.void,\n          onSome: (next) => PubSub.publish(changes, next),\n        }),\n      ),\n      Effect.asVoid,\n    );\n\n  return HostPowerMonitor.of({\n    snapshot: Ref.get(latestRef),\n    report,\n    streamChanges: Stream.fromPubSub(changes),\n  });\n});\n\nexport const layer = Layer.effect(\n  HostPowerMonitor,\n  Effect.gen(function* () {\n    const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;\n    const desktopSubscription = yield* desktopTelemetry.subscribe;\n    const initial = desktopSubscription.latest;\n    const monitor = yield* Option.match(initial, {\n      onNone: () => make(),\n      onSome: (snapshot) => make(snapshot.power),\n    });\n    yield* desktopSubscription.changes.pipe(\n      Stream.map((snapshot) => snapshot.power),\n      Stream.runForEach(monitor.report),\n      Effect.forkScoped,\n    );\n    return monitor;\n  }),\n);\n","import {\n  type AuthSessionId,\n  type BackgroundPolicySnapshot,\n  type BackgroundScope,\n  type ClientActivityLease,\n  type ClientActivityReportInput,\n  type HostPowerSnapshot,\n  type RpcClientId,\n} from \"@t3tools/contracts\";\nimport {\n  getBackgroundActivityPresetSettings,\n  resolveServerBackgroundActivitySettings,\n  type ResolvedBackgroundActivitySettings,\n} from \"@t3tools/shared/backgroundActivitySettings\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\n\nimport { ServerSettingsService } from \"../serverSettings.ts\";\nimport { subscribeBeforeSnapshot } from \"../utils/subscribeBeforeSnapshot.ts\";\nimport * as HostPowerMonitor from \"./HostPowerMonitor.ts\";\n\nexport class BackgroundPolicy extends Context.Service<\n  BackgroundPolicy,\n  {\n    readonly reportClientActivity: (\n      sessionId: AuthSessionId,\n      rpcClientId: RpcClientId,\n      input: ClientActivityReportInput,\n    ) => Effect.Effect<void>;\n    readonly removeRpcClient: (\n      sessionId: AuthSessionId,\n      rpcClientId: RpcClientId,\n    ) => Effect.Effect<void>;\n    readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;\n    readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;\n    readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;\n    readonly subscribe: Effect.Effect<\n      {\n        readonly latest: BackgroundPolicySnapshot;\n        readonly changes: Stream.Stream<BackgroundPolicySnapshot>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;\n    readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;\n    readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;\n  }\n>()(\"t3/background/BackgroundPolicy\") {}\n\nconst DEFAULT_LEASE_TTL_MS = 45_000;\nconst MAX_LEASE_TTL_MS = 120_000;\nexport const MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT = 16;\n\nfunction scopeKey(scope: BackgroundScope): string {\n  switch (scope.type) {\n    case \"server-config\":\n    case \"diagnostics\":\n      return scope.type;\n    case \"provider-status\":\n      return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;\n    case \"vcs-status\":\n    case \"git-refs\":\n      return `${scope.type}:${scope.cwd}`;\n    case \"thread\":\n      return `${scope.type}:${scope.threadId}`;\n  }\n}\n\nfunction isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {\n  return DateTime.isGreaterThan(lease.expiresAt, now);\n}\n\nfunction leaseKey(lease: Pick<ClientActivityLease, \"sessionId\" | \"rpcClientId\" | \"clientId\">) {\n  return JSON.stringify([lease.sessionId, lease.rpcClientId, lease.clientId]);\n}\n\nexport function upsertClientActivityLease(\n  leases: ReadonlyMap<string, ClientActivityLease>,\n  lease: ClientActivityLease,\n  now: DateTime.Utc,\n): Map<string, ClientActivityLease> {\n  const next = new Map(leases);\n  for (const [key, current] of next) {\n    if (!isLeaseActive(current, now)) {\n      next.delete(key);\n    }\n  }\n\n  const key = leaseKey(lease);\n  if (!next.has(key)) {\n    let connectionLeaseCount = 0;\n    let oldestConnectionLease:\n      | {\n          readonly key: string;\n          readonly updatedAtMs: number;\n        }\n      | undefined;\n    for (const [currentKey, current] of next) {\n      if (current.sessionId !== lease.sessionId || current.rpcClientId !== lease.rpcClientId) {\n        continue;\n      }\n      connectionLeaseCount += 1;\n      const updatedAtMs = DateTime.toEpochMillis(current.updatedAt);\n      if (oldestConnectionLease === undefined || updatedAtMs < oldestConnectionLease.updatedAtMs) {\n        oldestConnectionLease = { key: currentKey, updatedAtMs };\n      }\n    }\n    if (\n      connectionLeaseCount >= MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT &&\n      oldestConnectionLease !== undefined\n    ) {\n      next.delete(oldestConnectionLease.key);\n    }\n  }\n\n  next.set(key, lease);\n  return next;\n}\n\nfunction isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {\n  return isLeaseActive(lease, now) && lease.visible && (lease.focused || lease.recentlyInteracted);\n}\n\nfunction leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {\n  const key = scopeKey(scope);\n  return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);\n}\n\nfunction hasThermalPressure(hostPower: HostPowerSnapshot): boolean {\n  return hostPower.thermalState === \"serious\" || hostPower.thermalState === \"critical\";\n}\n\nfunction isHostConstrained(\n  hostPower: HostPowerSnapshot,\n  settings: ResolvedBackgroundActivitySettings,\n): boolean {\n  if (hostPower.stale) return false;\n  if (\n    hostPower.suspended ||\n    (settings.pauseWhenHostLocked && hostPower.locked === \"true\") ||\n    hasThermalPressure(hostPower)\n  ) {\n    return true;\n  }\n  if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === \"true\") return true;\n  return settings.pauseWhenOnBattery && hostPower.onBattery === \"true\";\n}\n\nfunction isClientConstrained(\n  lease: ClientActivityLease,\n  settings: ResolvedBackgroundActivitySettings,\n): boolean {\n  if (settings.pauseWhenClientLowPower && lease.lowPowerMode === \"true\") return true;\n  return settings.pauseWhenOnBattery && lease.batteryState === \"unplugged\";\n}\n\nfunction leaseMayRunScopedWork(\n  lease: ClientActivityLease,\n  scope: BackgroundScope,\n  now: DateTime.Utc,\n  settings: ResolvedBackgroundActivitySettings,\n): boolean {\n  const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);\n  if (!activeWithScope || isClientConstrained(lease, settings)) {\n    return false;\n  }\n  if (settings.profile === \"performance\") {\n    return true;\n  }\n  return isForegroundLease(lease, now);\n}\n\nfunction computeSnapshot(input: {\n  readonly hostPower: HostPowerSnapshot;\n  readonly leases: ReadonlyMap<string, ClientActivityLease>;\n  readonly now: DateTime.Utc;\n  readonly settings: ResolvedBackgroundActivitySettings;\n  readonly updatedAt: DateTime.Utc;\n}): BackgroundPolicySnapshot {\n  const activeLeases = [...input.leases.values()].filter((lease) =>\n    isLeaseActive(lease, input.now),\n  );\n  const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));\n  const activeScopeKeys = new Set<string>();\n  for (const lease of activeLeases) {\n    for (const scope of lease.scopes) {\n      activeScopeKeys.add(scopeKey(scope));\n    }\n  }\n\n  return {\n    hostPower: input.hostPower,\n    leases: activeLeases,\n    activeForegroundLeaseCount: foregroundLeases.length,\n    activeScopeKeys: [...activeScopeKeys].toSorted(),\n    shouldRunOpportunisticWork:\n      foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&\n      !isHostConstrained(input.hostPower, input.settings),\n    updatedAt: input.updatedAt,\n  };\n}\n\nexport const make = Effect.fn(\"background.policy.make\")(function* () {\n  const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;\n  const serverSettings = yield* ServerSettingsService;\n  const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());\n  const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);\n  const publishMutex = yield* Semaphore.make(1);\n\n  const backgroundActivitySettings = serverSettings.getSettings.pipe(\n    Effect.map(resolveServerBackgroundActivitySettings),\n    Effect.orElseSucceed(() => getBackgroundActivityPresetSettings(\"balanced\")),\n  );\n\n  const snapshot = Effect.gen(function* () {\n    const [hostPower, leases, now, settings] = yield* Effect.all([\n      hostPowerMonitor.snapshot,\n      Ref.get(leasesRef),\n      DateTime.now,\n      backgroundActivitySettings,\n    ]);\n    return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });\n  });\n\n  const publishSnapshotUnlocked = snapshot.pipe(\n    Effect.flatMap((next) => PubSub.publish(changes, next)),\n  );\n  const publishSnapshot = publishMutex.withPermits(1)(publishSnapshotUnlocked);\n\n  const reportClientActivity: BackgroundPolicy[\"Service\"][\"reportClientActivity\"] = (\n    sessionId,\n    rpcClientId,\n    input,\n  ) =>\n    publishMutex.withPermits(1)(\n      Effect.gen(function* () {\n        const ttlMs = Math.min(\n          Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),\n          MAX_LEASE_TTL_MS,\n        );\n        const now = yield* DateTime.now;\n        const expiresAt = DateTime.add(now, { milliseconds: ttlMs });\n        const lease: ClientActivityLease = {\n          sessionId,\n          rpcClientId,\n          clientId: input.clientId,\n          clientKind: input.clientKind,\n          visible: input.visible,\n          focused: input.focused,\n          recentlyInteracted: input.recentlyInteracted,\n          ...(input.appState !== undefined ? { appState: input.appState } : {}),\n          ...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),\n          ...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),\n          ...(input.networkType !== undefined ? { networkType: input.networkType } : {}),\n          scopes: input.scopes,\n          updatedAt: now,\n          expiresAt,\n        };\n        yield* Ref.update(leasesRef, (leases) => upsertClientActivityLease(leases, lease, now));\n        yield* publishSnapshotUnlocked;\n      }),\n    );\n\n  const removeRpcClient: BackgroundPolicy[\"Service\"][\"removeRpcClient\"] = (\n    sessionId,\n    rpcClientId,\n  ) =>\n    publishMutex.withPermits(1)(\n      Ref.update(leasesRef, (leases) => {\n        const next = new Map(leases);\n        for (const [key, lease] of next) {\n          if (lease.sessionId === sessionId && lease.rpcClientId === rpcClientId) {\n            next.delete(key);\n          }\n        }\n        return next;\n      }).pipe(Effect.andThen(publishSnapshotUnlocked), Effect.asVoid),\n    );\n\n  const hasDemand: BackgroundPolicy[\"Service\"][\"hasDemand\"] = (scope) =>\n    Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));\n\n  const shouldRunScopeWork: BackgroundPolicy[\"Service\"][\"shouldRunScopeWork\"] = (scope) =>\n    Effect.gen(function* () {\n      const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);\n      if (isHostConstrained(current.hostPower, settings)) {\n        return false;\n      }\n      return current.leases.some((lease) =>\n        leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),\n      );\n    });\n\n  const shouldRunOpportunisticWork = Effect.map(\n    snapshot,\n    (current) => current.shouldRunOpportunisticWork,\n  );\n\n  yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(\n    Effect.forkScoped,\n  );\n  yield* Stream.runForEach(serverSettings.streamChanges, () => publishSnapshot).pipe(\n    Effect.forkScoped,\n  );\n\n  yield* Effect.forever(\n    Effect.sleep(\"15 seconds\").pipe(\n      Effect.andThen(\n        publishMutex.withPermits(1)(\n          Effect.gen(function* () {\n            const now = yield* DateTime.now;\n            yield* Ref.update(leasesRef, (leases) => {\n              const next = new Map(leases);\n              for (const [key, lease] of next) {\n                if (!isLeaseActive(lease, now)) {\n                  next.delete(key);\n                }\n              }\n              return next;\n            });\n            yield* publishSnapshotUnlocked;\n          }),\n        ),\n      ),\n    ),\n  ).pipe(Effect.forkScoped);\n\n  return BackgroundPolicy.of({\n    reportClientActivity,\n    removeRpcClient,\n    reportHostPowerState: hostPowerMonitor.report,\n    snapshot,\n    streamChanges: Stream.fromPubSub(changes),\n    subscribe: subscribeBeforeSnapshot(changes, snapshot, publishMutex),\n    hasDemand,\n    shouldRunScopeWork,\n    shouldRunOpportunisticWork,\n  });\n});\n\nexport const layer = Layer.effect(BackgroundPolicy, make());\n","import type { ResourceAttributionEntry, ResourceAttributionSnapshot } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\n\nexport interface ResourceAttributionRecord {\n  readonly component: string;\n  readonly operation: string;\n  readonly logicalReadBytes?: number;\n  readonly logicalWriteBytes?: number;\n  readonly count?: number;\n  readonly durationMs?: number;\n}\n\nexport class ResourceAttribution extends Context.Service<\n  ResourceAttribution,\n  {\n    readonly record: (input: ResourceAttributionRecord) => Effect.Effect<void>;\n    readonly snapshot: Effect.Effect<ResourceAttributionSnapshot>;\n  }\n>()(\"t3/resourceTelemetry/ResourceAttribution\") {}\n\nfunction key(input: Pick<ResourceAttributionRecord, \"component\" | \"operation\">): string {\n  return `${input.component}\\u0000${input.operation}`;\n}\n\nfunction nonNegativeInteger(value: number | undefined, fallback: number): number {\n  if (value === undefined) return fallback;\n  if (!Number.isFinite(value)) return 0;\n  return Math.max(0, Math.round(value));\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.resourceAttribution.make\")(function* () {\n  const entries = yield* Ref.make(new Map<string, ResourceAttributionEntry>());\n\n  const record: ResourceAttribution[\"Service\"][\"record\"] = (input) =>\n    Ref.update(entries, (current) => {\n      const next = new Map(current);\n      const entryKey = key(input);\n      const existing = next.get(entryKey);\n      next.set(entryKey, {\n        component: input.component,\n        operation: input.operation,\n        logicalReadBytes:\n          (existing?.logicalReadBytes ?? 0) + nonNegativeInteger(input.logicalReadBytes, 0),\n        logicalWriteBytes:\n          (existing?.logicalWriteBytes ?? 0) + nonNegativeInteger(input.logicalWriteBytes, 0),\n        count: (existing?.count ?? 0) + nonNegativeInteger(input.count, 1),\n        durationMs: (existing?.durationMs ?? 0) + nonNegativeInteger(input.durationMs, 0),\n      });\n      return next;\n    });\n\n  return ResourceAttribution.of({\n    record,\n    snapshot: Effect.gen(function* () {\n      const readAt = yield* DateTime.now;\n      const current = yield* Ref.get(entries);\n      return {\n        readAt,\n        entries: [...current.values()].toSorted(\n          (left, right) => right.logicalWriteBytes - left.logicalWriteBytes,\n        ),\n      };\n    }),\n  });\n});\n\nexport const layer = Layer.effect(ResourceAttribution, make());\n","/**\n * Backend paths the web dev server proxies in single-origin browser dev.\n *\n * Two consumers must agree on this list: the Vite proxy map\n * (apps/web/vite.config.ts) that forwards these to the backend, and the\n * server's dev catch-all (apps/server/src/http.ts) that 404s them instead of\n * redirecting back to Vite. Drift is silent and nasty in both directions — a\n * prefix only Vite knows gets answered with index.html; a prefix only the\n * server knows redirect-loops through the proxy.\n */\nexport const DEV_PROXIED_PATH_PREFIXES = [\"/api\", \"/oauth\", \"/.well-known\", \"/ws\"] as const;\n\nexport function isDevProxiedPath(pathname: string): boolean {\n  return DEV_PROXIED_PATH_PREFIXES.some(\n    (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),\n  );\n}\n","/**\n * Shared batch exporter for OTLP/HTTP observability modules.\n *\n * Signal modules use this exporter to buffer already-encoded telemetry and post\n * it to a configured OTLP endpoint. It owns the scoped transport loop, batching,\n * retry behavior, temporary disabling after repeated failures, and final flush\n * during shutdown.\n *\n * @since 4.0.0\n */\nimport { Clock } from \"../../Clock.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Duration from \"../../Duration.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport * as FiberSet from \"../../FiberSet.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Num from \"../../Number.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Schedule from \"../../Schedule.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Headers from \"../../unstable/http/Headers.js\";\nimport * as HttpClient from \"../../unstable/http/HttpClient.js\";\nimport * as HttpClientError from \"../../unstable/http/HttpClientError.js\";\nimport * as HttpClientRequest from \"../../unstable/http/HttpClientRequest.js\";\nconst retryAfterDelay = value => {\n  const seconds = Option.fromUndefinedOr(value).pipe(Option.flatMap(Num.parse));\n  if (Option.isSome(seconds)) {\n    return Effect.succeed(Duration.seconds(seconds.value));\n  }\n  if (value === undefined) {\n    return Effect.succeed(Duration.seconds(5));\n  }\n  const timestamp = Date.parse(value);\n  if (Number.isNaN(timestamp)) {\n    return Effect.succeed(Duration.seconds(5));\n  }\n  return Effect.map(Clock, clock => Duration.millis(Math.max(timestamp - clock.currentTimeMillisUnsafe(), 1)));\n};\nconst policy = /*#__PURE__*/Schedule.forever.pipe(Schedule.passthrough, /*#__PURE__*/Schedule.addDelay(({\n  output: error\n}) => {\n  if (HttpClientError.isHttpClientError(error) && error.reason._tag === \"StatusCodeError\" && error.reason.response.status === 429) {\n    return retryAfterDelay(error.reason.response.headers[\"retry-after\"]);\n  }\n  return Effect.succeed(Duration.seconds(1));\n}));\n/**\n * Registry of exporter flush operations, used to manually drain buffered\n * telemetry before the surrounding scope closes.\n *\n * **Details**\n *\n * Every exporter created by `make` registers its export operation here, so a\n * single `flush` drains all signals sharing the registry. `flush` returns only\n * after the exports it initiated have settled, cannot fail, and respects each\n * exporter's temporary-disable window. Wrap it with `Effect.timeoutOption` to\n * bound its duration at the call site.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Flusher extends /*#__PURE__*/Context.Service()(\"effect/observability/OtlpExporter/Flusher\") {}\n/**\n * Provides a `Flusher` backed by a fresh registry.\n *\n * **Details**\n *\n * This is intentionally a single module-level constant rather than a factory:\n * layer memoization is keyed by layer instance, so every signal layer\n * referencing this same constant shares one registry per layer build, and one\n * `flush` drains traces, logs and metrics together. A factory returning a new\n * layer per call would silently create one registry per signal.\n *\n * Registration is scoped — an exporter is removed from the registry when its\n * own scope closes. Flushing with an empty registry is a no-op.\n *\n * Note that `flush` cannot await an export that was already in flight when it\n * was called (for example one started by the export interval); it only waits\n * for the exports it initiates.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerFlusher = /*#__PURE__*/Layer.sync(Flusher, () => {\n  const registry = new Set();\n  return {\n    flush: Effect.suspend(() => {\n      if (registry.size === 0) {\n        return Effect.void;\n      }\n      return Effect.forEach(registry, identity, {\n        concurrency: \"unbounded\",\n        discard: true\n      });\n    }),\n    register: run => Effect.flatMap(Scope.Scope, scope => {\n      registry.add(run);\n      return Scope.addFinalizer(scope, Effect.sync(() => registry.delete(run)));\n    })\n  };\n});\n/**\n * Creates a scoped OTLP batch exporter.\n *\n * **Details**\n *\n * The exporter buffers pushed data, periodically posts encoded batches to the\n * configured URL, retries transient failures, temporarily disables exporting\n * after unhandled failures, and flushes during scope finalization up to\n * `shutdownTimeout`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const services = yield* Effect.context();\n  const clock = Context.get(services, Clock);\n  const scope = Context.get(services, Scope.Scope);\n  const exportInterval = Duration.max(Duration.fromInputUnsafe(options.exportInterval), Duration.zero);\n  let disabledUntil = undefined;\n  const client = HttpClient.filterStatusOk(Context.get(services, HttpClient.HttpClient)).pipe(HttpClient.transformResponse(Effect.provideService(HttpClient.TracerPropagationEnabled, false)), HttpClient.retryTransient({\n    schedule: policy,\n    times: 3\n  }));\n  let headers = Headers.fromRecordUnsafe({\n    \"user-agent\": `effect-opentelemetry-${options.label}/0.0.0`\n  });\n  if (options.headers) {\n    headers = Headers.merge(Headers.fromInput(options.headers), headers);\n  }\n  const request = HttpClientRequest.post(options.url, {\n    headers\n  });\n  let buffer = [];\n  const runExport = Effect.suspend(() => {\n    if (disabledUntil !== undefined && clock.currentTimeMillisUnsafe() < disabledUntil) {\n      return Effect.void;\n    } else if (disabledUntil !== undefined) {\n      disabledUntil = undefined;\n    }\n    const items = buffer;\n    if (options.maxBatchSize !== \"disabled\") {\n      if (buffer.length === 0) {\n        return Effect.void;\n      }\n      buffer = [];\n    }\n    return client.execute(HttpClientRequest.setBody(request, options.body(items))).pipe(Effect.asVoid, Effect.withTracerEnabled(false));\n  }).pipe(Effect.catchCause(cause => {\n    if (disabledUntil !== undefined) return Effect.void;\n    disabledUntil = clock.currentTimeMillisUnsafe() + 60_000;\n    buffer = [];\n    return Effect.logDebug(\"Disabling exporter for 60 seconds\", cause);\n  }), Effect.annotateLogs({\n    package: \"@effect/opentelemetry\",\n    module: options.label\n  }));\n  const exportFibers = yield* FiberSet.make();\n  const runExportFork = yield* FiberSet.runtime(exportFibers)();\n  const flusher = yield* Flusher;\n  yield* flusher.register(runExport);\n  yield* Scope.addFinalizer(scope, Effect.suspend(() => {\n    if (disabledUntil !== undefined) return Effect.void;\n    runExportFork(runExport);\n    return FiberSet.awaitEmpty(exportFibers);\n  }).pipe(Effect.ignore, Effect.interruptible, Effect.timeoutOption(options.shutdownTimeout)));\n  yield* Effect.sleep(exportInterval).pipe(Effect.andThen(FiberSet.run(exportFibers, runExport)), Effect.flatMap(Fiber.await), Effect.forever, Effect.forkIn(scope));\n  return {\n    push(data) {\n      if (disabledUntil !== undefined) return;\n      buffer.push(data);\n      if (options.maxBatchSize !== \"disabled\" && buffer.length >= options.maxBatchSize) {\n        runExportFork(runExport);\n      }\n    }\n  };\n});\n//# sourceMappingURL=OtlpExporter.js.map","/**\n * Builds OTLP resource metadata shared by exported telemetry.\n *\n * An OTLP resource describes the service and other attributes attached to every\n * exported log, metric, or trace. This module builds resources from explicit\n * options or OpenTelemetry environment variables and converts JavaScript values\n * into OTLP attribute values.\n *\n * @since 4.0.0\n */\nimport * as Config from \"../../Config.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { format } from \"../../Formatter.js\";\nimport * as Schema from \"../../Schema.js\";\n/**\n * Creates an OTLP resource from service metadata and additional attributes.\n *\n * **Details**\n *\n * The resource always includes `service.name`, includes `service.version` when\n * provided, and converts custom attributes into OTLP attribute values.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => {\n  const resourceAttributes = options.attributes ? entriesToAttributes(Object.entries(options.attributes)) : [];\n  resourceAttributes.push({\n    key: \"service.name\",\n    value: {\n      stringValue: options.serviceName\n    }\n  });\n  if (options.serviceVersion) {\n    resourceAttributes.push({\n      key: \"service.version\",\n      value: {\n        stringValue: options.serviceVersion\n      }\n    });\n  }\n  return {\n    attributes: resourceAttributes,\n    droppedAttributesCount: 0\n  };\n};\n/**\n * Creates an OTLP resource from explicit options and OpenTelemetry\n * configuration.\n *\n * **When to use**\n *\n * Use when resource metadata may be configured in code or by the deployment\n * environment. To let operators set the service identity, omit `serviceName`,\n * `serviceVersion`, and their matching attributes, then use\n * `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`.\n *\n * **Details**\n *\n * Explicit `serviceName` and `serviceVersion` options take precedence over\n * matching explicit attributes. Explicit attributes take precedence over\n * environment variables. `OTEL_SERVICE_NAME` and `OTEL_SERVICE_VERSION` take\n * precedence over matching attributes in `OTEL_RESOURCE_ATTRIBUTES`. Missing\n * required configuration is converted to a defect.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const fromConfig = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const env = yield* Config.schema(Schema.UndefinedOr(Config.Record(Schema.StringFromUriComponent, Schema.StringFromUriComponent)), \"OTEL_RESOURCE_ATTRIBUTES\");\n  const serviceName = options?.serviceName ?? options?.attributes?.[\"service.name\"] ?? (yield* Config.schema(Schema.UndefinedOr(Schema.String), \"OTEL_SERVICE_NAME\")) ?? env?.[\"service.name\"] ?? (yield* Config.string(\"OTEL_SERVICE_NAME\"));\n  const serviceVersion = options?.serviceVersion ?? options?.attributes?.[\"service.version\"] ?? (yield* Config.schema(Schema.UndefinedOr(Schema.String), \"OTEL_SERVICE_VERSION\")) ?? env?.[\"service.version\"];\n  const attributes = {\n    ...env,\n    ...options?.attributes\n  };\n  delete attributes[\"service.name\"];\n  delete attributes[\"service.version\"];\n  return make({\n    serviceName,\n    serviceVersion,\n    attributes\n  });\n}, Effect.orDie);\n/**\n * Returns the `service.name` attribute from an OTLP resource.\n *\n * **When to use**\n *\n * Use when an OTLP resource is known to contain a string `service.name` and\n * throwing is acceptable if that invariant is broken.\n *\n * **Gotchas**\n *\n * Throws if the resource does not contain a string `service.name` attribute.\n *\n * @category attributes\n * @since 4.0.0\n */\nexport const serviceNameUnsafe = resource => {\n  const serviceNameAttribute = resource.attributes.find(attr => attr.key === \"service.name\");\n  if (!serviceNameAttribute || !serviceNameAttribute.value.stringValue) {\n    throw new Error(\"Resource does not contain a service name\");\n  }\n  return serviceNameAttribute.value.stringValue;\n};\n/**\n * Converts key/value entries into OTLP `KeyValue` attributes.\n *\n * @category attributes\n * @since 4.0.0\n */\nexport const entriesToAttributes = entries => {\n  const attributes = [];\n  for (const [key, value] of entries) {\n    attributes.push({\n      key,\n      value: unknownToAttributeValue(value)\n    });\n  }\n  return attributes;\n};\n/**\n * Converts an arbitrary JavaScript value into an OTLP `AnyValue`.\n *\n * **Details**\n *\n * Arrays are converted recursively, primitive values use their matching OTLP\n * fields, and unsupported values are formatted as strings.\n *\n * @category attributes\n * @since 4.0.0\n */\nexport const unknownToAttributeValue = value => {\n  if (Array.isArray(value)) {\n    return {\n      arrayValue: {\n        values: value.map(unknownToAttributeValue)\n      }\n    };\n  }\n  switch (typeof value) {\n    case \"string\":\n      return {\n        stringValue: value\n      };\n    case \"bigint\":\n      return {\n        intValue: String(value)\n      };\n    case \"number\":\n      return Number.isInteger(value) ? {\n        intValue: value\n      } : {\n        doubleValue: value\n      };\n    case \"boolean\":\n      return {\n        boolValue: value\n      };\n    default:\n      return {\n        stringValue: format(value)\n      };\n  }\n};\n//# sourceMappingURL=OtlpResource.js.map","/**\n * Serializes OTLP payloads into HTTP request bodies.\n *\n * Signal exporters build trace, metric, and log data structures in memory. This\n * module provides the service that turns those structures into JSON or protobuf\n * HTTP bodies before they are posted to an OTLP collector.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as HttpBody from \"../http/HttpBody.js\";\nimport * as otlpProtobuf from \"./internal/otlpProtobuf.js\";\n/**\n * Service for serializing OTLP traces, metrics, and logs into HTTP request\n * bodies.\n *\n * @category services\n * @since 4.0.0\n */\nexport class OtlpSerialization extends /*#__PURE__*/Context.Service()(\"effect/observability/OtlpSerialization\") {}\n/**\n * Provides `OtlpSerialization` using OTLP/HTTP JSON bodies.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/Layer.succeed(OtlpSerialization, {\n  traces: spans => HttpBody.jsonUnsafe(spans),\n  metrics: metrics => HttpBody.jsonUnsafe(metrics),\n  logs: logs => HttpBody.jsonUnsafe(logs)\n});\n/**\n * Provides `OtlpSerialization` using protobuf-encoded OTLP bodies with the\n * `application/x-protobuf` content type.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtobuf = /*#__PURE__*/Layer.succeed(OtlpSerialization, {\n  traces: spans => HttpBody.uint8Array(otlpProtobuf.encodeTracesData(spans), \"application/x-protobuf\"),\n  metrics: metrics => HttpBody.uint8Array(otlpProtobuf.encodeMetricsData(metrics), \"application/x-protobuf\"),\n  logs: logs => HttpBody.uint8Array(otlpProtobuf.encodeLogsData(logs), \"application/x-protobuf\")\n});\n//# sourceMappingURL=OtlpSerialization.js.map","/**\n * Exports Effect metrics over OTLP/HTTP.\n *\n * This module periodically snapshots metrics from the current Effect context,\n * serializes them as OTLP resource metrics, and posts them to a metrics\n * endpoint such as an OpenTelemetry Collector or vendor intake. It is meant for\n * long-running services that already update `Metric` counters, gauges,\n * histograms, frequencies, or summaries. The exporter supports cumulative\n * reporting from a fixed start time and delta reporting from the previous\n * export.\n *\n * @since 4.0.0\n */\nimport * as Arr from \"../../Array.js\";\nimport { Clock } from \"../../Clock.js\";\nimport * as Config from \"../../Config.js\";\nimport * as Duration from \"../../Duration.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Metric from \"../../Metric.js\";\nimport * as Option from \"../../Option.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Starts a scoped OTLP metrics exporter.\n *\n * **Details**\n *\n * The exporter snapshots registered Effect metrics on the configured interval, serializes them with the selected aggregation temporality, and flushes during scope finalization up to `shutdownTimeout`.\n * Manual flushing also triggers a snapshot. With delta temporality, each\n * snapshot advances the previous-export state, so frequent flushes narrow the\n * delta aggregation windows.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const clock = yield* Clock;\n  const serialization = yield* OtlpSerialization;\n  const startTimeNanos = yield* clock.currentTimeNanos;\n  const startTime = String(startTimeNanos);\n  const temporality = options.temporality ?? \"cumulative\";\n  const resource = yield* OtlpResource.fromConfig(options.resource);\n  const metricsScope = {\n    name: OtlpResource.serviceNameUnsafe(resource)\n  };\n  const services = yield* Effect.context();\n  // State for delta temporality tracking\n  let previousExportTimeNanos = startTimeNanos;\n  const previousCounterState = new Map();\n  const previousHistogramState = new Map();\n  const previousFrequencyState = new Map();\n  const previousSummaryState = new Map();\n  const snapshot = () => {\n    const snapshot = Metric.snapshotUnsafe(services);\n    const nowNanos = clock.currentTimeNanosUnsafe();\n    const nowTime = String(nowNanos);\n    const metricData = [];\n    const metricDataByName = new Map();\n    const addMetricData = data => {\n      metricData.push(data);\n      metricDataByName.set(data.name, data);\n    };\n    const isDelta = temporality === \"delta\";\n    const aggregationTemporalityEnum = isDelta ? EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA : EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;\n    const intervalStartTime = isDelta ? String(previousExportTimeNanos) : startTime;\n    for (let i = 0, len = snapshot.length; i < len; i++) {\n      const state = snapshot[i];\n      const unit = state.attributes?.unit ?? state.attributes?.time_unit ?? \"1\";\n      const attributes = state.attributes ? OtlpResource.entriesToAttributes(Object.entries(state.attributes)) : [];\n      const metricKey = makeMetricKey(state.id, state.attributes);\n      switch (state.type) {\n        case \"Counter\":\n          {\n            const currentCount = state.state.count;\n            let reportValue = currentCount;\n            if (isDelta) {\n              const previousCount = previousCounterState.get(metricKey);\n              if (previousCount !== undefined) {\n                if (typeof currentCount === \"bigint\" && typeof previousCount === \"bigint\") {\n                  reportValue = currentCount - previousCount;\n                  // Handle reset: if current < previous, report current value\n                  if (reportValue < BigInt(0)) {\n                    reportValue = currentCount;\n                  }\n                } else {\n                  const curr = Number(currentCount);\n                  const prev = Number(previousCount);\n                  reportValue = curr - prev;\n                  // Handle reset\n                  if (reportValue < 0) {\n                    reportValue = curr;\n                  }\n                }\n              }\n              previousCounterState.set(metricKey, currentCount);\n            }\n            const dataPoint = {\n              attributes,\n              startTimeUnixNano: intervalStartTime,\n              timeUnixNano: nowTime\n            };\n            if (typeof reportValue === \"bigint\") {\n              dataPoint.asInt = Number(reportValue);\n            } else {\n              dataPoint.asDouble = reportValue;\n            }\n            if (metricDataByName.has(state.id)) {\n              metricDataByName.get(state.id).sum.dataPoints.push(dataPoint);\n            } else {\n              addMetricData({\n                name: state.id,\n                description: state.description,\n                unit,\n                sum: {\n                  aggregationTemporality: aggregationTemporalityEnum,\n                  isMonotonic: state.state.incremental,\n                  dataPoints: [dataPoint]\n                }\n              });\n            }\n            break;\n          }\n        case \"Gauge\":\n          {\n            // Gauges don't have temporality - they always report current value\n            const dataPoint = {\n              attributes,\n              startTimeUnixNano: startTime,\n              timeUnixNano: nowTime\n            };\n            if (typeof state.state.value === \"bigint\") {\n              dataPoint.asInt = Number(state.state.value);\n            } else {\n              dataPoint.asDouble = state.state.value;\n            }\n            if (metricDataByName.has(state.id)) {\n              metricDataByName.get(state.id).gauge.dataPoints.push(dataPoint);\n            } else {\n              addMetricData({\n                name: state.id,\n                description: state.description,\n                unit,\n                gauge: {\n                  dataPoints: [dataPoint]\n                }\n              });\n            }\n            break;\n          }\n        case \"Histogram\":\n          {\n            const size = state.state.buckets.length;\n            const currentBuckets = {\n              boundaries: Arr.allocate(size - 1),\n              counts: Arr.allocate(size)\n            };\n            let idx = 0;\n            let prev = 0;\n            for (const [boundary, value] of state.state.buckets) {\n              if (idx < size - 1) {\n                currentBuckets.boundaries[idx] = boundary;\n              }\n              currentBuckets.counts[idx] = value - prev;\n              prev = value;\n              idx++;\n            }\n            let reportCount = state.state.count;\n            let reportSum = state.state.sum;\n            let reportBucketCounts = currentBuckets.counts;\n            const reportMin = state.state.min;\n            const reportMax = state.state.max;\n            if (isDelta) {\n              const previousState = previousHistogramState.get(metricKey);\n              if (previousState !== undefined) {\n                reportCount = state.state.count - previousState.count;\n                reportSum = state.state.sum - previousState.sum;\n                reportBucketCounts = currentBuckets.counts.map((c, i) => Math.max(0, c - (previousState.bucketCounts[i] ?? 0)));\n                // For delta, min/max represent the interval's min/max\n                // We can't compute these from cumulative state, so we use current values\n                // Note: This is a limitation - true delta min/max would require tracking\n                // observations within each interval\n              }\n              previousHistogramState.set(metricKey, {\n                count: state.state.count,\n                sum: state.state.sum,\n                bucketCounts: currentBuckets.counts.slice(),\n                min: state.state.min,\n                max: state.state.max\n              });\n            }\n            const dataPoint = {\n              attributes,\n              startTimeUnixNano: intervalStartTime,\n              timeUnixNano: nowTime,\n              count: reportCount,\n              min: reportMin,\n              max: reportMax,\n              sum: reportSum,\n              bucketCounts: reportBucketCounts,\n              explicitBounds: currentBuckets.boundaries\n            };\n            if (metricDataByName.has(state.id)) {\n              metricDataByName.get(state.id).histogram.dataPoints.push(dataPoint);\n            } else {\n              addMetricData({\n                name: state.id,\n                description: state.description,\n                unit,\n                histogram: {\n                  aggregationTemporality: aggregationTemporalityEnum,\n                  dataPoints: [dataPoint]\n                }\n              });\n            }\n            break;\n          }\n        case \"Frequency\":\n          {\n            const dataPoints = [];\n            const currentOccurrences = new Map();\n            for (const [freqKey, value] of state.state.occurrences) {\n              currentOccurrences.set(freqKey, value);\n              let reportValue = value;\n              if (isDelta) {\n                const previousOccurrences = previousFrequencyState.get(metricKey);\n                if (previousOccurrences !== undefined) {\n                  const previousValue = previousOccurrences.get(freqKey) ?? 0;\n                  reportValue = Math.max(0, value - previousValue);\n                }\n              }\n              dataPoints.push({\n                attributes: [...attributes, {\n                  key: \"key\",\n                  value: {\n                    stringValue: freqKey\n                  }\n                }],\n                startTimeUnixNano: intervalStartTime,\n                timeUnixNano: nowTime,\n                asInt: reportValue\n              });\n            }\n            if (isDelta) {\n              previousFrequencyState.set(metricKey, currentOccurrences);\n            }\n            if (metricDataByName.has(state.id)) {\n              metricDataByName.get(state.id).sum.dataPoints.push(...dataPoints);\n            } else {\n              addMetricData({\n                name: state.id,\n                description: state.description,\n                unit,\n                sum: {\n                  aggregationTemporality: aggregationTemporalityEnum,\n                  isMonotonic: true,\n                  dataPoints\n                }\n              });\n            }\n            break;\n          }\n        case \"Summary\":\n          {\n            // Quantiles are always computed fresh from the sliding window\n            // They don't have temporality in the traditional sense\n            const dataPoints = [{\n              attributes: [...attributes, {\n                key: \"quantile\",\n                value: {\n                  stringValue: \"min\"\n                }\n              }],\n              startTimeUnixNano: intervalStartTime,\n              timeUnixNano: nowTime,\n              asDouble: state.state.min\n            }];\n            for (const [quantile, value] of state.state.quantiles) {\n              dataPoints.push({\n                attributes: [...attributes, {\n                  key: \"quantile\",\n                  value: {\n                    stringValue: quantile.toString()\n                  }\n                }],\n                startTimeUnixNano: intervalStartTime,\n                timeUnixNano: nowTime,\n                asDouble: value ?? 0\n              });\n            }\n            dataPoints.push({\n              attributes: [...attributes, {\n                key: \"quantile\",\n                value: {\n                  stringValue: \"max\"\n                }\n              }],\n              startTimeUnixNano: intervalStartTime,\n              timeUnixNano: nowTime,\n              asDouble: state.state.max\n            });\n            let reportCount = state.state.count;\n            let reportSum = state.state.sum;\n            if (isDelta) {\n              const previousState = previousSummaryState.get(metricKey);\n              if (previousState !== undefined) {\n                reportCount = state.state.count - previousState.count;\n                reportSum = state.state.sum - previousState.sum;\n              }\n              previousSummaryState.set(metricKey, {\n                count: state.state.count,\n                sum: state.state.sum\n              });\n            }\n            const countDataPoint = {\n              attributes,\n              startTimeUnixNano: intervalStartTime,\n              timeUnixNano: nowTime,\n              asInt: reportCount\n            };\n            const sumDataPoint = {\n              attributes,\n              startTimeUnixNano: intervalStartTime,\n              timeUnixNano: nowTime,\n              asDouble: reportSum\n            };\n            if (metricDataByName.has(`${state.id}_quantiles`)) {\n              metricDataByName.get(`${state.id}_quantiles`).sum.dataPoints.push(...dataPoints);\n              metricDataByName.get(`${state.id}_count`).sum.dataPoints.push(countDataPoint);\n              metricDataByName.get(`${state.id}_sum`).sum.dataPoints.push(sumDataPoint);\n            } else {\n              addMetricData({\n                name: `${state.id}_quantiles`,\n                description: state.description,\n                unit,\n                sum: {\n                  aggregationTemporality: aggregationTemporalityEnum,\n                  isMonotonic: false,\n                  dataPoints\n                }\n              });\n              addMetricData({\n                name: `${state.id}_count`,\n                description: state.description,\n                unit: \"1\",\n                sum: {\n                  aggregationTemporality: aggregationTemporalityEnum,\n                  isMonotonic: true,\n                  dataPoints: [countDataPoint]\n                }\n              });\n              addMetricData({\n                name: `${state.id}_sum`,\n                description: state.description,\n                unit: \"1\",\n                sum: {\n                  aggregationTemporality: aggregationTemporalityEnum,\n                  isMonotonic: true,\n                  dataPoints: [sumDataPoint]\n                }\n              });\n            }\n            break;\n          }\n      }\n    }\n    // Update the previous export time for delta calculations\n    if (isDelta) {\n      previousExportTimeNanos = nowNanos;\n    }\n    return serialization.metrics({\n      resourceMetrics: [{\n        resource,\n        scopeMetrics: [{\n          scope: metricsScope,\n          metrics: metricData\n        }]\n      }]\n    });\n  };\n  yield* Exporter.make({\n    label: \"OtlpMetrics\",\n    url: options.url,\n    headers: options.headers,\n    maxBatchSize: \"disabled\",\n    exportInterval: options.exportInterval ?? Duration.seconds(10),\n    body: snapshot,\n    shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n  });\n});\n/**\n * Layer that starts the OTLP metrics exporter created by `make`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.effectDiscard(make(options)).pipe(Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP metrics layer from OpenTelemetry configuration.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n  const {\n    disabled,\n    endpoint,\n    exporters\n  } = yield* Config.all({\n    disabled: Config.boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n    endpoint: OtlpEnv.endpoint(\"METRICS\"),\n    exporters: OtlpEnv.exporters(\"METRICS\")\n  });\n  if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n    return Exporter.layerFlusher;\n  }\n  const {\n    baseTimeout,\n    metricsTimeout,\n    exportTimeout,\n    exportInterval,\n    temporalityPreference\n  } = yield* Config.all({\n    baseTimeout: Config.option(Config.int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n    metricsTimeout: Config.option(Config.int(\"OTEL_EXPORTER_OTLP_METRICS_TIMEOUT\")),\n    exportTimeout: Config.option(Config.int(\"OTEL_METRIC_EXPORT_TIMEOUT\")),\n    exportInterval: Config.option(Config.int(\"OTEL_METRIC_EXPORT_INTERVAL\").pipe(Config.map(Duration.millis))),\n    temporalityPreference: Config.option(Config.literals([\"delta\", \"cumulative\"], \"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE\"))\n  });\n  const shutdownTimeout = Option.firstSomeOf([metricsTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n  return layer({\n    url: endpoint.toString(),\n    resource: options?.resource,\n    headers: options?.headers ?? (yield* OtlpEnv.headers(\"METRICS\")),\n    exportInterval: Option.getOrUndefined(exportInterval),\n    shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n    temporality: Option.getOrUndefined(temporalityPreference)\n  });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\n/** Creates a unique key for a metric including its attributes */\nconst makeMetricKey = (id, attributes) => {\n  if (attributes === undefined || Object.keys(attributes).length === 0) {\n    return id;\n  }\n  const sortedEntries = Object.entries(attributes).sort((a, b) => a[0].localeCompare(b[0]));\n  return `${id}:${JSON.stringify(sortedEntries)}`;\n};\n/**\n * AggregationTemporality defines how a metric aggregator reports aggregated\n * values. It describes how those values relate to the time interval over\n * which they are aggregated.\n */\nconst EAggregationTemporality = {\n  AGGREGATION_TEMPORALITY_UNSPECIFIED: 0,\n  /** DELTA is an AggregationTemporality for a metric aggregator which reports\n    changes since last report time. Successive metrics contain aggregation of\n    values from continuous and non-overlapping intervals.\n       The values for a DELTA metric are based only on the time interval\n    associated with one measurement cycle. There is no dependency on\n    previous measurements like is the case for CUMULATIVE metrics.\n       For example, consider a system measuring the number of requests that\n    it receives and reports the sum of these requests every second as a\n    DELTA metric:\n       1. The system starts receiving at time=t_0.\n    2. A request is received, the system measures 1 request.\n    3. A request is received, the system measures 1 request.\n    4. A request is received, the system measures 1 request.\n    5. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0 to\n        t_0+1 with a value of 3.\n    6. A request is received, the system measures 1 request.\n    7. A request is received, the system measures 1 request.\n    8. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0+1 to\n        t_0+2 with a value of 2. */\n  AGGREGATION_TEMPORALITY_DELTA: 1,\n  /** CUMULATIVE is an AggregationTemporality for a metric aggregator which\n    reports changes since a fixed start time. This means that current values\n    of a CUMULATIVE metric depend on all previous measurements since the\n    start time. Because of this, the sender is required to retain this state\n    in some form. If this state is lost or invalidated, the CUMULATIVE metric\n    values MUST be reset and a new fixed start time following the last\n    reported measurement time sent MUST be used.\n       For example, consider a system measuring the number of requests that\n    it receives and reports the sum of these requests every second as a\n    CUMULATIVE metric:\n       1. The system starts receiving at time=t_0.\n    2. A request is received, the system measures 1 request.\n    3. A request is received, the system measures 1 request.\n    4. A request is received, the system measures 1 request.\n    5. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0 to\n        t_0+1 with a value of 3.\n    6. A request is received, the system measures 1 request.\n    7. A request is received, the system measures 1 request.\n    8. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0 to\n        t_0+2 with a value of 5.\n    9. The system experiences a fault and loses state.\n    10. The system recovers and resumes receiving at time=t_1.\n    11. A request is received, the system measures 1 request.\n    12. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_1 to\n        t_0+1 with a value of 1.\n       Note: Even though, when reporting changes since last report time, using\n    CUMULATIVE is valid, it is not recommended. This may cause problems for\n    systems that do not use start_time to determine when the aggregation\n    value was reset (e.g. Prometheus). */\n  AGGREGATION_TEMPORALITY_CUMULATIVE: 2\n};\n//# sourceMappingURL=OtlpMetrics.js.map","/**\n * Exports Effect tracing spans over OTLP/HTTP.\n *\n * This module creates a `Tracer.Tracer` backed by the shared OTLP batch\n * exporter, so spans created by Effect tracing APIs can be sent to an\n * OpenTelemetry Collector, vendor endpoint, or local collector. Exported spans\n * include identifiers, parent links, attributes, events, timing, kind, and\n * status information. Use the constructor directly or install it through the\n * provided layer.\n *\n * @since 4.0.0\n */\nimport * as Cause from \"../../Cause.js\";\nimport * as Config from \"../../Config.js\";\nimport * as Duration from \"../../Duration.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { flow } from \"../../Function.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Tracer from \"../../Tracer.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport { entriesToAttributes } from \"./OtlpResource.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Creates a `Tracer` that exports ended sampled spans to an OTLP traces endpoint.\n *\n * **Details**\n *\n * Spans are batched using the configured interval and batch size, serialized\n * with `OtlpSerialization`, and flushed when the surrounding `Scope` closes.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const otelResource = yield* OtlpResource.fromConfig(options.resource);\n  const serialization = yield* OtlpSerialization;\n  const scope = {\n    name: OtlpResource.serviceNameUnsafe(otelResource)\n  };\n  const exporter = yield* Exporter.make({\n    label: \"OtlpTracer\",\n    url: options.url,\n    headers: options.headers,\n    exportInterval: options.exportInterval ?? Duration.seconds(5),\n    maxBatchSize: options.maxBatchSize ?? 1000,\n    body(spans) {\n      const data = {\n        resourceSpans: [{\n          resource: otelResource,\n          scopeSpans: [{\n            scope,\n            spans\n          }]\n        }]\n      };\n      return serialization.traces(data);\n    },\n    shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n  });\n  function exportFn(span) {\n    if (!span.sampled) return;\n    exporter.push(makeOtlpSpan(span));\n  }\n  return Tracer.make({\n    span(options) {\n      return makeSpan({\n        ...options,\n        status: {\n          _tag: \"Started\",\n          startTime: options.startTime\n        },\n        attributes: new Map(),\n        export: exportFn\n      });\n    },\n    context: options.context ? function (primitive, fiber) {\n      if (fiber.currentSpan === undefined) {\n        return primitive[\"~effect/Effect/evaluate\"](fiber);\n      }\n      return options.context(primitive, fiber.currentSpan);\n    } : undefined\n  });\n});\n/**\n * Provides `Tracer.Tracer` using the OTLP tracer created by `make`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/flow(make, /*#__PURE__*/Layer.effect(Tracer.Tracer), /*#__PURE__*/Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP traces layer from OpenTelemetry configuration.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n  const {\n    disabled,\n    endpoint,\n    exporters\n  } = yield* Config.all({\n    disabled: Config.boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n    endpoint: OtlpEnv.endpoint(\"TRACES\"),\n    exporters: OtlpEnv.exporters(\"TRACES\")\n  });\n  if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n    return Exporter.layerFlusher;\n  }\n  const {\n    baseTimeout,\n    tracesTimeout,\n    exportTimeout,\n    scheduleDelay,\n    maxBatchSize\n  } = yield* Config.all({\n    baseTimeout: Config.option(Config.int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n    tracesTimeout: Config.option(Config.int(\"OTEL_EXPORTER_OTLP_TRACES_TIMEOUT\")),\n    exportTimeout: Config.option(Config.int(\"OTEL_BSP_EXPORT_TIMEOUT\")),\n    scheduleDelay: Config.option(Config.int(\"OTEL_BSP_SCHEDULE_DELAY\").pipe(Config.map(Duration.millis))),\n    maxBatchSize: Config.option(Config.int(\"OTEL_BSP_MAX_EXPORT_BATCH_SIZE\"))\n  });\n  const shutdownTimeout = Option.firstSomeOf([tracesTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n  return layer({\n    url: endpoint.toString(),\n    resource: options?.resource,\n    headers: options?.headers ?? (yield* OtlpEnv.headers(\"TRACES\")),\n    exportInterval: Option.getOrUndefined(scheduleDelay),\n    maxBatchSize: Option.getOrUndefined(maxBatchSize),\n    context: options?.context,\n    shutdownTimeout: Option.getOrUndefined(shutdownTimeout)\n  });\n}).pipe(Effect.orDie, Layer.unwrap);\nconst SpanProto = {\n  _tag: \"Span\",\n  end(endTime, exit) {\n    this.status = {\n      _tag: \"Ended\",\n      startTime: this.status.startTime,\n      endTime,\n      exit\n    };\n    this.export(this);\n  },\n  attribute(key, value) {\n    this.attributes.set(key, value);\n  },\n  event(name, startTime, attributes) {\n    this.events.push([name, startTime, attributes]);\n  },\n  addLinks(links) {\n    this.links.push(...links);\n  }\n};\nconst makeSpan = options => {\n  const self = Object.assign(Object.create(SpanProto), options);\n  if (Option.isSome(self.parent)) {\n    self.traceId = self.parent.value.traceId;\n  } else {\n    self.traceId = generateId(32);\n  }\n  self.spanId = generateId(16);\n  self.events = [];\n  return self;\n};\nconst generateId = len => {\n  const chars = \"0123456789abcdef\";\n  let result = \"\";\n  for (let i = 0; i < len; i++) {\n    result += chars[Math.floor(Math.random() * chars.length)];\n  }\n  return result;\n};\nconst makeOtlpSpan = self => {\n  const status = self.status;\n  const attributes = entriesToAttributes(self.attributes.entries());\n  const events = self.events.map(([name, startTime, attributes]) => ({\n    name,\n    timeUnixNano: String(startTime),\n    attributes: attributes ? entriesToAttributes(Object.entries(attributes)) : [],\n    droppedAttributesCount: 0\n  }));\n  let otelStatus;\n  if (status.exit._tag === \"Success\") {\n    otelStatus = constOtelStatusSuccess;\n  } else if (Cause.hasInterruptsOnly(status.exit.cause)) {\n    otelStatus = {\n      code: StatusCode.Ok,\n      message: \"Interrupted\"\n    };\n    attributes.push({\n      key: \"span.label\",\n      value: {\n        stringValue: \"⚠︎ Interrupted\"\n      }\n    }, {\n      key: \"status.interrupted\",\n      value: {\n        boolValue: true\n      }\n    });\n  } else {\n    const errors = Cause.prettyErrors(status.exit.cause, {\n      includeCauseInStack: true\n    });\n    otelStatus = {\n      code: StatusCode.Error\n    };\n    if (errors.length > 0) {\n      otelStatus.message = errors[0].message;\n      for (const error of errors) {\n        events.push({\n          name: \"exception\",\n          timeUnixNano: String(status.endTime),\n          droppedAttributesCount: 0,\n          attributes: [{\n            \"key\": \"exception.type\",\n            \"value\": {\n              \"stringValue\": error.name\n            }\n          }, {\n            \"key\": \"exception.message\",\n            \"value\": {\n              \"stringValue\": error.message\n            }\n          }, {\n            \"key\": \"exception.stacktrace\",\n            \"value\": {\n              \"stringValue\": error.stack ?? \"No stack trace available\"\n            }\n          }]\n        });\n      }\n    }\n  }\n  return {\n    traceId: self.traceId,\n    spanId: self.spanId,\n    parentSpanId: Option.match(self.parent, {\n      onNone: () => undefined,\n      onSome: parent => parent.spanId\n    }),\n    name: self.name,\n    kind: SpanKind[self.kind],\n    startTimeUnixNano: String(status.startTime),\n    endTimeUnixNano: String(status.endTime),\n    attributes,\n    droppedAttributesCount: 0,\n    events,\n    droppedEventsCount: 0,\n    status: otelStatus,\n    links: self.links.map(link => ({\n      traceId: link.span.traceId,\n      spanId: link.span.spanId,\n      attributes: entriesToAttributes(Object.entries(link.attributes)),\n      droppedAttributesCount: 0\n    })),\n    droppedLinksCount: 0\n  };\n};\nconst StatusCode = {\n  Unset: 0,\n  Ok: 1,\n  Error: 2\n};\nconst SpanKind = {\n  unspecified: 0,\n  internal: 1,\n  server: 2,\n  client: 3,\n  producer: 4,\n  consumer: 5\n};\nconst constOtelStatusSuccess = {\n  code: StatusCode.Ok\n};\n//# sourceMappingURL=OtlpTracer.js.map","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\nimport * as Schema from \"effect/Schema\";\n\nexport interface RotatingFileSinkOptions {\n  readonly filePath: string;\n  readonly maxBytes: number;\n  readonly maxFiles: number;\n  readonly throwOnError?: boolean;\n}\n\nexport class RotatingFileSinkConfigurationError extends Schema.TaggedErrorClass<RotatingFileSinkConfigurationError>()(\n  \"RotatingFileSinkConfigurationError\",\n  {\n    option: Schema.Literals([\"maxBytes\", \"maxFiles\"]),\n    received: Schema.Number,\n    minimum: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `${this.option} must be >= ${this.minimum} (received ${this.received})`;\n  }\n}\n\nexport class RotatingFileSinkError extends Schema.TaggedErrorClass<RotatingFileSinkError>()(\n  \"RotatingFileSinkError\",\n  {\n    operation: Schema.Literals([\"initialize\", \"read\", \"write\", \"rotate\", \"prune\"]),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} rotating log file ${this.filePath}`;\n  }\n}\n\nconst isRotatingFileSinkError = Schema.is(RotatingFileSinkError);\n\nconst isFileNotFoundError = (cause: unknown): cause is NodeJS.ErrnoException =>\n  cause instanceof Error && \"code\" in cause && cause.code === \"ENOENT\";\n\nexport class RotatingFileSink {\n  private readonly filePath: string;\n  private readonly maxBytes: number;\n  private readonly maxFiles: number;\n  private readonly throwOnError: boolean;\n  private currentSize = 0;\n\n  constructor(options: RotatingFileSinkOptions) {\n    if (options.maxBytes < 1) {\n      throw new RotatingFileSinkConfigurationError({\n        option: \"maxBytes\",\n        received: options.maxBytes,\n        minimum: 1,\n      });\n    }\n    if (options.maxFiles < 1) {\n      throw new RotatingFileSinkConfigurationError({\n        option: \"maxFiles\",\n        received: options.maxFiles,\n        minimum: 1,\n      });\n    }\n\n    this.filePath = options.filePath;\n    this.maxBytes = options.maxBytes;\n    this.maxFiles = options.maxFiles;\n    this.throwOnError = options.throwOnError ?? false;\n\n    try {\n      NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });\n    } catch (cause) {\n      throw new RotatingFileSinkError({\n        operation: \"initialize\",\n        filePath: this.filePath,\n        cause,\n      });\n    }\n    this.pruneOverflowBackups();\n    this.currentSize = this.readCurrentSize();\n  }\n\n  write(chunk: string | Buffer): void {\n    const buffer = typeof chunk === \"string\" ? Buffer.from(chunk) : chunk;\n    if (buffer.length === 0) return;\n\n    try {\n      if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {\n        this.rotate();\n      }\n\n      NodeFS.appendFileSync(this.filePath, buffer);\n      this.currentSize += buffer.length;\n    } catch (cause) {\n      if (isRotatingFileSinkError(cause)) {\n        throw cause;\n      }\n      if (this.throwOnError) {\n        throw new RotatingFileSinkError({\n          operation: \"write\",\n          filePath: this.filePath,\n          cause,\n        });\n      }\n      this.currentSize = this.readCurrentSize();\n    }\n  }\n\n  private rotate(): void {\n    try {\n      const oldest = this.withSuffix(this.maxFiles);\n      if (NodeFS.existsSync(oldest)) {\n        NodeFS.rmSync(oldest, { force: true });\n      }\n\n      for (let index = this.maxFiles - 1; index >= 1; index -= 1) {\n        const source = this.withSuffix(index);\n        const target = this.withSuffix(index + 1);\n        if (NodeFS.existsSync(source)) {\n          NodeFS.renameSync(source, target);\n        }\n      }\n\n      if (NodeFS.existsSync(this.filePath)) {\n        NodeFS.renameSync(this.filePath, this.withSuffix(1));\n      }\n\n      this.currentSize = 0;\n    } catch (cause) {\n      if (this.throwOnError) {\n        throw new RotatingFileSinkError({\n          operation: \"rotate\",\n          filePath: this.filePath,\n          cause,\n        });\n      }\n      this.currentSize = this.readCurrentSize();\n    }\n  }\n\n  private pruneOverflowBackups(): void {\n    try {\n      const dir = NodePath.dirname(this.filePath);\n      const baseName = NodePath.basename(this.filePath);\n      for (const entry of NodeFS.readdirSync(dir)) {\n        if (!entry.startsWith(`${baseName}.`)) continue;\n        const suffix = Number(entry.slice(baseName.length + 1));\n        if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;\n        NodeFS.rmSync(NodePath.join(dir, entry), { force: true });\n      }\n    } catch (cause) {\n      if (this.throwOnError) {\n        throw new RotatingFileSinkError({\n          operation: \"prune\",\n          filePath: this.filePath,\n          cause,\n        });\n      }\n    }\n  }\n\n  private readCurrentSize(): number {\n    try {\n      return NodeFS.statSync(this.filePath).size;\n    } catch (cause) {\n      if (isFileNotFoundError(cause)) {\n        return 0;\n      }\n      throw new RotatingFileSinkError({\n        operation: \"read\",\n        filePath: this.filePath,\n        cause,\n      });\n    }\n  }\n\n  private withSuffix(index: number): string {\n    return `${this.filePath}.${index}`;\n  }\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport type * as Exit from \"effect/Exit\";\nimport * as ExitRuntime from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\nimport { OtlpResource, OtlpTracer } from \"effect/unstable/observability\";\n\nimport { RotatingFileSink } from \"./logging.ts\";\n\nconst FLUSH_BUFFER_THRESHOLD = 256;\nconst textEncoder = new TextEncoder();\n\nexport type TraceAttributes = Readonly<Record<string, unknown>>;\n\nexport interface TraceRecordEvent {\n  readonly name: string;\n  readonly timeUnixNano: string;\n  readonly attributes: Readonly<Record<string, unknown>>;\n}\n\nexport interface TraceRecordLink {\n  readonly traceId: string;\n  readonly spanId: string;\n  readonly attributes: Readonly<Record<string, unknown>>;\n}\n\ninterface BaseTraceRecord {\n  readonly name: string;\n  readonly kind: string;\n  readonly traceId: string;\n  readonly spanId: string;\n  readonly parentSpanId?: string;\n  readonly sampled: boolean;\n  readonly startTimeUnixNano: string;\n  readonly endTimeUnixNano: string;\n  readonly durationMs: number;\n  readonly attributes: Readonly<Record<string, unknown>>;\n  readonly events: ReadonlyArray<TraceRecordEvent>;\n  readonly links: ReadonlyArray<TraceRecordLink>;\n}\n\nexport interface EffectTraceRecord extends BaseTraceRecord {\n  readonly type: \"effect-span\";\n  readonly exit:\n    | {\n        readonly _tag: \"Success\";\n      }\n    | {\n        readonly _tag: \"Interrupted\";\n        readonly cause: string;\n      }\n    | {\n        readonly _tag: \"Failure\";\n        readonly cause: string;\n      };\n}\n\nexport interface OtlpTraceRecord extends BaseTraceRecord {\n  readonly type: \"otlp-span\";\n  readonly resourceAttributes: Readonly<Record<string, unknown>>;\n  readonly scope: Readonly<{\n    readonly name?: string;\n    readonly version?: string;\n    readonly attributes: Readonly<Record<string, unknown>>;\n  }>;\n  readonly status?:\n    | {\n        readonly code?: string;\n        readonly message?: string;\n      }\n    | undefined;\n}\n\nexport type TraceRecord = EffectTraceRecord | OtlpTraceRecord;\n\nfunction isStructuralTag(value: unknown): value is string {\n  return (\n    typeof value === \"string\" &&\n    value.length > 0 &&\n    value.length <= 128 &&\n    /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)\n  );\n}\n\nexport function errorTag(error: unknown): string {\n  try {\n    if (typeof error === \"object\" && error !== null && \"_tag\" in error) {\n      return isStructuralTag(error._tag) ? error._tag : \"TaggedError\";\n    }\n    if (error instanceof Error) {\n      return isStructuralTag(error.name) ? error.name : \"Error\";\n    }\n  } catch {\n    return \"UnknownError\";\n  }\n  return typeof error;\n}\n\nexport function causeErrorTag(cause: Cause.Cause<unknown>): string {\n  const failure = Cause.findErrorOption(cause);\n  if (Option.isSome(failure)) {\n    return errorTag(failure.value);\n  }\n  return cause.reasons[0]?._tag ?? \"Empty\";\n}\n\nexport interface TraceSinkOptions {\n  readonly filePath: string;\n  readonly maxBytes: number;\n  readonly maxFiles: number;\n  readonly batchWindowMs: number;\n  readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;\n}\n\nexport interface TraceSinkFlushStats {\n  readonly logicalWriteBytes: number;\n  readonly count: number;\n  readonly durationMs: number;\n}\n\nexport interface TraceSink {\n  readonly filePath: string;\n  push: (record: TraceRecord) => void;\n  flush: Effect.Effect<void>;\n  close: () => Effect.Effect<void>;\n}\n\nexport interface LocalFileTracerOptions extends TraceSinkOptions {\n  readonly delegate?: Tracer.Tracer;\n  readonly sink?: TraceSink;\n}\n\ntype OtlpSpan = OtlpTracer.ScopeSpan[\"spans\"][number];\ntype OtlpSpanEvent = OtlpSpan[\"events\"][number];\ntype OtlpSpanLink = OtlpSpan[\"links\"][number];\ntype OtlpSpanStatus = OtlpSpan[\"status\"];\n\ninterface SerializableSpan {\n  readonly name: string;\n  readonly traceId: string;\n  readonly spanId: string;\n  readonly parent: Option.Option<Tracer.AnySpan>;\n  readonly status: Tracer.SpanStatus;\n  readonly sampled: boolean;\n  readonly kind: Tracer.SpanKind;\n  readonly attributes: ReadonlyMap<string, unknown>;\n  readonly links: ReadonlyArray<Tracer.SpanLink>;\n  readonly events: ReadonlyArray<\n    readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]\n  >;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction markSeen(value: object, seen: WeakSet<object>): boolean {\n  if (seen.has(value)) {\n    return true;\n  }\n  seen.add(value);\n  return false;\n}\n\nfunction normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {\n  if (\n    value === null ||\n    value === undefined ||\n    typeof value === \"string\" ||\n    typeof value === \"number\" ||\n    typeof value === \"boolean\"\n  ) {\n    return value ?? null;\n  }\n  if (typeof value === \"bigint\") {\n    return value.toString();\n  }\n  if (value instanceof Date) {\n    return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n  }\n  if (value instanceof Error) {\n    return {\n      name: value.name,\n      message: value.message,\n      ...(value.stack ? { stack: value.stack } : {}),\n    };\n  }\n  if (Array.isArray(value)) {\n    if (markSeen(value, seen)) {\n      return \"[Circular]\";\n    }\n    return value.map((entry) => normalizeJsonValue(entry, seen));\n  }\n  if (value instanceof Map) {\n    if (markSeen(value, seen)) {\n      return \"[Circular]\";\n    }\n    return Object.fromEntries(\n      Array.from(value.entries(), ([key, entryValue]) => [\n        String(key),\n        normalizeJsonValue(entryValue, seen),\n      ]),\n    );\n  }\n  if (value instanceof Set) {\n    if (markSeen(value, seen)) {\n      return \"[Circular]\";\n    }\n    return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));\n  }\n  if (!isPlainObject(value)) {\n    return String(value);\n  }\n  if (markSeen(value, seen)) {\n    return \"[Circular]\";\n  }\n  return Object.fromEntries(\n    Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),\n  );\n}\n\nexport function compactTraceAttributes(\n  attributes: Readonly<Record<string, unknown>>,\n): TraceAttributes {\n  const entries: Array<[string, unknown]> = [];\n  for (const [key, value] of Object.entries(attributes)) {\n    if (value !== undefined) {\n      entries.push([key, normalizeJsonValue(value)]);\n    }\n  }\n  return Object.fromEntries(entries);\n}\n\nfunction formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord[\"exit\"] {\n  if (ExitRuntime.isSuccess(exit)) {\n    return { _tag: \"Success\" };\n  }\n  if (Cause.hasInterruptsOnly(exit.cause)) {\n    return {\n      _tag: \"Interrupted\",\n      cause: Cause.pretty(exit.cause),\n    };\n  }\n  return {\n    _tag: \"Failure\",\n    cause: Cause.pretty(exit.cause),\n  };\n}\n\nexport function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {\n  const status = span.status as Extract<Tracer.SpanStatus, { _tag: \"Ended\" }>;\n  const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;\n\n  return {\n    type: \"effect-span\",\n    name: span.name,\n    traceId: span.traceId,\n    spanId: span.spanId,\n    ...(parentSpanId ? { parentSpanId } : {}),\n    sampled: span.sampled,\n    kind: span.kind,\n    startTimeUnixNano: String(status.startTime),\n    endTimeUnixNano: String(status.endTime),\n    durationMs: Number(status.endTime - status.startTime) / 1_000_000,\n    attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),\n    events: span.events.map(([name, startTime, attributes]) => ({\n      name,\n      timeUnixNano: String(startTime),\n      attributes: compactTraceAttributes(attributes),\n    })),\n    links: span.links.map((link) => ({\n      traceId: link.span.traceId,\n      spanId: link.span.spanId,\n      attributes: compactTraceAttributes(link.attributes),\n    })),\n    exit: formatTraceExit(status.exit),\n  };\n}\n\nexport const makeTraceSink = Effect.fn(\"makeTraceSink\")(function* (options: TraceSinkOptions) {\n  const sink = new RotatingFileSink({\n    filePath: options.filePath,\n    maxBytes: options.maxBytes,\n    maxFiles: options.maxFiles,\n    throwOnError: true,\n  });\n\n  let buffer: Array<string> = [];\n  let pendingFlushStats: TraceSinkFlushStats = {\n    logicalWriteBytes: 0,\n    count: 0,\n    durationMs: 0,\n  };\n\n  const flushUnsafe = () => {\n    if (buffer.length === 0) {\n      return;\n    }\n\n    const records = buffer;\n    buffer = [];\n    let persistedCount = 0;\n\n    while (persistedCount < records.length) {\n      const firstRecordBytes = textEncoder.encode(records[persistedCount]).byteLength;\n      if (firstRecordBytes > options.maxBytes) {\n        persistedCount += 1;\n        continue;\n      }\n\n      let nextIndex = persistedCount + 1;\n      let chunkBytes = firstRecordBytes;\n      while (nextIndex < records.length) {\n        const nextRecordBytes = textEncoder.encode(records[nextIndex]).byteLength;\n        if (chunkBytes + nextRecordBytes > options.maxBytes) break;\n        chunkBytes += nextRecordBytes;\n        nextIndex += 1;\n      }\n\n      const chunk = records.slice(persistedCount, nextIndex).join(\"\");\n      const startedAt = performance.now();\n      try {\n        sink.write(chunk);\n      } catch {\n        buffer.unshift(...records.slice(persistedCount));\n        return;\n      }\n      pendingFlushStats = {\n        logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,\n        count: pendingFlushStats.count + nextIndex - persistedCount,\n        durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),\n      };\n      persistedCount = nextIndex;\n    }\n  };\n\n  const flush = Effect.sync(() => {\n    flushUnsafe();\n    const stats = pendingFlushStats;\n    pendingFlushStats = {\n      logicalWriteBytes: 0,\n      count: 0,\n      durationMs: 0,\n    };\n    return stats;\n  }).pipe(\n    Effect.flatMap((stats) =>\n      stats.count > 0 && options.onFlush ? options.onFlush(stats).pipe(Effect.ignore) : Effect.void,\n    ),\n    Effect.withTracerEnabled(false),\n  );\n\n  yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));\n  yield* Effect.forkScoped(\n    Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),\n  );\n\n  return {\n    filePath: options.filePath,\n    push(record) {\n      try {\n        buffer.push(`${JSON.stringify(record)}\\n`);\n        if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {\n          flushUnsafe();\n        }\n      } catch {\n        return;\n      }\n    },\n    flush,\n    close: () => flush,\n  } satisfies TraceSink;\n});\n\nclass LocalFileSpan implements Tracer.Span {\n  readonly _tag = \"Span\";\n  readonly name: string;\n  readonly spanId: string;\n  readonly traceId: string;\n  readonly parent: Option.Option<Tracer.AnySpan>;\n  readonly annotations: Tracer.Span[\"annotations\"];\n  readonly links: Array<Tracer.SpanLink>;\n  readonly sampled: boolean;\n  readonly kind: Tracer.SpanKind;\n\n  status: Tracer.SpanStatus;\n  attributes: Map<string, unknown>;\n  events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;\n  private readonly delegate: Tracer.Span;\n  private readonly push: (record: EffectTraceRecord) => void;\n\n  constructor(\n    options: Parameters<Tracer.Tracer[\"span\"]>[0],\n    delegate: Tracer.Span,\n    push: (record: EffectTraceRecord) => void,\n  ) {\n    this.delegate = delegate;\n    this.push = push;\n    this.name = delegate.name;\n    this.spanId = delegate.spanId;\n    this.traceId = delegate.traceId;\n    this.parent = options.parent;\n    this.annotations = options.annotations;\n    this.links = [...options.links];\n    this.sampled = delegate.sampled;\n    this.kind = delegate.kind;\n    this.status = {\n      _tag: \"Started\",\n      startTime: options.startTime,\n    };\n    this.attributes = new Map();\n    this.events = [];\n  }\n\n  end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n    this.status = {\n      _tag: \"Ended\",\n      startTime: this.status.startTime,\n      endTime,\n      exit,\n    };\n    this.delegate.end(endTime, exit);\n\n    if (this.sampled) {\n      this.push(spanToTraceRecord(this));\n    }\n  }\n\n  attribute(key: string, value: unknown): void {\n    this.attributes.set(key, value);\n    this.delegate.attribute(key, value);\n  }\n\n  event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {\n    const nextAttributes = attributes ?? {};\n    this.events.push([name, startTime, nextAttributes]);\n    this.delegate.event(name, startTime, nextAttributes);\n  }\n\n  addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {\n    this.links.push(...links);\n    this.delegate.addLinks(links);\n  }\n}\n\nexport const makeLocalFileTracer = Effect.fn(\"makeLocalFileTracer\")(function* (\n  options: LocalFileTracerOptions,\n) {\n  const sink =\n    options.sink ??\n    (yield* makeTraceSink({\n      filePath: options.filePath,\n      maxBytes: options.maxBytes,\n      maxFiles: options.maxFiles,\n      batchWindowMs: options.batchWindowMs,\n      ...(options.onFlush ? { onFlush: options.onFlush } : {}),\n    }));\n\n  const delegate =\n    options.delegate ??\n    Tracer.make({\n      span: (spanOptions) => new Tracer.NativeSpan(spanOptions),\n    });\n\n  return Tracer.make({\n    span(spanOptions) {\n      return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);\n    },\n    ...(delegate.context ? { context: delegate.context } : {}),\n  });\n});\n\nconst SPAN_KIND_MAP: Record<number, OtlpTraceRecord[\"kind\"]> = {\n  1: \"internal\",\n  2: \"server\",\n  3: \"client\",\n  4: \"producer\",\n  5: \"consumer\",\n};\n\nexport function decodeOtlpTraceRecords(\n  payload: OtlpTracer.TraceData,\n): ReadonlyArray<OtlpTraceRecord> {\n  const records: Array<OtlpTraceRecord> = [];\n\n  for (const resourceSpan of payload.resourceSpans) {\n    const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);\n\n    for (const scopeSpan of resourceSpan.scopeSpans) {\n      for (const span of scopeSpan.spans) {\n        records.push(\n          otlpSpanToTraceRecord({\n            resourceAttributes,\n            scopeAttributes: decodeAttributes(\n              \"attributes\" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)\n                ? scopeSpan.scope.attributes\n                : [],\n            ),\n            scopeName: scopeSpan.scope.name,\n            scopeVersion:\n              \"version\" in scopeSpan.scope && typeof scopeSpan.scope.version === \"string\"\n                ? scopeSpan.scope.version\n                : undefined,\n            span,\n          }),\n        );\n      }\n    }\n  }\n\n  return records;\n}\n\nfunction otlpSpanToTraceRecord(input: {\n  readonly resourceAttributes: Readonly<Record<string, unknown>>;\n  readonly scopeAttributes: Readonly<Record<string, unknown>>;\n  readonly scopeName: string | undefined;\n  readonly scopeVersion: string | undefined;\n  readonly span: OtlpSpan;\n}): OtlpTraceRecord {\n  return {\n    type: \"otlp-span\",\n    name: input.span.name,\n    traceId: input.span.traceId,\n    spanId: input.span.spanId,\n    ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),\n    sampled: true,\n    kind: normalizeSpanKind(input.span.kind),\n    startTimeUnixNano: input.span.startTimeUnixNano,\n    endTimeUnixNano: input.span.endTimeUnixNano,\n    durationMs:\n      Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /\n      1_000_000,\n    attributes: decodeAttributes(input.span.attributes),\n    resourceAttributes: input.resourceAttributes,\n    scope: {\n      ...(input.scopeName ? { name: input.scopeName } : {}),\n      ...(input.scopeVersion ? { version: input.scopeVersion } : {}),\n      attributes: input.scopeAttributes,\n    },\n    events: decodeEvents(input.span.events),\n    links: decodeLinks(input.span.links),\n    status: decodeStatus(input.span.status),\n  };\n}\n\nfunction decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord[\"status\"] {\n  const code = String(input.code);\n  const message = input.message;\n\n  return {\n    code,\n    ...(message ? { message } : {}),\n  };\n}\n\nfunction decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {\n  return input.map((current) => ({\n    name: current.name,\n    timeUnixNano: current.timeUnixNano,\n    attributes: decodeAttributes(current.attributes),\n  }));\n}\n\nfunction decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {\n  return input.flatMap((current) => {\n    const traceId = current.traceId;\n    const spanId = current.spanId;\n    return {\n      traceId,\n      spanId,\n      attributes: decodeAttributes(current.attributes),\n    };\n  });\n}\n\nfunction decodeAttributes(\n  input: ReadonlyArray<OtlpResource.KeyValue>,\n): Readonly<Record<string, unknown>> {\n  const entries: Record<string, unknown> = {};\n\n  for (const attribute of input) {\n    entries[attribute.key] = decodeValue(attribute.value);\n  }\n\n  return compactTraceAttributes(entries);\n}\n\nfunction decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {\n  if (input == null) {\n    return null;\n  }\n  if (\"stringValue\" in input) {\n    return input.stringValue;\n  }\n  if (\"boolValue\" in input) {\n    return input.boolValue;\n  }\n  if (\"intValue\" in input) {\n    return input.intValue;\n  }\n  if (\"doubleValue\" in input) {\n    return input.doubleValue;\n  }\n  if (\"bytesValue\" in input) {\n    return input.bytesValue;\n  }\n  if (input.arrayValue) {\n    return input.arrayValue.values.map((entry) => decodeValue(entry));\n  }\n  if (input.kvlistValue) {\n    return decodeAttributes(input.kvlistValue.values);\n  }\n  return null;\n}\n\nfunction normalizeSpanKind(input: number): OtlpTraceRecord[\"kind\"] {\n  return SPAN_KIND_MAP[input] || \"internal\";\n}\n\nfunction parseBigInt(input: string): bigint {\n  try {\n    return BigInt(input);\n  } catch {\n    return 0n;\n  }\n}\n","export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [\".htm\", \".html\", \".pdf\"] as const;\n\nexport const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [\n  \".avif\",\n  \".gif\",\n  \".ico\",\n  \".jpeg\",\n  \".jpg\",\n  \".png\",\n  \".svg\",\n  \".webp\",\n] as const;\n\nfunction hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {\n  const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? \"\";\n  return extensions.some((extension) => pathWithoutQuery.endsWith(extension));\n}\n\nexport function isWorkspaceBrowserPreviewPath(path: string): boolean {\n  return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);\n}\n\nexport function isWorkspaceImagePreviewPath(path: string): boolean {\n  return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);\n}\n\nexport function isWorkspacePreviewEntryPath(path: string): boolean {\n  return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);\n}\n","export const PROJECT_FAVICON_FALLBACK_MARKER = \"project-favicon-missing\";\n\nexport function getProjectFaviconCacheKey(\n  environmentId: string,\n  workspaceRoot: string,\n  url: string,\n) {\n  let revision = url;\n\n  try {\n    const pathname = new URL(url, \"https://t3.invalid\").pathname;\n    revision = pathname.slice(pathname.lastIndexOf(\"/\") + 1);\n  } catch {\n    // Keep the full value as a safe fallback for malformed URLs.\n  }\n\n  return JSON.stringify([environmentId, workspaceRoot, revision]);\n}\n\nexport function isProjectFaviconFallbackUrl(url: string | null | undefined): boolean {\n  if (!url) return false;\n\n  try {\n    const pathname = new URL(url, \"https://t3.invalid\").pathname;\n    return pathname.slice(pathname.lastIndexOf(\"/\") + 1) === PROJECT_FAVICON_FALLBACK_MARKER;\n  } catch {\n    return false;\n  }\n}\n","import * as Schema from \"effect/Schema\";\n\nimport { T3ProjectFile, T3_PROJECT_FILE_SCHEMA_URL } from \"@t3tools/contracts\";\n\nimport { fromLenientJson } from \"./schemaJson.ts\";\n\n/**\n * Codec between the raw `t3.json` file contents (lenient JSONC string) and the\n * decoded {@link T3ProjectFile}.\n */\nexport const T3ProjectFileFromJson = fromLenientJson(T3ProjectFile);\n\n/**\n * Build the publishable JSON Schema document for `t3.json` (draft 2020-12).\n *\n * Served from the marketing site at {@link T3_PROJECT_FILE_SCHEMA_URL} so\n * editors get LSP support via a `$schema` reference.\n */\nexport function buildT3ProjectFileJsonSchema(): Record<string, unknown> {\n  const document = Schema.toJsonSchemaDocument(T3ProjectFile);\n  const jsonSchema: Record<string, unknown> = {\n    $schema: \"https://json-schema.org/draft/2020-12/schema\",\n    $id: T3_PROJECT_FILE_SCHEMA_URL,\n    ...document.schema,\n  };\n  if (document.definitions && Object.keys(document.definitions).length > 0) {\n    jsonSchema.$defs = document.definitions;\n  }\n  return jsonSchema;\n}\n","/**\n * T3ProjectFileLoader - Effect service that loads the checked-in `t3.json`\n * project file from a workspace root.\n *\n * Loading is best-effort: a missing file resolves to `Option.none`, and\n * unreadable or invalid files are logged and treated as absent so callers\n * can fall back to their defaults.\n *\n * @module T3ProjectFileLoader\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport { T3_PROJECT_FILE_NAME, type T3ProjectFile } from \"@t3tools/contracts\";\nimport { T3ProjectFileFromJson } from \"@t3tools/shared/t3ProjectFile\";\n\nconst decodeT3ProjectFileJson = Schema.decodeEffect(T3ProjectFileFromJson);\n\nexport class T3ProjectFileLoadError extends Schema.TaggedErrorClass<T3ProjectFileLoadError>()(\n  \"T3ProjectFileLoadError\",\n  {\n    operation: Schema.Literals([\"read\", \"decode\"]),\n    workspaceRoot: Schema.String,\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} ${T3_PROJECT_FILE_NAME} at ${this.filePath}.`;\n  }\n}\n\n/** Service tag for t3.json project file loading. */\nexport class T3ProjectFileLoader extends Context.Service<\n  T3ProjectFileLoader,\n  {\n    /**\n     * Load and decode `t3.json` at the workspace root.\n     *\n     * Never fails: missing, unreadable, or invalid files resolve to\n     * `Option.none` (invalid files are logged as warnings).\n     */\n    readonly load: (workspaceRoot: string) => Effect.Effect<Option.Option<T3ProjectFile>>;\n  }\n>()(\"t3/project/T3ProjectFileLoader\") {}\n\nconst logT3ProjectFileLoadError = (error: T3ProjectFileLoadError) =>\n  Effect.logWarning(error).pipe(\n    Effect.annotateLogs({\n      operation: error.operation,\n      workspaceRoot: error.workspaceRoot,\n      filePath: error.filePath,\n      errorTag: error._tag,\n    }),\n  );\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const load: T3ProjectFileLoader[\"Service\"][\"load\"] = Effect.fn(\"T3ProjectFileLoader.load\")(\n    function* (workspaceRoot) {\n      const filePath = path.join(workspaceRoot, T3_PROJECT_FILE_NAME);\n      const raw = yield* fileSystem.readFileString(filePath).pipe(\n        Effect.map(Option.some),\n        Effect.catchTags({\n          PlatformError: (error) =>\n            error.reason._tag === \"NotFound\"\n              ? Effect.succeed(Option.none<string>())\n              : logT3ProjectFileLoadError(\n                  new T3ProjectFileLoadError({\n                    operation: \"read\",\n                    workspaceRoot,\n                    filePath,\n                    cause: error,\n                  }),\n                ).pipe(Effect.as(Option.none<string>())),\n        }),\n      );\n      if (Option.isNone(raw)) {\n        return Option.none<T3ProjectFile>();\n      }\n      return yield* decodeT3ProjectFileJson(raw.value).pipe(\n        Effect.map(Option.some),\n        Effect.catchTags({\n          SchemaError: (error) =>\n            logT3ProjectFileLoadError(\n              new T3ProjectFileLoadError({\n                operation: \"decode\",\n                workspaceRoot,\n                filePath,\n                cause: error,\n              }),\n            ).pipe(Effect.as(Option.none<T3ProjectFile>())),\n        }),\n      );\n    },\n  );\n\n  return T3ProjectFileLoader.of({ load });\n});\n\nexport const layer = Layer.effect(T3ProjectFileLoader, make);\n","/**\n * ProjectFaviconResolver - Effect service contract for project icon discovery.\n *\n * Resolves a representative favicon or app icon file for a workspace by\n * checking common file locations and project source metadata.\n *\n * @module ProjectFaviconResolver\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\nimport * as T3ProjectFileLoader from \"./T3ProjectFileLoader.ts\";\n\n// Well-known favicon paths checked in order.\nconst FAVICON_CANDIDATES = [\n  \"favicon.svg\",\n  \"favicon.ico\",\n  \"favicon.png\",\n  \"public/favicon.svg\",\n  \"public/favicon.ico\",\n  \"public/favicon.png\",\n  \"app/favicon.ico\",\n  \"app/favicon.png\",\n  \"app/icon.svg\",\n  \"app/icon.png\",\n  \"app/icon.ico\",\n  \"src/favicon.ico\",\n  \"src/favicon.svg\",\n  \"src/app/favicon.ico\",\n  \"src/app/icon.svg\",\n  \"src/app/icon.png\",\n  \"assets/icon.svg\",\n  \"assets/icon.png\",\n  \"assets/logo.svg\",\n  \"assets/logo.png\",\n  \".idea/icon.svg\",\n] as const;\n\n// Files that may contain a <link rel=\"icon\"> or icon metadata declaration.\nconst ICON_SOURCE_FILES = [\n  \"index.html\",\n  \"public/index.html\",\n  \"app/routes/__root.tsx\",\n  \"src/routes/__root.tsx\",\n  \"app/root.tsx\",\n  \"src/root.tsx\",\n  \"src/index.html\",\n] as const;\n\n// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.\nconst LINK_ICON_HTML_RE =\n  /<link\\b(?=[^>]*\\brel=[\"'](?:icon|shortcut icon)[\"'])(?=[^>]*\\bhref=[\"']([^\"'?]+))[^>]*>/i;\nconst LINK_ICON_OBJ_RE =\n  /(?=[^}]*\\brel\\s*:\\s*[\"'](?:icon|shortcut icon)[\"'])(?=[^}]*\\bhref\\s*:\\s*[\"']([^\"'?]+))[^}]*/i;\n\nexport class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(\n  \"ProjectFaviconResolutionError\",\n  {\n    operation: Schema.Literals([\n      \"normalize-workspace\",\n      \"resolve-path\",\n      \"stat-candidate\",\n      \"read-source\",\n    ]),\n    workspaceRoot: Schema.String,\n    relativePath: Schema.optional(Schema.String),\n    absolutePath: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;\n  }\n}\n\n/** Service tag for project favicon resolution. */\nexport class ProjectFaviconResolver extends Context.Service<\n  ProjectFaviconResolver,\n  {\n    /**\n     * Resolve a favicon or icon file path for the provided workspace root.\n     *\n     * Returns `null` when no candidate icon file can be found.\n     */\n    readonly resolvePath: (\n      cwd: string,\n    ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;\n  }\n>()(\"t3/project/ProjectFaviconResolver\") {}\n\nfunction extractIconHref(source: string): string | null {\n  const htmlMatch = source.match(LINK_ICON_HTML_RE);\n  if (htmlMatch?.[1]) return htmlMatch[1];\n  const objMatch = source.match(LINK_ICON_OBJ_RE);\n  if (objMatch?.[1]) return objMatch[1];\n  return null;\n}\n\nconst optionOnNotFound = <A, R>(\n  effect: Effect.Effect<A, PlatformError.PlatformError, R>,\n): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>\n  effect.pipe(\n    Effect.map(Option.some),\n    Effect.catchTags({\n      PlatformError: (error) =>\n        error.reason._tag === \"NotFound\" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),\n    }),\n  );\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;\n\n  const resolveIconHref = (href: string): ReadonlyArray<string> => {\n    const clean = href.replace(/^\\//, \"\");\n    return [path.join(\"public\", clean), clean];\n  };\n\n  const findExistingFile = Effect.fn(\"ProjectFaviconResolver.findExistingFile\")(function* (\n    projectCwd: string,\n    relativeCandidates: ReadonlyArray<string>,\n  ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {\n    for (const relativePath of relativeCandidates) {\n      const candidate = yield* workspacePaths\n        .resolveRelativePathWithinRoot({\n          workspaceRoot: projectCwd,\n          relativePath,\n        })\n        .pipe(\n          Effect.map(Option.some),\n          Effect.catchTags({\n            WorkspacePathOutsideRootError: () =>\n              Effect.succeed(\n                Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),\n              ),\n          }),\n        );\n      if (Option.isNone(candidate)) {\n        continue;\n      }\n      const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProjectFaviconResolutionError({\n              operation: \"stat-candidate\",\n              workspaceRoot: projectCwd,\n              relativePath,\n              absolutePath: candidate.value.absolutePath,\n              cause,\n            }),\n        ),\n      );\n      if (Option.isSome(stats) && stats.value.type === \"File\") {\n        return candidate.value.absolutePath;\n      }\n    }\n    return null;\n  });\n\n  const resolvePath: ProjectFaviconResolver[\"Service\"][\"resolvePath\"] = Effect.fn(\n    \"ProjectFaviconResolver.resolvePath\",\n  )(function* (cwd) {\n    const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProjectFaviconResolutionError({\n            operation: \"normalize-workspace\",\n            workspaceRoot: cwd,\n            cause,\n          }),\n      ),\n    );\n    // A t3.json iconPath takes precedence over the well-known locations.\n    const projectFile = yield* projectFileLoader.load(projectCwd);\n    if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {\n      const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);\n      if (existing) {\n        return existing;\n      }\n    }\n\n    for (const candidate of FAVICON_CANDIDATES) {\n      const existing = yield* findExistingFile(projectCwd, [candidate]);\n      if (existing) {\n        return existing;\n      }\n    }\n\n    for (const sourceFile of ICON_SOURCE_FILES) {\n      const sourcePath = yield* workspacePaths\n        .resolveRelativePathWithinRoot({\n          workspaceRoot: projectCwd,\n          relativePath: sourceFile,\n        })\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProjectFaviconResolutionError({\n                operation: \"resolve-path\",\n                workspaceRoot: projectCwd,\n                relativePath: sourceFile,\n                cause,\n              }),\n          ),\n        );\n      const source = yield* optionOnNotFound(\n        fileSystem.readFileString(sourcePath.absolutePath),\n      ).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProjectFaviconResolutionError({\n              operation: \"read-source\",\n              workspaceRoot: projectCwd,\n              relativePath: sourceFile,\n              absolutePath: sourcePath.absolutePath,\n              cause,\n            }),\n        ),\n      );\n      if (Option.isNone(source)) {\n        continue;\n      }\n      const href = extractIconHref(source.value);\n      if (!href) {\n        continue;\n      }\n      const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));\n      if (existing) {\n        return existing;\n      }\n    }\n\n    return null;\n  });\n\n  return ProjectFaviconResolver.of({ resolvePath });\n});\n\nexport const layer = Layer.effect(ProjectFaviconResolver, make);\n","import type { AssetResource } from \"@t3tools/contracts\";\nimport {\n  AssetAttachmentNotFoundError,\n  AssetPreviewTypeValidationError,\n  AssetProjectFaviconInspectionError,\n  AssetProjectFaviconNotFoundError,\n  AssetProjectFaviconResolutionError,\n  AssetSigningKeyLoadError,\n  AssetWorkspaceAssetInspectionError,\n  AssetWorkspaceAssetNotFoundError,\n  AssetWorkspaceContextNotFoundError,\n  AssetWorkspacePathValidationError,\n  AssetWorkspaceResolutionError,\n  AssetWorkspaceRootNormalizationError,\n} from \"@t3tools/contracts\";\nimport {\n  isWorkspaceImagePreviewPath,\n  isWorkspacePreviewEntryPath,\n  WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,\n  WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,\n} from \"@t3tools/shared/filePreview\";\nimport { PROJECT_FAVICON_FALLBACK_MARKER } from \"@t3tools/shared/projectFavicon\";\nimport * as Clock from \"effect/Clock\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport {\n  base64UrlDecodeUtf8,\n  base64UrlEncode,\n  signPayload,\n  timingSafeEqualBase64Url,\n} from \"../auth/utils.ts\";\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport { resolveAttachmentPathById } from \"../attachmentStore.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport * as ProjectFaviconResolver from \"../project/ProjectFaviconResolver.ts\";\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\n\nexport const ASSET_ROUTE_PREFIX = \"/api/assets\";\n\nconst SIGNING_SECRET_NAME = \"asset-access-signing-key\";\nconst ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;\nconst PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;\nconst PROJECT_FAVICON_VERSION_PREFIX = \"v\";\nconst PREVIEW_ASSET_EXTENSIONS = new Set([\n  ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,\n  ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,\n  \".css\",\n  \".js\",\n  \".mjs\",\n  \".otf\",\n  \".ttf\",\n  \".woff\",\n  \".woff2\",\n]);\n\nconst AssetClaimsSchema = Schema.Union([\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"workspace-file\"),\n    workspaceRoot: Schema.String,\n    baseRelativePath: Schema.String,\n    expiresAt: Schema.Number,\n  }),\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"workspace-file-exact\"),\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    expiresAt: Schema.Number,\n  }),\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"attachment\"),\n    attachmentId: Schema.String,\n    expiresAt: Schema.Number,\n  }),\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"project-favicon\"),\n    workspaceRoot: Schema.String,\n    relativePath: Schema.NullOr(Schema.String),\n    expiresAt: Schema.Number,\n  }),\n]);\ntype AssetClaims = typeof AssetClaimsSchema.Type;\n\nconst AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);\nconst decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);\nconst encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);\n\nexport type ResolvedAsset = { readonly kind: \"file\"; readonly path: string };\n\nfunction decodeClaims(encodedPayload: string): AssetClaims | null {\n  try {\n    return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));\n  } catch {\n    return null;\n  }\n}\n\nfunction decodeRelativePath(value: string): string | null {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return null;\n  }\n}\n\nconst optionOnNotFound = <A, R>(\n  effect: Effect.Effect<A, PlatformError.PlatformError, R>,\n): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>\n  effect.pipe(\n    Effect.map(Option.some),\n    Effect.catchTags({\n      PlatformError: (error) =>\n        error.reason._tag === \"NotFound\" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),\n    }),\n  );\n\nconst resolveCanonicalWorkspaceFile = Effect.fn(\"AssetAccess.resolveCanonicalWorkspaceFile\")(\n  function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {\n    const fileSystem = yield* FileSystem.FileSystem;\n    const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n    const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(\n      Effect.map(Option.some),\n      Effect.catchTags({\n        WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),\n      }),\n    );\n    if (Option.isNone(resolved)) return null;\n\n    const [canonicalRoot, canonicalFile] = yield* Effect.all([\n      optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),\n      optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),\n    ]);\n    if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;\n\n    const path = yield* Path.Path;\n    const relative = path.relative(canonicalRoot.value, canonicalFile.value);\n    if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) return null;\n\n    const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));\n    return Option.isSome(info) && info.value.type === \"File\" ? canonicalFile.value : null;\n  },\n);\n\nconst resolveCanonicalWorkspaceFileForRequest = (input: {\n  readonly workspaceRoot: string;\n  readonly relativePath: string;\n}) =>\n  resolveCanonicalWorkspaceFile(input).pipe(\n    Effect.tapError((cause) =>\n      Effect.logError(\"Failed to resolve canonical asset path.\", {\n        workspaceRoot: input.workspaceRoot,\n        relativePath: input.relativePath,\n        cause,\n      }),\n    ),\n    Effect.orElseSucceed(() => null),\n  );\n\nexport const issueAssetUrl = Effect.fn(\"AssetAccess.issueAssetUrl\")(function* (input: {\n  readonly resource: AssetResource;\n  readonly workspaceRoot?: string;\n}) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;\n  let claims: AssetClaims;\n  let fileName: string;\n\n  switch (input.resource._tag) {\n    case \"workspace-file\": {\n      if (!input.workspaceRoot) {\n        return yield* new AssetWorkspaceContextNotFoundError({\n          resource: input.resource,\n        });\n      }\n      const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceRootNormalizationError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      const relativePath = path.isAbsolute(input.resource.path)\n        ? path.relative(workspaceRoot, input.resource.path)\n        : input.resource.path;\n      const resolved = yield* workspacePaths\n        .resolveRelativePathWithinRoot({ workspaceRoot, relativePath })\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new AssetWorkspacePathValidationError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        );\n      if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {\n        return yield* new AssetPreviewTypeValidationError({\n          resource: input.resource,\n        });\n      }\n      const canonicalFile = yield* resolveCanonicalWorkspaceFile({\n        workspaceRoot,\n        relativePath: resolved.relativePath,\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceAssetInspectionError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      if (!canonicalFile) {\n        return yield* new AssetWorkspaceAssetNotFoundError({\n          resource: input.resource,\n        });\n      }\n      const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceResolutionError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      claims = isWorkspaceImagePreviewPath(resolved.relativePath)\n        ? {\n            version: 1,\n            kind: \"workspace-file-exact\",\n            workspaceRoot: canonicalWorkspaceRoot,\n            relativePath: resolved.relativePath,\n            expiresAt,\n          }\n        : {\n            version: 1,\n            kind: \"workspace-file\",\n            workspaceRoot: canonicalWorkspaceRoot,\n            baseRelativePath: path.dirname(resolved.relativePath),\n            expiresAt,\n          };\n      fileName = path.basename(resolved.relativePath);\n      break;\n    }\n    case \"attachment\": {\n      const config = yield* ServerConfig.ServerConfig;\n      const attachmentPath = resolveAttachmentPathById({\n        attachmentsDir: config.attachmentsDir,\n        attachmentId: input.resource.attachmentId,\n      });\n      if (!attachmentPath) {\n        return yield* new AssetAttachmentNotFoundError({\n          resource: input.resource,\n        });\n      }\n      claims = {\n        version: 1,\n        kind: \"attachment\",\n        attachmentId: input.resource.attachmentId,\n        expiresAt,\n      };\n      fileName = path.basename(attachmentPath);\n      break;\n    }\n    case \"project-favicon\": {\n      const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceRootNormalizationError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;\n      const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetProjectFaviconResolutionError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;\n      const canonicalFaviconPath = relativePath\n        ? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(\n            Effect.mapError(\n              (cause) =>\n                new AssetProjectFaviconInspectionError({\n                  resource: input.resource,\n                  cause,\n                }),\n            ),\n          )\n        : null;\n      if (relativePath && !canonicalFaviconPath) {\n        return yield* new AssetProjectFaviconNotFoundError({\n          resource: input.resource,\n        });\n      }\n      claims = {\n        version: 1,\n        kind: \"project-favicon\",\n        workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(\n          Effect.mapError(\n            (cause) =>\n              new AssetWorkspaceResolutionError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        ),\n        relativePath,\n        expiresAt,\n      };\n      if (relativePath && canonicalFaviconPath) {\n        const crypto = yield* Crypto.Crypto;\n        const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(\n          Effect.mapError(\n            (cause) =>\n              new AssetProjectFaviconInspectionError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        );\n        const revision = yield* crypto.digest(\"SHA-256\", faviconBytes).pipe(\n          Effect.map(Encoding.encodeHex),\n          Effect.mapError(\n            (cause) =>\n              new AssetProjectFaviconInspectionError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        );\n        fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(relativePath)}`;\n      } else {\n        fileName = PROJECT_FAVICON_FALLBACK_MARKER;\n      }\n      break;\n    }\n  }\n\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(\n    Effect.mapError(\n      (cause) =>\n        new AssetSigningKeyLoadError({\n          resource: input.resource,\n          cause,\n        }),\n    ),\n  );\n  if (claims.kind === \"project-favicon\") {\n    const issuedAt = yield* Clock.currentTimeMillis;\n    expiresAt =\n      (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *\n      PROJECT_FAVICON_TOKEN_BUCKET_MS;\n    claims = { ...claims, expiresAt };\n  }\n  const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));\n  const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;\n  return {\n    relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,\n    expiresAt,\n  };\n});\n\nexport const resolveAsset = Effect.fn(\"AssetAccess.resolveAsset\")(function* (\n  token: string,\n  relativePath: string,\n) {\n  const [encodedPayload, signature] = token.split(\".\");\n  if (!encodedPayload || !signature) return null;\n\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(\n    Effect.tapError((cause) => Effect.logError(\"Failed to load the asset signing key.\", { cause })),\n    Effect.orElseSucceed(() => null),\n  );\n  if (!signingSecret) return null;\n  if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;\n\n  const claims = decodeClaims(encodedPayload);\n  if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;\n\n  if (claims.kind === \"attachment\") {\n    const config = yield* ServerConfig.ServerConfig;\n    const attachmentPath = resolveAttachmentPathById({\n      attachmentsDir: config.attachmentsDir,\n      attachmentId: claims.attachmentId,\n    });\n    if (!attachmentPath) return null;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(\n      Effect.tapError((cause) =>\n        Effect.logError(\"Failed to inspect attachment asset.\", {\n          attachmentId: claims.attachmentId,\n          path: attachmentPath,\n          cause,\n        }),\n      ),\n      Effect.orElseSucceed(() => Option.none()),\n    );\n    return Option.isSome(info) && info.value.type === \"File\"\n      ? ({ kind: \"file\", path: attachmentPath } satisfies ResolvedAsset)\n      : null;\n  }\n\n  if (claims.kind === \"project-favicon\") {\n    if (claims.relativePath === null) return null;\n    const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({\n      workspaceRoot: claims.workspaceRoot,\n      relativePath: claims.relativePath,\n    });\n    return faviconPath ? ({ kind: \"file\", path: faviconPath } satisfies ResolvedAsset) : null;\n  }\n\n  const decodedPath = decodeRelativePath(relativePath);\n  if (decodedPath === null) return null;\n  const path = yield* Path.Path;\n  if (claims.kind === \"workspace-file-exact\") {\n    if (decodedPath !== path.basename(claims.relativePath)) return null;\n    const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({\n      workspaceRoot: claims.workspaceRoot,\n      relativePath: claims.relativePath,\n    });\n    return exactWorkspaceFile\n      ? ({ kind: \"file\", path: exactWorkspaceFile } satisfies ResolvedAsset)\n      : null;\n  }\n  const segments = decodedPath.split(/[\\\\/]/);\n  if (\n    decodedPath.length === 0 ||\n    decodedPath.includes(\"\\0\") ||\n    segments.some((segment) => segment === \".\" || segment === \"..\" || segment.startsWith(\".\")) ||\n    !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())\n  ) {\n    return null;\n  }\n  const joinedRelativePath =\n    claims.baseRelativePath === \".\" ? decodedPath : path.join(claims.baseRelativePath, decodedPath);\n  const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({\n    workspaceRoot: claims.workspaceRoot,\n    relativePath: joinedRelativePath,\n  });\n  return workspaceFile ? ({ kind: \"file\", path: workspaceFile } satisfies ResolvedAsset) : null;\n});\n","import type { TraceRecord, TraceSink } from \"@t3tools/shared/observability\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nexport class BrowserTraceCollector extends Context.Service<\n  BrowserTraceCollector,\n  {\n    readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;\n  }\n>()(\"t3/observability/BrowserTraceCollector\") {}\n\nexport const make = (sink: TraceSink): BrowserTraceCollector[\"Service\"] =>\n  BrowserTraceCollector.of({\n    record: (records) =>\n      Effect.sync(() => {\n        for (const record of records) {\n          sink.push(record);\n        }\n      }),\n  });\n\nexport const layer = (sink: TraceSink) => Layer.succeed(BrowserTraceCollector, make(sink));\n","import {\n  AuthAccessReadScope,\n  AuthAccessWriteScope,\n  AuthStandardClientScopes,\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n  AuthReviewWriteScope,\n  AuthTerminalOperateScope,\n  EnvironmentAuthInvalidError,\n  type EnvironmentAuthInvalidReason,\n  EnvironmentHttpApi,\n  EnvironmentInternalError,\n  type EnvironmentInternalErrorReason,\n  EnvironmentOperationForbiddenError,\n  EnvironmentRequestInvalidError,\n  type EnvironmentRequestInvalidReason,\n  EnvironmentResourceNotFoundError,\n  type EnvironmentResourceNotFoundReason,\n  EnvironmentScopeRequiredError,\n  EnvironmentAuthenticatedAuth,\n  EnvironmentAuthenticatedPrincipal,\n} from \"@t3tools/contracts\";\nimport type { AuthEnvironmentScope } from \"@t3tools/contracts\";\nimport { parseAllowedOAuthScope } from \"@t3tools/shared/oauthScope\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Cookies from \"effect/unstable/http/Cookies\";\nimport * as HttpEffect from \"effect/unstable/http/HttpEffect\";\nimport { HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport * as EnvironmentAuth from \"./EnvironmentAuth.ts\";\nimport * as SessionStore from \"./SessionStore.ts\";\nimport { deriveAuthClientMetadata } from \"./utils.ts\";\nimport { verifyRequestDpopProof } from \"./dpop.ts\";\n\nconst CREDENTIAL_RESPONSE_HEADERS = {\n  \"cache-control\": \"no-store\",\n  pragma: \"no-cache\",\n} as const;\n\nconst appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>\n  Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),\n);\n\nconst appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>\n  Effect.succeed(HttpServerResponse.setHeader(response, \"www-authenticate\", \"DPoP\")),\n);\n\nconst appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) =>\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const usesDpop =\n      (request.originalUrl.startsWith(\"/oauth/token\") && request.headers.dpop !== undefined) ||\n      request.headers.authorization?.startsWith(\"DPoP \") === true;\n    if (usesDpop) {\n      yield* appendDpopChallengeHeader;\n    }\n    return yield* error;\n  });\n\nexport const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(\n  Effect.map((span) => span.traceId),\n  Effect.orElseSucceed(() => \"unavailable\"),\n);\n\nexport function annotateEnvironmentRequest(endpoint: string) {\n  return Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const url = HttpServerRequest.toURL(request);\n    const traceId = yield* currentEnvironmentTraceId;\n\n    yield* Effect.addFinalizer((exit) =>\n      exit._tag === \"Failure\"\n        ? Effect.logWarning(\"environment api request failed\", {\n            endpoint,\n            traceId,\n            errorTag: causeErrorTag(exit.cause),\n            cause: exit.cause,\n          })\n        : Effect.void,\n    );\n    yield* Effect.annotateLogsScoped({ \"environment.endpoint\": endpoint, traceId });\n    yield* Effect.annotateCurrentSpan({\n      \"environment.endpoint\": endpoint,\n      \"http.request.method\": request.method,\n      \"url.path\": url._tag === \"Some\" ? url.value.pathname : \"unknown\",\n    });\n  });\n}\n\nexport function failEnvironmentAuthInvalid(reason: EnvironmentAuthInvalidReason) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(new EnvironmentAuthInvalidError({ code: \"auth_invalid\", reason, traceId })),\n    ),\n  );\n}\n\nexport function failEnvironmentInvalidRequest(reason: EnvironmentRequestInvalidReason) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(new EnvironmentRequestInvalidError({ code: \"invalid_request\", reason, traceId })),\n    ),\n  );\n}\n\nexport function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(\n        new EnvironmentScopeRequiredError({\n          code: \"insufficient_scope\",\n          requiredScope,\n          traceId,\n        }),\n      ),\n    ),\n  );\n}\n\nfunction failEnvironmentOperationForbidden(reason: \"current_session_revoke_not_allowed\") {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(\n        new EnvironmentOperationForbiddenError({\n          code: \"operation_forbidden\",\n          reason,\n          traceId,\n        }),\n      ),\n    ),\n  );\n}\n\nexport function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(new EnvironmentResourceNotFoundError({ code: \"not_found\", reason, traceId })),\n    ),\n  );\n}\n\nexport function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {\n  return Effect.gen(function* () {\n    const traceId = yield* currentEnvironmentTraceId;\n    if (error !== undefined) {\n      yield* Effect.logError(\"environment api operation failed\", {\n        reason,\n        traceId,\n        cause: error,\n      });\n    }\n    return yield* new EnvironmentInternalError({ code: \"internal_error\", reason, traceId });\n  });\n}\n\nexport const requireEnvironmentScope = Effect.fn(\"environment.auth.requireScope\")(function* (\n  scope: AuthEnvironmentScope,\n) {\n  const session = yield* EnvironmentAuthenticatedPrincipal;\n  if (!session.scopes.has(scope)) {\n    return yield* failEnvironmentScopeRequired(scope);\n  }\n  return session;\n});\n\nexport const environmentAuthenticatedAuthLayer = Layer.effect(\n  EnvironmentAuthenticatedAuth,\n  Effect.gen(function* () {\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    return (httpEffect) =>\n      Effect.gen(function* () {\n        const request = yield* HttpServerRequest.HttpServerRequest;\n        const session = yield* serverAuth.authenticateHttpRequest(request).pipe(\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"internal_error\", error),\n          ),\n        );\n        return yield* httpEffect.pipe(\n          Effect.provideService(EnvironmentAuthenticatedPrincipal, {\n            ...session,\n            scopes: new Set(session.scopes),\n          }),\n        );\n      }).pipe(Effect.catchTag(\"EnvironmentAuthInvalidError\", appendDpopChallengeOnUnauthorized));\n  }),\n);\n\nexport const authHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"auth\",\n  Effect.fnUntraced(function* (handlers) {\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const sessions = yield* SessionStore.SessionStore;\n\n    return handlers\n      .handle(\n        \"session\",\n        Effect.fn(\"environment.auth.session\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const request = yield* HttpServerRequest.HttpServerRequest;\n            return yield* serverAuth.getSessionState(request);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"internal_error\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"browserSession\",\n        Effect.fn(\"environment.auth.browserSession\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const request = yield* HttpServerRequest.HttpServerRequest;\n            const result = yield* serverAuth.createBrowserSession(\n              args.payload.credential,\n              deriveAuthClientMetadata({ request }),\n            );\n            const sessionCookies = yield* Effect.fromResult(\n              Cookies.set(Cookies.empty, sessions.cookieName, result.sessionToken, {\n                expires: DateTime.toDate(result.response.expiresAt),\n                httpOnly: true,\n                path: \"/\",\n                sameSite: \"lax\",\n              }),\n            ).pipe(Effect.catch(() => failEnvironmentInternal(\"browser_session_cookie_failed\")));\n\n            yield* HttpEffect.appendPreResponseHandler((_request, response) =>\n              Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),\n            );\n            yield* appendCredentialResponseHeaders;\n            return result.response;\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"browser_session_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"token\",\n        Effect.fn(\"environment.auth.token\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const request = yield* HttpServerRequest.HttpServerRequest;\n            const requestedScopes =\n              args.payload.scope === undefined\n                ? undefined\n                : parseAllowedOAuthScope({\n                    value: args.payload.scope,\n                    allowedScopes: new Set<AuthEnvironmentScope>([\n                      AuthOrchestrationReadScope,\n                      AuthOrchestrationOperateScope,\n                      AuthTerminalOperateScope,\n                      AuthReviewWriteScope,\n                      AuthAccessReadScope,\n                      AuthAccessWriteScope,\n                      AuthRelayReadScope,\n                      AuthRelayWriteScope,\n                    ]),\n                  });\n            if (requestedScopes === null) {\n              return yield* failEnvironmentInvalidRequest(\"invalid_scope\");\n            }\n            const proofKeyThumbprint = args.headers.dpop\n              ? yield* verifyRequestDpopProof({ request }).pipe(\n                  Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>\n                    appendDpopChallengeHeader.pipe(\n                      Effect.andThen(failEnvironmentAuthInvalid(\"invalid_credential\")),\n                    ),\n                  ),\n                  Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n                    failEnvironmentInternal(\"access_token_issuance_failed\", error),\n                  ),\n                )\n              : undefined;\n            yield* appendCredentialResponseHeaders;\n            return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(\n              args.payload.subject_token,\n              requestedScopes,\n              deriveAuthClientMetadata({\n                request,\n                presented: {\n                  ...(args.payload.client_label ? { label: args.payload.client_label } : {}),\n                  ...(args.payload.client_device_type\n                    ? { deviceType: args.payload.client_device_type }\n                    : {}),\n                  ...(args.payload.client_os ? { os: args.payload.client_os } : {}),\n                },\n              }),\n              proofKeyThumbprint ? { proofKeyThumbprint } : undefined,\n            );\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>\n            failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"access_token_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"webSocketTicket\",\n        Effect.fn(\"environment.auth.webSocketTicket\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* EnvironmentAuthenticatedPrincipal;\n            yield* appendCredentialResponseHeaders;\n            return yield* serverAuth.issueWebSocketTicket(session);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"websocket_ticket_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"pairingCredential\",\n        Effect.fn(\"environment.auth.pairingCredential\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;\n            if (\n              delegatedScopes.length === 0 ||\n              new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length\n            ) {\n              return yield* failEnvironmentInvalidRequest(\"invalid_scope\");\n            }\n            for (const delegatedScope of delegatedScopes) {\n              if (!session.scopes.has(delegatedScope)) {\n                return yield* failEnvironmentScopeRequired(delegatedScope);\n              }\n            }\n            return yield* serverAuth.issuePairingCredential(args.payload);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"pairing_credential_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"pairingLinks\",\n        Effect.fn(\"environment.auth.pairingLinks\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            yield* requireEnvironmentScope(AuthAccessReadScope);\n            return yield* serverAuth.listPairingLinks();\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"pairing_links_load_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"revokePairingLink\",\n        Effect.fn(\"environment.auth.revokePairingLink\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const revoked = yield* serverAuth.revokePairingLink(args.payload.id);\n            return { revoked };\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"pairing_link_revoke_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"clients\",\n        Effect.fn(\"environment.auth.clients\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessReadScope);\n            return yield* serverAuth.listClientSessions(session.sessionId);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"client_sessions_load_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"revokeClient\",\n        Effect.fn(\"environment.auth.revokeClient\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const revoked = yield* serverAuth.revokeClientSession(\n              session.sessionId,\n              args.payload.sessionId,\n            );\n            return { revoked };\n          },\n          Effect.catchTag(\"ServerAuthForbiddenOperationError\", () =>\n            failEnvironmentOperationForbidden(\"current_session_revoke_not_allowed\"),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"client_session_revoke_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"revokeOtherClients\",\n        Effect.fn(\"environment.auth.revokeOtherClients\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);\n            return { revokedCount };\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"client_session_revoke_failed\", error),\n          ),\n        ),\n      );\n  }),\n);\n","export const browserApiCorsAllowedMethods = [\"GET\", \"POST\", \"OPTIONS\"] as const;\nexport const browserApiCorsAllowedHeaders = [\n  \"authorization\",\n  \"b3\",\n  \"traceparent\",\n  \"content-type\",\n  \"dpop\",\n] as const;\n\nexport const browserApiCorsHeaders = {\n  \"access-control-allow-origin\": \"*\",\n  \"access-control-allow-methods\": browserApiCorsAllowedMethods.join(\", \"),\n  \"access-control-allow-headers\": browserApiCorsAllowedHeaders.join(\", \"),\n} as const;\n","import Mime from \"@effect/platform-node/Mime\";\nimport {\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  EnvironmentHttpApi,\n} from \"@t3tools/contracts\";\nimport { isDevProxiedPath } from \"@t3tools/shared/devProxy\";\nimport { decodeOtlpTraceRecords } from \"@t3tools/shared/observability\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport { cast } from \"effect/Function\";\nimport {\n  HttpBody,\n  HttpClient,\n  HttpClientResponse,\n  HttpMiddleware,\n  HttpRouter,\n  HttpServerResponse,\n  HttpServerRequest,\n  HttpServerRespondable,\n} from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\nimport { OtlpTracer } from \"effect/unstable/observability\";\n\nimport * as ServerConfig from \"./config.ts\";\nimport { ASSET_ROUTE_PREFIX, resolveAsset } from \"./assets/AssetAccess.ts\";\nimport * as BrowserTraceCollector from \"./observability/BrowserTraceCollector.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport {\n  annotateEnvironmentRequest,\n  failEnvironmentScopeRequired,\n  failEnvironmentAuthInvalid,\n  failEnvironmentInternal,\n} from \"./auth/http.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from \"./httpCors.ts\";\n\nconst OTLP_TRACES_PROXY_PATH = \"/api/observability/v1/traces\";\nconst LOOPBACK_HOSTNAMES = new Set([\"127.0.0.1\", \"::1\", \"localhost\"]);\nconst DESKTOP_RENDERER_ORIGINS = [\"t3code://app\", \"t3code-dev://app\"];\nexport const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {\n  global: true,\n});\n\nexport const browserApiCorsLayer = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    const devOrigin = config.devUrl?.origin;\n    // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be\n    // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.\n    //\n    // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second\n    // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies\n    // through Vite and is same-origin (no preflight at all), so this is a\n    // safety net for the desktop renderer and any direct-to-backend caller.\n    return HttpRouter.cors({\n      ...(devOrigin\n        ? {\n            allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],\n            credentials: true,\n          }\n        : {}),\n      allowedMethods: browserApiCorsAllowedMethods,\n      allowedHeaders: browserApiCorsAllowedHeaders,\n      maxAge: 600,\n    });\n  }),\n);\n\nexport function isLoopbackHostname(hostname: string): boolean {\n  const normalizedHostname = hostname\n    .trim()\n    .toLowerCase()\n    .replace(/^\\[(.*)\\]$/, \"$1\");\n  return LOOPBACK_HOSTNAMES.has(normalizedHostname);\n}\n\nexport function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {\n  const redirectUrl = new URL(devUrl.toString());\n  redirectUrl.pathname = requestUrl.pathname;\n  redirectUrl.search = requestUrl.search;\n  redirectUrl.hash = requestUrl.hash;\n  return redirectUrl.toString();\n}\n\nconst authenticateRawRouteWithScope = (\n  scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,\n) =>\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const session = yield* serverAuth.authenticateHttpRequest(request).pipe(\n      Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n        failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n      ),\n      Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n        failEnvironmentInternal(\"internal_error\", error),\n      ),\n    );\n    if (!session.scopes.includes(scope)) {\n      return yield* failEnvironmentScopeRequired(scope);\n    }\n  });\n\nexport const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"metadata\",\n  Effect.fnUntraced(function* (handlers) {\n    const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;\n    return handlers.handle(\n      \"descriptor\",\n      Effect.fn(\"environment.metadata.descriptor\")(function* (args) {\n        yield* annotateEnvironmentRequest(args.endpoint.name);\n        return yield* serverEnvironment.getDescriptor;\n      }),\n    );\n  }),\n);\n\nclass DecodeOtlpTraceRecordsError extends Data.TaggedError(\"DecodeOtlpTraceRecordsError\")<{\n  readonly cause: unknown;\n  readonly bodyJson: OtlpTracer.TraceData;\n}> {}\n\nexport const otlpTracesProxyRouteLayer = HttpRouter.add(\n  \"POST\",\n  OTLP_TRACES_PROXY_PATH,\n  Effect.gen(function* () {\n    yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const config = yield* ServerConfig.ServerConfig;\n    const otlpTracesUrl = config.otlpTracesUrl;\n    const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;\n    const httpClient = yield* HttpClient.HttpClient;\n    const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);\n\n    yield* Effect.try({\n      try: () => decodeOtlpTraceRecords(bodyJson),\n      catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),\n    }).pipe(\n      Effect.flatMap((records) => browserTraceCollector.record(records)),\n      Effect.catch((cause) =>\n        Effect.logWarning(\"Failed to decode browser OTLP traces\", {\n          cause,\n          bodyJson,\n        }),\n      ),\n    );\n\n    if (otlpTracesUrl === undefined) {\n      return HttpServerResponse.empty({ status: 204 });\n    }\n\n    return yield* httpClient\n      .post(otlpTracesUrl, {\n        body: HttpBody.jsonUnsafe(bodyJson),\n      })\n      .pipe(\n        Effect.flatMap(HttpClientResponse.filterStatusOk),\n        Effect.as(HttpServerResponse.empty({ status: 204 })),\n        Effect.tapError((cause) =>\n          Effect.logWarning(\"Failed to export browser OTLP traces\", {\n            cause,\n            otlpTracesUrl,\n          }),\n        ),\n        Effect.orElseSucceed(() =>\n          HttpServerResponse.text(\"Trace export failed.\", { status: 502 }),\n        ),\n      );\n  }).pipe(\n    Effect.catchTags({\n      EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,\n      EnvironmentInternalError: HttpServerRespondable.toResponse,\n      EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,\n    }),\n  ),\n);\n\nexport const assetRouteLayer = HttpRouter.add(\n  \"GET\",\n  `${ASSET_ROUTE_PREFIX}/*`,\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const url = HttpServerRequest.toURL(request);\n    if (Option.isNone(url)) {\n      return HttpServerResponse.text(\"Bad Request\", { status: 400 });\n    }\n\n    const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);\n    const separatorIndex = suffix.indexOf(\"/\");\n    if (separatorIndex <= 0) {\n      return HttpServerResponse.text(\"Not Found\", { status: 404 });\n    }\n\n    const asset = yield* resolveAsset(\n      suffix.slice(0, separatorIndex),\n      suffix.slice(separatorIndex + 1),\n    );\n    if (!asset) {\n      return HttpServerResponse.text(\"Not Found\", { status: 404 });\n    }\n    return yield* HttpServerResponse.file(asset.path, {\n      status: 200,\n      headers: {\n        \"Cache-Control\": \"private, max-age=3600\",\n        \"X-Content-Type-Options\": \"nosniff\",\n      },\n    }).pipe(\n      Effect.orElseSucceed(() => HttpServerResponse.text(\"Internal Server Error\", { status: 500 })),\n    );\n  }),\n);\n\nexport const staticAndDevRouteLayer = HttpRouter.add(\n  \"GET\",\n  \"*\",\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const url = HttpServerRequest.toURL(request);\n\n    if (Option.isNone(url)) {\n      return HttpServerResponse.text(\"Bad Request\", { status: 400 });\n    }\n\n    const config = yield* ServerConfig.ServerConfig;\n    if (config.devUrl && isDevProxiedPath(url.value.pathname)) {\n      return HttpServerResponse.text(\"Not Found\", { status: 404 });\n    }\n\n    if (config.devUrl && isLoopbackHostname(url.value.hostname)) {\n      return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {\n        status: 302,\n      });\n    }\n\n    const staticDir =\n      config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);\n    if (!staticDir) {\n      return HttpServerResponse.text(\"No static directory configured and no dev URL set.\", {\n        status: 503,\n      });\n    }\n\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const staticRoot = path.resolve(staticDir);\n    const staticRequestPath = url.value.pathname === \"/\" ? \"/index.html\" : url.value.pathname;\n    const rawStaticRelativePath = staticRequestPath.replace(/^[/\\\\]+/, \"\");\n    const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(\"..\");\n    const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\\\]+/, \"\");\n    const hasPathTraversalSegment = staticRelativePath.startsWith(\"..\");\n    if (\n      staticRelativePath.length === 0 ||\n      hasRawLeadingParentSegment ||\n      hasPathTraversalSegment ||\n      staticRelativePath.includes(\"\\0\")\n    ) {\n      return HttpServerResponse.text(\"Invalid static file path\", { status: 400 });\n    }\n\n    const isWithinStaticRoot = (candidate: string) =>\n      candidate === staticRoot ||\n      candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);\n\n    let filePath = path.resolve(staticRoot, staticRelativePath);\n    if (!isWithinStaticRoot(filePath)) {\n      return HttpServerResponse.text(\"Invalid static file path\", { status: 400 });\n    }\n\n    const ext = path.extname(filePath);\n    if (!ext) {\n      filePath = path.resolve(filePath, \"index.html\");\n      if (!isWithinStaticRoot(filePath)) {\n        return HttpServerResponse.text(\"Invalid static file path\", { status: 400 });\n      }\n    }\n\n    const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));\n    if (!fileInfo || fileInfo.type !== \"File\") {\n      const indexPath = path.resolve(staticRoot, \"index.html\");\n      const indexData = yield* fileSystem\n        .readFile(indexPath)\n        .pipe(Effect.orElseSucceed(() => null));\n      if (!indexData) {\n        return HttpServerResponse.text(\"Not Found\", { status: 404 });\n      }\n      return HttpServerResponse.uint8Array(indexData, {\n        status: 200,\n        contentType: \"text/html; charset=utf-8\",\n      });\n    }\n\n    const contentType = Mime.getType(filePath) ?? \"application/octet-stream\";\n    const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));\n    if (!data) {\n      return HttpServerResponse.text(\"Internal Server Error\", { status: 500 });\n    }\n\n    return HttpServerResponse.uint8Array(data, {\n      status: 200,\n      contentType,\n    });\n  }),\n);\n","/**\n * Marks encoded worker message fields that should move through `postMessage` as\n * transfer-list entries.\n *\n * Worker messages still pass through schema encoding and structured clone, but\n * schemas wrapped with `schema` can also report backing resources such as\n * `ArrayBuffer`, `ImageData.data.buffer`, or `MessagePort` to a `Collector`.\n * Worker platforms then pass the collected values as the transfer list for the\n * same `postMessage` call, avoiding copies for large payloads and ports.\n *\n * @since 4.0.0\n */\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport { dual } from \"../../Function.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as SchemaGetter from \"../../SchemaGetter.js\";\n/**\n * Service for collecting `Transferable` objects while encoding worker messages\n * so they can be passed to `postMessage` transfer lists.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Collector extends /*#__PURE__*/Context.Service()(\"effect/workers/Transferable/Collector\") {}\n/**\n * Creates a mutable `Collector` service directly, exposing unsafe synchronous\n * methods for reading, adding, and clearing collected transferables.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeCollectorUnsafe = () => {\n  let tranferables = [];\n  const unsafeAddAll = transfers => {\n    tranferables.push(...transfers);\n  };\n  const unsafeRead = () => tranferables;\n  const unsafeClear = () => {\n    const prev = tranferables;\n    tranferables = [];\n    return prev;\n  };\n  return Collector.of({\n    addAllUnsafe: unsafeAddAll,\n    addAll: transferables => Effect.sync(() => unsafeAddAll(transferables)),\n    readUnsafe: unsafeRead,\n    read: Effect.sync(unsafeRead),\n    clearUnsafe: unsafeClear,\n    clear: Effect.sync(unsafeClear)\n  });\n};\n/**\n * Effect that creates a fresh `Collector` service for accumulating\n * transferables.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeCollector = /*#__PURE__*/Effect.sync(makeCollectorUnsafe);\n/**\n * Adds transferables to the current `Collector` when one is present in the\n * context, and does nothing otherwise.\n *\n * @category accessors\n * @since 4.0.0\n */\nexport const addAll = tranferables => Effect.contextWith(services => {\n  const collector = Context.getOrUndefined(services, Collector);\n  if (!collector) return Effect.void;\n  collector.addAllUnsafe(tranferables);\n  return Effect.void;\n});\n/**\n * Creates a schema getter that records transferables derived from a value in\n * the current `Collector` while passing the value through unchanged.\n *\n * @category getters\n * @since 4.0.0\n */\nexport const getterAddAll = f => SchemaGetter.transformOrFail(e => Effect.contextWith(services => {\n  const collector = Context.getOrUndefined(services, Collector);\n  if (!collector) return Effect.succeed(e);\n  collector.addAllUnsafe(f(e));\n  return Effect.succeed(e);\n}));\n/**\n * Wraps a schema so encoding records transferables selected from the encoded\n * value, enabling worker messages to populate a `postMessage` transfer list.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const schema = /*#__PURE__*/dual(2, (self, f) => self.annotate({\n  toCodecJson: () => passthroughLink\n}).pipe(Schema.decode({\n  decode: SchemaGetter.passthrough(),\n  encode: getterAddAll(f)\n})));\nconst passthroughLink = /*#__PURE__*/Schema.link()(Schema.Any, {\n  decode: /*#__PURE__*/SchemaGetter.passthrough(),\n  encode: /*#__PURE__*/SchemaGetter.passthrough()\n});\n/**\n * Schema for transferring `ImageData` values with their pixel data buffer.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const ImageData = /*#__PURE__*/schema(Schema.Any, _ => [_.data.buffer]);\n/**\n * Schema for transferring `MessagePort` values as transferable objects.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const MessagePort = /*#__PURE__*/schema(Schema.Any, _ => [_]);\n/**\n * Schema for transferring `Uint8Array` values with their backing buffer.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const Uint8Array = /*#__PURE__*/schema(Schema.Uint8Array, _ => [_.buffer]);\n//# sourceMappingURL=Transferable.js.map","/**\n * Typed error model for worker APIs.\n *\n * This module defines the `WorkerError` wrapper, the reason variants for spawn,\n * send, receive, and unknown worker failures, a schema union for those reasons,\n * and a guard for recognizing worker errors at runtime.\n *\n * @since 4.0.0\n */\nimport { hasProperty } from \"../../Predicate.js\";\nimport * as Schema from \"../../Schema.js\";\nconst TypeId = \"~effect/workers/WorkerError\";\n/**\n * Returns `true` when a value is a `WorkerError`.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isWorkerError = u => hasProperty(u, TypeId);\n/**\n * Worker error reason for failures while spawning or setting up a worker.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class WorkerSpawnError extends /*#__PURE__*/Schema.ErrorClass(\"effect/workers/WorkerError/WorkerSpawnError\")({\n  _tag: /*#__PURE__*/Schema.tag(\"WorkerSpawnError\"),\n  message: Schema.String,\n  cause: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Defect())\n}) {}\n/**\n * Worker error reason for failures while sending a message to a worker.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class WorkerSendError extends /*#__PURE__*/Schema.ErrorClass(\"effect/workers/WorkerError/WorkerSendError\")({\n  _tag: /*#__PURE__*/Schema.tag(\"WorkerSendError\"),\n  message: Schema.String,\n  cause: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Defect())\n}) {}\n/**\n * Worker error reason for failures while receiving or handling a message from a\n * worker.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class WorkerReceiveError extends /*#__PURE__*/Schema.ErrorClass(\"effect/workers/WorkerError/WorkerReceiveError\")({\n  _tag: /*#__PURE__*/Schema.tag(\"WorkerReceiveError\"),\n  message: Schema.String,\n  cause: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Defect())\n}) {}\n/**\n * Worker error reason for an unclassified worker failure.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class WorkerUnknownError extends /*#__PURE__*/Schema.ErrorClass(\"effect/workers/WorkerError/WorkerUnknownError\")({\n  _tag: /*#__PURE__*/Schema.tag(\"WorkerUnknownError\"),\n  message: Schema.String,\n  cause: /*#__PURE__*/Schema.optional(/*#__PURE__*/Schema.Defect())\n}) {}\n/**\n * Schema for decoding and encoding all supported worker error reason variants.\n *\n * @category schemas\n * @since 4.0.0\n */\nexport const WorkerErrorReason = /*#__PURE__*/Schema.Union([WorkerSpawnError, WorkerSendError, WorkerReceiveError, WorkerUnknownError]);\n/**\n * Error raised by worker APIs, wrapping a specific `WorkerErrorReason` and\n * exposing its message and cause.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class WorkerError extends /*#__PURE__*/Schema.ErrorClass(TypeId)({\n  _tag: /*#__PURE__*/Schema.tag(\"WorkerError\"),\n  reason: WorkerErrorReason\n}) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props) {\n    super({\n      ...props,\n      cause: props.reason.cause\n    });\n  }\n  /**\n   * Marks this value as a worker error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  get message() {\n    return this.reason.message;\n  }\n}\n//# sourceMappingURL=WorkerError.js.map","/**\n * Client-side protocol failures reported by unstable RPC transports.\n *\n * `RpcClientError` is the error type generated clients use when a call fails\n * before a remote handler can return its declared typed error. Its `reason`\n * covers built-in transport failures from HTTP, sockets, and workers, plus\n * `RpcClientDefect` values for malformed or incompatible protocol data.\n *\n * @since 4.0.0\n */\nimport * as Schema from \"../../Schema.js\";\nimport { HttpClientErrorSchema } from \"../http/HttpClientError.js\";\nimport { SocketErrorReason } from \"../socket/Socket.js\";\nimport { WorkerErrorReason } from \"../workers/WorkerError.js\";\nconst TypeId = \"~effect/rpc/RpcClientError\";\n/**\n * Represents a client-side RPC defect, such as a protocol violation or\n * decoding failure, with a message and original cause.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class RpcClientDefect extends /*#__PURE__*/Schema.ErrorClass(\"effect/rpc/RpcClientError/RpcClientDefect\")({\n  _tag: /*#__PURE__*/Schema.tag(\"RpcClientDefect\"),\n  message: Schema.String,\n  cause: /*#__PURE__*/Schema.Defect()\n}) {}\n/**\n * Error wrapper for RPC client failures, including worker, socket, HTTP client,\n * and client protocol defect failures.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class RpcClientError extends /*#__PURE__*/Schema.ErrorClass(TypeId)({\n  _tag: /*#__PURE__*/Schema.tag(\"RpcClientError\"),\n  reason: /*#__PURE__*/Schema.Union([WorkerErrorReason, SocketErrorReason, HttpClientErrorSchema, RpcClientDefect])\n}) {\n  /**\n   * Marks this value as an RPC client error for runtime guards.\n   *\n   * @since 4.0.0\n   */\n  [TypeId] = TypeId;\n  get message() {\n    return `${this.reason._tag}: ${this.reason.message}`;\n  }\n}\n//# sourceMappingURL=RpcClientError.js.map","import * as Schema from \"../../Schema.js\";\n/**\n * Converts a bigint or string request id into the branded `RequestId` type.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const RequestId = id => id;\n/**\n * Represents the reusable `Eof` message value.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const constEof = {\n  _tag: \"Eof\"\n};\n/**\n * Represents the reusable `Ping` message value.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const constPing = {\n  _tag: \"Ping\"\n};\n/**\n * The brand identifier used by the `ResponseId` type.\n *\n * @category type IDs\n * @since 4.0.0\n */\nexport const ResponseIdTypeId = \"~effect//rpc/RpcServer/ResponseId\";\nconst encodeDefect = /*#__PURE__*/Schema.encodeSync(/*#__PURE__*/Schema.Defect());\n/**\n * Creates an encoded terminal response for a request whose exit is a defect\n * encoded with `Schema.Defect()`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ResponseExitDieEncoded = options => ({\n  _tag: \"Exit\",\n  requestId: options.requestId,\n  exit: {\n    _tag: \"Failure\",\n    cause: [{\n      _tag: \"Die\",\n      defect: encodeDefect(options.defect)\n    }]\n  }\n});\n/**\n * Creates a transport-encoded defect response by encoding the input with\n * `Schema.Defect()`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const ResponseDefectEncoded = input => ({\n  _tag: \"Defect\",\n  defect: encodeDefect(input)\n});\n/**\n * Represents the reusable `Pong` message value.\n *\n * @category constants\n * @since 4.0.0\n */\nexport const constPong = {\n  _tag: \"Pong\"\n};\n/**\n * Checks if the response type is terminal.\n *\n * @category guards\n * @since 4.0.0\n */\nexport const isTerminalResponse = response => {\n  switch (response._tag) {\n    case \"Exit\":\n    case \"Defect\":\n    case \"ClientProtocolError\":\n      {\n        return true;\n      }\n    default:\n      {\n        return false;\n      }\n  }\n};\n//# sourceMappingURL=RpcMessage.js.map","var decoder;\ntry {\n\tdecoder = new TextDecoder();\n} catch(error) {}\nvar src;\nvar srcEnd;\nvar position = 0;\nvar alreadySet;\nconst EMPTY_ARRAY = [];\nvar strings = EMPTY_ARRAY;\nvar stringPosition = 0;\nvar currentUnpackr = {};\nvar currentStructures;\nvar srcString;\nvar srcStringStart = 0;\nvar srcStringEnd = 0;\nvar bundledStrings;\nvar referenceMap;\nvar currentExtensions = [];\nvar dataView;\nvar defaultOptions = {\n\tuseRecords: false,\n\tmapsAsObjects: true\n};\nexport class C1Type {}\nexport const C1 = new C1Type();\nC1.name = 'MessagePack 0xC1';\nvar sequentialMode = false;\nvar inlineObjectReadThreshold = 2;\nvar BlockedFunction; // we use search and replace to change the next call to BlockedFunction to avoid CSP issues for\n\nexport class Unpackr {\n\tconstructor(options) {\n\t\tif (options) {\n\t\t\tif (options.useRecords === false && options.mapsAsObjects === undefined)\n\t\t\t\toptions.mapsAsObjects = true;\n\t\t\tif (options.sequential && options.trusted !== false) {\n\t\t\t\toptions.trusted = true;\n\t\t\t\tif (!options.structures && options.useRecords != false) {\n\t\t\t\t\toptions.structures = [];\n\t\t\t\t\tif (!options.maxSharedStructures)\n\t\t\t\t\t\toptions.maxSharedStructures = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options.structures)\n\t\t\t\toptions.structures.sharedLength = options.structures.length;\n\t\t\telse if (options.getStructures) {\n\t\t\t\t(options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures\n\t\t\t\toptions.structures.sharedLength = 0;\n\t\t\t}\n\t\t\tif (options.int64AsNumber) {\n\t\t\t\toptions.int64AsType = 'number';\n\t\t\t}\n\t\t}\n\t\tObject.assign(this, options);\n\t}\n\tunpack(source, options) {\n\t\tif (src) {\n\t\t\t// re-entrant execution, save the state and restore it after we do this unpack\n\t\t\treturn saveState(() => {\n\t\t\t\tclearSource();\n\t\t\t\treturn this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options);\n\t\t\t});\n\t\t}\n\t\tif (!source.buffer && source.constructor === ArrayBuffer)\n\t\t\tsource = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);\n\t\tif (typeof options === 'object') {\n\t\t\tsrcEnd = options.end || source.length;\n\t\t\tposition = options.start || 0;\n\t\t} else {\n\t\t\tposition = 0;\n\t\t\tsrcEnd = options > -1 ? options : source.length;\n\t\t}\n\t\tstringPosition = 0;\n\t\tsrcStringEnd = 0;\n\t\tsrcString = null;\n\t\tstrings = EMPTY_ARRAY;\n\t\tbundledStrings = null;\n\t\tsrc = source;\n\t\t// this provides cached access to the data view for a buffer if it is getting reused, which is a recommend\n\t\t// technique for getting data from a database where it can be copied into an existing buffer instead of creating\n\t\t// new ones\n\t\ttry {\n\t\t\tdataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));\n\t\t} catch(error) {\n\t\t\t// if it doesn't have a buffer, maybe it is the wrong type of object\n\t\t\tsrc = null;\n\t\t\tif (source instanceof Uint8Array)\n\t\t\t\tthrow error;\n\t\t\tthrow new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source));\n\t\t}\n\t\tif (this instanceof Unpackr) {\n\t\t\tcurrentUnpackr = this;\n\t\t\tif (this.structures) {\n\t\t\t\tcurrentStructures = this.structures;\n\t\t\t\treturn checkedRead(options);\n\t\t\t} else if (!currentStructures || currentStructures.length > 0) {\n\t\t\t\tcurrentStructures = [];\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentUnpackr = defaultOptions;\n\t\t\tif (!currentStructures || currentStructures.length > 0)\n\t\t\t\tcurrentStructures = [];\n\t\t}\n\t\treturn checkedRead(options);\n\t}\n\tunpackMultiple(source, forEach) {\n\t\tlet values, lastPosition = 0;\n\t\ttry {\n\t\t\tsequentialMode = true;\n\t\t\tlet size = source.length;\n\t\t\tlet value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);\n\t\t\tif (forEach) {\n\t\t\t\tif (forEach(value, lastPosition, position) === false) return;\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position;\n\t\t\t\t\tif (forEach(checkedRead(), lastPosition, position) === false) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalues = [ value ];\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position;\n\t\t\t\t\tvalues.push(checkedRead());\n\t\t\t\t}\n\t\t\t\treturn values;\n\t\t\t}\n\t\t} catch(error) {\n\t\t\terror.lastPosition = lastPosition;\n\t\t\terror.values = values;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tsequentialMode = false;\n\t\t\tclearSource();\n\t\t}\n\t}\n\t_mergeStructures(loadedStructures, existingStructures) {\n\t\tif (this._onLoadedStructures)\n\t\t\tloadedStructures = this._onLoadedStructures(loadedStructures);\n\t\tloadedStructures = loadedStructures || [];\n\t\tif (Object.isFrozen(loadedStructures))\n\t\t\tloadedStructures = loadedStructures.map(structure => structure.slice(0));\n\t\tfor (let i = 0, l = loadedStructures.length; i < l; i++) {\n\t\t\tlet structure = loadedStructures[i];\n\t\t\tif (structure) {\n\t\t\t\tstructure.isShared = true;\n\t\t\t\tif (i >= 32)\n\t\t\t\t\tstructure.highByte = (i - 32) >> 5;\n\t\t\t}\n\t\t}\n\t\tloadedStructures.sharedLength = loadedStructures.length;\n\t\tfor (let id in existingStructures || []) {\n\t\t\tif (id >= 0) {\n\t\t\t\tlet structure = loadedStructures[id];\n\t\t\t\tlet existing = existingStructures[id];\n\t\t\t\tif (existing) {\n\t\t\t\t\tif (structure)\n\t\t\t\t\t\t(loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;\n\t\t\t\t\tloadedStructures[id] = existing;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.structures = loadedStructures;\n\t}\n\tdecode(source, options) {\n\t\treturn this.unpack(source, options);\n\t}\n}\nexport function getPosition() {\n\treturn position;\n}\nexport function checkedRead(options) {\n\ttry {\n\t\tif (!currentUnpackr.trusted && !sequentialMode) {\n\t\t\tlet sharedLength = currentStructures.sharedLength || 0;\n\t\t\tif (sharedLength < currentStructures.length)\n\t\t\t\tcurrentStructures.length = sharedLength;\n\t\t}\n\t\tlet result;\n\t\tif (currentUnpackr._readStruct && src[position] < 0x40 && src[position] >= 0x20) {\n\t\t\tresult = currentUnpackr._readStruct(src, position, srcEnd);\n\t\t\tsrc = null; // dispose of this so that recursive unpack calls don't save state\n\t\t\tif (!(options && options.lazy) && result)\n\t\t\t\tresult = result.toJSON();\n\t\t\tposition = srcEnd;\n\t\t} else\n\t\t\tresult = read();\n\t\tif (bundledStrings) { // bundled strings to skip past\n\t\t\tposition = bundledStrings.postBundlePosition;\n\t\t\tbundledStrings = null;\n\t\t}\n\t\tif (sequentialMode)\n\t\t\t// we only need to restore the structures if there was an error, but if we completed a read,\n\t\t\t// we can clear this out and keep the structures we read\n\t\t\tcurrentStructures.restoreStructures = null;\n\n\t\tif (position == srcEnd) {\n\t\t\t// finished reading this source, cleanup references\n\t\t\tif (currentStructures && currentStructures.restoreStructures)\n\t\t\t\trestoreStructures();\n\t\t\tcurrentStructures = null;\n\t\t\tsrc = null;\n\t\t\tif (referenceMap)\n\t\t\t\treferenceMap = null;\n\t\t} else if (position > srcEnd) {\n\t\t\t// over read\n\t\t\tthrow new Error('Unexpected end of MessagePack data');\n\t\t} else if (!sequentialMode) {\n\t\t\tlet jsonView;\n\t\t\ttry {\n\t\t\t\tjsonView = JSON.stringify(result, (_, value) => typeof value === \"bigint\" ? `${value}n` : value).slice(0, 100);\n\t\t\t} catch(error) {\n\t\t\t\tjsonView = '(JSON view not available ' + error + ')';\n\t\t\t}\n\t\t\tthrow new Error('Data read, but end of buffer not reached ' + jsonView);\n\t\t}\n\t\t// else more to read, but we are reading sequentially, so don't clear source yet\n\t\treturn result;\n\t} catch(error) {\n\t\tif (currentStructures && currentStructures.restoreStructures)\n\t\t\trestoreStructures();\n\t\tclearSource();\n\t\tif (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position > srcEnd) {\n\t\t\terror.incomplete = true;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nfunction restoreStructures() {\n\tfor (let id in currentStructures.restoreStructures) {\n\t\tcurrentStructures[id] = currentStructures.restoreStructures[id];\n\t}\n\tcurrentStructures.restoreStructures = null;\n}\n\nexport function read() {\n\tlet token = src[position++];\n\tif (token < 0xa0) {\n\t\tif (token < 0x80) {\n\t\t\tif (token < 0x40)\n\t\t\t\treturn token;\n\t\t\telse {\n\t\t\t\tlet structure = currentStructures[token & 0x3f] ||\n\t\t\t\t\tcurrentUnpackr.getStructures && loadStructures()[token & 0x3f];\n\t\t\t\tif (structure) {\n\t\t\t\t\tif (!structure.read) {\n\t\t\t\t\t\tstructure.read = createStructureReader(structure, token & 0x3f);\n\t\t\t\t\t}\n\t\t\t\t\treturn structure.read();\n\t\t\t\t} else\n\t\t\t\t\treturn token;\n\t\t\t}\n\t\t} else if (token < 0x90) {\n\t\t\t// map\n\t\t\ttoken -= 0x80;\n\t\t\tif (currentUnpackr.mapsAsObjects) {\n\t\t\t\tlet object = {};\n\t\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\t\tlet key = readKey();\n\t\t\t\t\tif (key === '__proto__')\n\t\t\t\t\t\tkey = '__proto_';\n\t\t\t\t\tobject[key] = read();\n\t\t\t\t}\n\t\t\t\treturn object;\n\t\t\t} else {\n\t\t\t\tlet map = new Map();\n\t\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\t\tmap.set(read(), read());\n\t\t\t\t}\n\t\t\t\treturn map;\n\t\t\t}\n\t\t} else {\n\t\t\ttoken -= 0x90;\n\t\t\tlet array = new Array(token);\n\t\t\tfor (let i = 0; i < token; i++) {\n\t\t\t\tarray[i] = read();\n\t\t\t}\n\t\t\tif (currentUnpackr.freezeData)\n\t\t\t\treturn Object.freeze(array);\n\t\t\treturn array;\n\t\t}\n\t} else if (token < 0xc0) {\n\t\t// fixstr\n\t\tlet length = token - 0xa0;\n\t\tif (srcStringEnd >= position) {\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart);\n\t\t}\n\t\tif (srcStringEnd == 0 && srcEnd < 140) {\n\t\t\t// for small blocks, avoiding the overhead of the extract call is helpful\n\t\t\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length);\n\t\t\tif (string != null)\n\t\t\t\treturn string;\n\t\t}\n\t\treturn readFixedString(length);\n\t} else {\n\t\tlet value;\n\t\tswitch (token) {\n\t\t\tcase 0xc0: return null;\n\t\t\tcase 0xc1:\n\t\t\t\tif (bundledStrings) {\n\t\t\t\t\tvalue = read(); // followed by the length of the string in characters (not bytes!)\n\t\t\t\t\tif (value > 0)\n\t\t\t\t\t\treturn bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value);\n\t\t\t\t\telse\n\t\t\t\t\t\treturn bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value);\n\t\t\t\t}\n\t\t\t\treturn C1; // \"never-used\", return special object to denote that\n\t\t\tcase 0xc2: return false;\n\t\t\tcase 0xc3: return true;\n\t\t\tcase 0xc4:\n\t\t\t\t// bin 8\n\t\t\t\tvalue = src[position++];\n\t\t\t\tif (value === undefined)\n\t\t\t\t\tthrow new Error('Unexpected end of buffer');\n\t\t\t\treturn readBin(value);\n\t\t\tcase 0xc5:\n\t\t\t\t// bin 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readBin(value);\n\t\t\tcase 0xc6:\n\t\t\t\t// bin 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readBin(value);\n\t\t\tcase 0xc7:\n\t\t\t\t// ext 8\n\t\t\t\treturn readExt(src[position++]);\n\t\t\tcase 0xc8:\n\t\t\t\t// ext 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readExt(value);\n\t\t\tcase 0xc9:\n\t\t\t\t// ext 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readExt(value);\n\t\t\tcase 0xca:\n\t\t\t\tvalue = dataView.getFloat32(position);\n\t\t\t\tif (currentUnpackr.useFloat32 > 2) {\n\t\t\t\t\t// this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\tlet multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)];\n\t\t\t\t\tposition += 4;\n\t\t\t\t\treturn ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier;\n\t\t\t\t}\n\t\t\t\tposition += 4;\n\t\t\t\treturn value;\n\t\t\tcase 0xcb:\n\t\t\t\tvalue = dataView.getFloat64(position);\n\t\t\t\tposition += 8;\n\t\t\t\treturn value;\n\t\t\t// uint handlers\n\t\t\tcase 0xcc:\n\t\t\t\treturn src[position++];\n\t\t\tcase 0xcd:\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn value;\n\t\t\tcase 0xce:\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn value;\n\t\t\tcase 0xcf:\n\t\t\t\tif (currentUnpackr.int64AsType === 'number') {\n\t\t\t\t\tvalue = dataView.getUint32(position) * 0x100000000;\n\t\t\t\t\tvalue += dataView.getUint32(position + 4);\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'string') {\n\t\t\t\t\tvalue = dataView.getBigUint64(position).toString();\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'auto') {\n\t\t\t\t\tvalue = dataView.getBigUint64(position);\n\t\t\t\t\tif (value<=BigInt(2)<<BigInt(52)) value=Number(value);\n\t\t\t\t} else\n\t\t\t\t\tvalue = dataView.getBigUint64(position);\n\t\t\t\tposition += 8;\n\t\t\t\treturn value;\n\n\t\t\t// int handlers\n\t\t\tcase 0xd0:\n\t\t\t\treturn dataView.getInt8(position++);\n\t\t\tcase 0xd1:\n\t\t\t\tvalue = dataView.getInt16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn value;\n\t\t\tcase 0xd2:\n\t\t\t\tvalue = dataView.getInt32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn value;\n\t\t\tcase 0xd3:\n\t\t\t\tif (currentUnpackr.int64AsType === 'number') {\n\t\t\t\t\tvalue = dataView.getInt32(position) * 0x100000000;\n\t\t\t\t\tvalue += dataView.getUint32(position + 4);\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'string') {\n\t\t\t\t\tvalue = dataView.getBigInt64(position).toString();\n\t\t\t\t} else if (currentUnpackr.int64AsType === 'auto') {\n\t\t\t\t\tvalue = dataView.getBigInt64(position);\n\t\t\t\t\tif (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);\n\t\t\t\t} else\n\t\t\t\t\tvalue = dataView.getBigInt64(position);\n\t\t\t\tposition += 8;\n\t\t\t\treturn value;\n\n\t\t\tcase 0xd4:\n\t\t\t\t// fixext 1\n\t\t\t\tvalue = src[position++];\n\t\t\t\tif (value == 0x72) {\n\t\t\t\t\treturn recordDefinition(src[position++] & 0x3f);\n\t\t\t\t} else {\n\t\t\t\t\tlet extension = currentExtensions[value];\n\t\t\t\t\tif (extension) {\n\t\t\t\t\t\tif (extension.read) {\n\t\t\t\t\t\t\tposition++; // skip filler byte\n\t\t\t\t\t\t\treturn extension.read(read());\n\t\t\t\t\t\t} else if (extension.noBuffer) {\n\t\t\t\t\t\t\tposition++; // skip filler byte\n\t\t\t\t\t\t\treturn extension();\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\treturn extension(src.subarray(position, ++position));\n\t\t\t\t\t} else\n\t\t\t\t\t\tthrow new Error('Unknown extension ' + value);\n\t\t\t\t}\n\t\t\tcase 0xd5:\n\t\t\t\t// fixext 2\n\t\t\t\tvalue = src[position];\n\t\t\t\tif (value == 0x72) {\n\t\t\t\t\tposition++;\n\t\t\t\t\treturn recordDefinition(src[position++] & 0x3f, src[position++]);\n\t\t\t\t} else\n\t\t\t\t\treturn readExt(2);\n\t\t\tcase 0xd6:\n\t\t\t\t// fixext 4\n\t\t\t\treturn readExt(4);\n\t\t\tcase 0xd7:\n\t\t\t\t// fixext 8\n\t\t\t\treturn readExt(8);\n\t\t\tcase 0xd8:\n\t\t\t\t// fixext 16\n\t\t\t\treturn readExt(16);\n\t\t\tcase 0xd9:\n\t\t\t// str 8\n\t\t\t\tvalue = src[position++];\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart);\n\t\t\t\t}\n\t\t\t\treturn readString8(value);\n\t\t\tcase 0xda:\n\t\t\t// str 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart);\n\t\t\t\t}\n\t\t\t\treturn readString16(value);\n\t\t\tcase 0xdb:\n\t\t\t// str 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\tif (srcStringEnd >= position) {\n\t\t\t\t\treturn srcString.slice(position - srcStringStart, (position += value) - srcStringStart);\n\t\t\t\t}\n\t\t\t\treturn readString32(value);\n\t\t\tcase 0xdc:\n\t\t\t// array 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readArray(value);\n\t\t\tcase 0xdd:\n\t\t\t// array 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readArray(value);\n\t\t\tcase 0xde:\n\t\t\t// map 16\n\t\t\t\tvalue = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\treturn readMap(value);\n\t\t\tcase 0xdf:\n\t\t\t// map 32\n\t\t\t\tvalue = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\treturn readMap(value);\n\t\t\tdefault: // negative int\n\t\t\t\tif (token >= 0xe0)\n\t\t\t\t\treturn token - 0x100;\n\t\t\t\tif (token === undefined) {\n\t\t\t\t\tlet error = new Error('Unexpected end of MessagePack data');\n\t\t\t\t\terror.incomplete = true;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tthrow new Error('Unknown MessagePack token ' + token);\n\n\t\t}\n\t}\n}\nconst validName = /^[a-zA-Z_$][a-zA-Z\\d_$]*$/;\nfunction createStructureReader(structure, firstId) {\n\tfunction readObject() {\n\t\t// This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function\n\t\tif (readObject.count++ > inlineObjectReadThreshold) {\n\t\t\tlet optimizedReadObject;\n\t\t\ttry {\n\t\t\t\toptimizedReadObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +\n\t\t\t\t\t'({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);\n\t\t\t} catch(error) {\n\t\t\t\t// in CF workers, the new Function call could begin to fail at any point in time\n\t\t\t\tinlineObjectReadThreshold = Infinity; // disable going forward\n\t\t\t\treturn readObject(); // recursively try again\n\t\t\t}\n\t\t\tstructure.read0 = optimizedReadObject; // keep the un-wrapped body reader in sync\n\t\t\tif (structure.highByte === 0)\n\t\t\t\tstructure.read = createSecondByteReader(firstId, structure.read);\n\t\t\treturn optimizedReadObject(); // second byte is already read, if there is one so immediately read object\n\t\t}\n\t\tlet object = {};\n\t\tfor (let i = 0, l = structure.length; i < l; i++) {\n\t\t\tlet key = structure[i];\n\t\t\tif (key === '__proto__')\n\t\t\t\tkey = '__proto_';\n\t\t\tobject[key] = read();\n\t\t}\n\t\tif (currentUnpackr.freezeData)\n\t\t\treturn Object.freeze(object);\n\t\treturn object;\n\t}\n\treadObject.count = 0;\n\t// read0 is the un-wrapped body reader: it reads the record's values directly without\n\t// consuming a leading high byte. recordDefinition uses it for the immediate read that follows\n\t// a record definition (the high byte, if present, was already consumed). For highByte === 0\n\t// structures the public reader is a second-byte reader (used by later references), but the\n\t// definition read itself must not consume that byte.\n\tstructure.read0 = readObject;\n\tif (structure.highByte === 0) {\n\t\treturn createSecondByteReader(firstId, readObject);\n\t}\n\treturn readObject;\n}\n\nconst createSecondByteReader = (firstId, read0) => {\n\treturn function() {\n\t\tlet highByte = src[position++];\n\t\tif (highByte === 0)\n\t\t\treturn read0();\n\t\tlet id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);\n\t\tlet structure = currentStructures[id] || loadStructures()[id];\n\t\tif (!structure) {\n\t\t\tthrow new Error('Record id is not defined for ' + id);\n\t\t}\n\t\tif (!structure.read)\n\t\t\tstructure.read = createStructureReader(structure, firstId);\n\t\treturn structure.read();\n\t};\n};\n\nexport function loadStructures() {\n\tlet loadedStructures = saveState(() => {\n\t\t// save the state in case getStructures modifies our buffer\n\t\tsrc = null;\n\t\treturn currentUnpackr.getStructures();\n\t});\n\treturn currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures);\n}\n\nvar readFixedString = readStringJS;\nvar readString8 = readStringJS;\nvar readString16 = readStringJS;\nvar readString32 = readStringJS;\nexport let isNativeAccelerationEnabled = false;\n\nexport function setExtractor(extractStrings) {\n\tisNativeAccelerationEnabled = true;\n\treadFixedString = readString(1);\n\treadString8 = readString(2);\n\treadString16 = readString(3);\n\treadString32 = readString(5);\n\tfunction readString(headerLength) {\n\t\treturn function readString(length) {\n\t\t\tlet string = strings[stringPosition++];\n\t\t\tif (string == null) {\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\treturn readStringJS(length);\n\t\t\t\tlet byteOffset = src.byteOffset;\n\t\t\t\tlet extraction = extractStrings(position - headerLength + byteOffset, srcEnd + byteOffset, src.buffer);\n\t\t\t\tif (typeof extraction == 'string') {\n\t\t\t\t\tstring = extraction;\n\t\t\t\t\tstrings = EMPTY_ARRAY;\n\t\t\t\t} else {\n\t\t\t\t\tstrings = extraction;\n\t\t\t\t\tstringPosition = 1;\n\t\t\t\t\tsrcStringEnd = 1; // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings\n\t\t\t\t\tstring = strings[0];\n\t\t\t\t\tif (string === undefined)\n\t\t\t\t\t\tthrow new Error('Unexpected end of buffer');\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet srcStringLength = string.length;\n\t\t\tif (srcStringLength <= length) {\n\t\t\t\tposition += length;\n\t\t\t\treturn string;\n\t\t\t}\n\t\t\tsrcString = string;\n\t\t\tsrcStringStart = position;\n\t\t\tsrcStringEnd = position + srcStringLength;\n\t\t\tposition += length;\n\t\t\treturn string.slice(0, length); // we know we just want the beginning\n\t\t};\n\t}\n}\nfunction readStringJS(length) {\n\tlet result;\n\tif (length < 16) {\n\t\tif (result = shortStringInJS(length))\n\t\t\treturn result;\n\t}\n\tif (length > 64 && decoder)\n\t\treturn decoder.decode(src.subarray(position, position += length));\n\tconst end = position + length;\n\tconst units = [];\n\tresult = '';\n\twhile (position < end) {\n\t\tconst byte1 = src[position++];\n\t\tif ((byte1 & 0x80) === 0) {\n\t\t\t// 1 byte\n\t\t\tunits.push(byte1);\n\t\t} else if ((byte1 & 0xe0) === 0xc0) {\n\t\t\t// 2 bytes\n\t\t\tif (byte1 < 0xc2 || position >= end || (src[position] & 0xc0) !== 0x80) {\n\t\t\t\tunits.push(0xFFFD);\n\t\t\t} else {\n\t\t\t\tconst byte2 = src[position++] & 0x3f;\n\t\t\t\tunits.push(((byte1 & 0x1f) << 6) | byte2);\n\t\t\t}\n\t\t} else if ((byte1 & 0xf0) === 0xe0) {\n\t\t\t// 3 bytes\n\t\t\tconst byte2 = position < end ? src[position] : 0;\n\t\t\tif (position >= end || (byte2 & 0xc0) !== 0x80 ||\n\t\t\t\t(byte1 === 0xe0 && byte2 < 0xa0) || (byte1 === 0xed && byte2 >= 0xa0)) {\n\t\t\t\tunits.push(0xFFFD);\n\t\t\t} else {\n\t\t\t\tposition++;\n\t\t\t\tif (position >= end || (src[position] & 0xc0) !== 0x80) {\n\t\t\t\t\tunits.push(0xFFFD);\n\t\t\t\t} else {\n\t\t\t\t\tconst byte3 = src[position++] & 0x3f;\n\t\t\t\t\tunits.push(((byte1 & 0x1f) << 12) | ((byte2 & 0x3f) << 6) | byte3);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ((byte1 & 0xf8) === 0xf0) {\n\t\t\t// 4 bytes\n\t\t\tconst byte2 = position < end ? src[position] : 0;\n\t\t\tif (byte1 > 0xf4 || position >= end || (byte2 & 0xc0) !== 0x80 ||\n\t\t\t\t(byte1 === 0xf0 && byte2 < 0x90) || (byte1 === 0xf4 && byte2 >= 0x90)) {\n\t\t\t\tunits.push(0xFFFD);\n\t\t\t} else {\n\t\t\t\tposition++;\n\t\t\t\tif (position >= end || (src[position] & 0xc0) !== 0x80) {\n\t\t\t\t\tunits.push(0xFFFD);\n\t\t\t\t} else {\n\t\t\t\t\tconst byte3 = src[position++] & 0x3f;\n\t\t\t\t\tif (position >= end || (src[position] & 0xc0) !== 0x80) {\n\t\t\t\t\t\tunits.push(0xFFFD);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst byte4 = src[position++] & 0x3f;\n\t\t\t\t\t\tlet unit = ((byte1 & 0x07) << 0x12) | ((byte2 & 0x3f) << 0x0c) | (byte3 << 0x06) | byte4;\n\t\t\t\t\t\tunit -= 0x10000;\n\t\t\t\t\t\tunits.push(((unit >>> 10) & 0x3ff) | 0xd800);\n\t\t\t\t\t\tunits.push(0xdc00 | (unit & 0x3ff));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tunits.push(0xFFFD); // replacement character for invalid lead byte\n\t\t}\n\n\t\tif (units.length >= 0x1000) {\n\t\t\tresult += fromCharCode.apply(String, units);\n\t\t\tunits.length = 0;\n\t\t}\n\t}\n\n\tif (units.length > 0) {\n\t\tresult += fromCharCode.apply(String, units);\n\t}\n\n\treturn result;\n}\nexport function readString(source, start, length) {\n\tlet existingSrc = src;\n\tsrc = source;\n\tposition = start;\n\ttry {\n\t\treturn readStringJS(length);\n\t} finally {\n\t\tsrc = existingSrc;\n\t}\n}\n\nfunction readArray(length) {\n\tlet array = new Array(length);\n\tfor (let i = 0; i < length; i++) {\n\t\tarray[i] = read();\n\t}\n\tif (currentUnpackr.freezeData)\n\t\treturn Object.freeze(array);\n\treturn array;\n}\n\nfunction readMap(length) {\n\tif (currentUnpackr.mapsAsObjects) {\n\t\tlet object = {};\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tlet key = readKey();\n\t\t\tif (key === '__proto__')\n\t\t\t\tkey = '__proto_';\n\t\t\tobject[key] = read();\n\t\t}\n\t\treturn object;\n\t} else {\n\t\tlet map = new Map();\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tmap.set(read(), read());\n\t\t}\n\t\treturn map;\n\t}\n}\n\nvar fromCharCode = String.fromCharCode;\nfunction longStringInJS(length) {\n\tlet start = position;\n\tlet bytes = new Array(length);\n\tfor (let i = 0; i < length; i++) {\n\t\tconst byte = src[position++];\n\t\tif ((byte & 0x80) > 0) {\n\t\t\t\tposition = start;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbytes[i] = byte;\n\t\t}\n\t\treturn fromCharCode.apply(String, bytes);\n}\nfunction shortStringInJS(length) {\n\tif (length < 4) {\n\t\tif (length < 2) {\n\t\t\tif (length === 0)\n\t\t\t\treturn '';\n\t\t\telse {\n\t\t\t\tlet a = src[position++];\n\t\t\t\tif ((a & 0x80) > 1) {\n\t\t\t\t\tposition -= 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a);\n\t\t\t}\n\t\t} else {\n\t\t\tlet a = src[position++];\n\t\t\tlet b = src[position++];\n\t\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0) {\n\t\t\t\tposition -= 2;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (length < 3)\n\t\t\t\treturn fromCharCode(a, b);\n\t\t\tlet c = src[position++];\n\t\t\tif ((c & 0x80) > 0) {\n\t\t\t\tposition -= 3;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c);\n\t\t}\n\t} else {\n\t\tlet a = src[position++];\n\t\tlet b = src[position++];\n\t\tlet c = src[position++];\n\t\tlet d = src[position++];\n\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {\n\t\t\tposition -= 4;\n\t\t\treturn;\n\t\t}\n\t\tif (length < 6) {\n\t\t\tif (length === 4)\n\t\t\t\treturn fromCharCode(a, b, c, d);\n\t\t\telse {\n\t\t\t\tlet e = src[position++];\n\t\t\t\tif ((e & 0x80) > 0) {\n\t\t\t\t\tposition -= 5;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e);\n\t\t\t}\n\t\t} else if (length < 8) {\n\t\t\tlet e = src[position++];\n\t\t\tlet f = src[position++];\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0) {\n\t\t\t\tposition -= 6;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (length < 7)\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f);\n\t\t\tlet g = src[position++];\n\t\t\tif ((g & 0x80) > 0) {\n\t\t\t\tposition -= 7;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c, d, e, f, g);\n\t\t} else {\n\t\t\tlet e = src[position++];\n\t\t\tlet f = src[position++];\n\t\t\tlet g = src[position++];\n\t\t\tlet h = src[position++];\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {\n\t\t\t\tposition -= 8;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (length < 10) {\n\t\t\t\tif (length === 8)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h);\n\t\t\t\telse {\n\t\t\t\t\tlet i = src[position++];\n\t\t\t\t\tif ((i & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 9;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i);\n\t\t\t\t}\n\t\t\t} else if (length < 12) {\n\t\t\t\tlet i = src[position++];\n\t\t\t\tlet j = src[position++];\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0) {\n\t\t\t\t\tposition -= 10;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (length < 11)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j);\n\t\t\t\tlet k = src[position++];\n\t\t\t\tif ((k & 0x80) > 0) {\n\t\t\t\t\tposition -= 11;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k);\n\t\t\t} else {\n\t\t\t\tlet i = src[position++];\n\t\t\t\tlet j = src[position++];\n\t\t\t\tlet k = src[position++];\n\t\t\t\tlet l = src[position++];\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {\n\t\t\t\t\tposition -= 12;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (length < 14) {\n\t\t\t\t\tif (length === 12)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l);\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet m = src[position++];\n\t\t\t\t\t\tif ((m & 0x80) > 0) {\n\t\t\t\t\t\t\tposition -= 13;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet m = src[position++];\n\t\t\t\t\tlet n = src[position++];\n\t\t\t\t\tif ((m & 0x80) > 0 || (n & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 14;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (length < 15)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n);\n\t\t\t\t\tlet o = src[position++];\n\t\t\t\t\tif ((o & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 15;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readOnlyJSString() {\n\tlet token = src[position++];\n\tlet length;\n\tif (token < 0xc0) {\n\t\t// fixstr\n\t\tlength = token - 0xa0;\n\t} else {\n\t\tswitch(token) {\n\t\t\tcase 0xd9:\n\t\t\t// str 8\n\t\t\t\tlength = src[position++];\n\t\t\t\tbreak;\n\t\t\tcase 0xda:\n\t\t\t// str 16\n\t\t\t\tlength = dataView.getUint16(position);\n\t\t\t\tposition += 2;\n\t\t\t\tbreak;\n\t\t\tcase 0xdb:\n\t\t\t// str 32\n\t\t\t\tlength = dataView.getUint32(position);\n\t\t\t\tposition += 4;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error('Expected string');\n\t\t}\n\t}\n\treturn readStringJS(length);\n}\n\n\nfunction readBin(length) {\n\treturn currentUnpackr.copyBuffers ?\n\t\t// specifically use the copying slice (not the node one)\n\t\tUint8Array.prototype.slice.call(src, position, position += length) :\n\t\tsrc.subarray(position, position += length);\n}\nfunction readExt(length) {\n\tlet type = src[position++];\n\tif (currentExtensions[type]) {\n\t\tlet end;\n\t\treturn currentExtensions[type](src.subarray(position, end = (position += length)), (readPosition) => {\n\t\t\tposition = readPosition;\n\t\t\ttry {\n\t\t\t\treturn read();\n\t\t\t} finally {\n\t\t\t\tposition = end;\n\t\t\t}\n\t\t});\n\t}\n\telse\n\t\tthrow new Error('Unknown extension type ' + type);\n}\n\nvar keyCache = new Array(4096);\nfunction readKey() {\n\tlet length = src[position++];\n\tif (length >= 0xa0 && length < 0xc0) {\n\t\t// fixstr, potentially use key cache\n\t\tlength = length - 0xa0;\n\t\tif (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart);\n\t\telse if (!(srcStringEnd == 0 && srcEnd < 180))\n\t\t\treturn readFixedString(length);\n\t} else { // not cacheable, go back and do a standard read\n\t\tposition--;\n\t\treturn asSafeString(read());\n\t}\n\tlet key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff;\n\tlet entry = keyCache[key];\n\tlet checkPosition = position;\n\tlet end = position + length - 3;\n\tlet chunk;\n\tlet i = 0;\n\tif (entry && entry.bytes == length) {\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = dataView.getUint32(checkPosition);\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcheckPosition += 4;\n\t\t}\n\t\tend += 3;\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = src[checkPosition++];\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (checkPosition === end) {\n\t\t\tposition = checkPosition;\n\t\t\treturn entry.string;\n\t\t}\n\t\tend -= 3;\n\t\tcheckPosition = position;\n\t}\n\tentry = [];\n\tkeyCache[key] = entry;\n\tentry.bytes = length;\n\twhile (checkPosition < end) {\n\t\tchunk = dataView.getUint32(checkPosition);\n\t\tentry.push(chunk);\n\t\tcheckPosition += 4;\n\t}\n\tend += 3;\n\twhile (checkPosition < end) {\n\t\tchunk = src[checkPosition++];\n\t\tentry.push(chunk);\n\t}\n\t// for small blocks, avoiding the overhead of the extract call is helpful\n\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length);\n\tif (string != null)\n\t\treturn entry.string = string;\n\treturn entry.string = readFixedString(length);\n}\n\nfunction asSafeString(property) {\n\t// protect against expensive (DoS) string conversions\n\tif (typeof property === 'string') return property;\n\tif (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();\n\tif (property == null) return property + '';\n\tif (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every(item => ['string', 'number', 'boolean', 'bigint'].includes(typeof item))) {\n\t\treturn property.flat().toString();\n\t}\n\tthrow new Error(`Invalid property type for record: ${typeof property}`);\n}\n// the registration of the record definition extension (as \"r\")\nconst recordDefinition = (id, highByte) => {\n\tlet structure = read().map(asSafeString); // ensure that all keys are strings and\n\t// that the array is mutable\n\tlet firstByte = id;\n\tif (highByte !== undefined) {\n\t\tid = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);\n\t\tstructure.highByte = highByte;\n\t}\n\tlet existingStructure = currentStructures[id];\n\t// If it is a shared structure, we need to restore any changes after reading.\n\t// Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore\n\t// to the state prior to an incomplete read in order to properly resume.\n\tif (existingStructure && (existingStructure.isShared || sequentialMode)) {\n\t\t(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;\n\t}\n\tcurrentStructures[id] = structure;\n\tstructure.read = createStructureReader(structure, firstByte);\n\t// The high byte (if any) was already consumed as the `highByte` argument above, so read the\n\t// record body directly. Going through structure.read (a second-byte reader when highByte === 0)\n\t// would misinterpret the first value byte as a high byte — corrupting two-byte own-record\n\t// definitions (0xd5 0x72 ...). createStructureReader stashes the un-wrapped body reader on\n\t// structure.read0 precisely for this immediate post-definition read.\n\treturn (structure.read0 || structure.read)();\n};\ncurrentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here\ncurrentExtensions[0].noBuffer = true;\n\ncurrentExtensions[0x42] = data => {\n\tlet headLength = (data.byteLength % 8) || 8;\n\tlet head = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);\n\tfor (let i = 1; i < headLength; i++) {\n\t\thead <<= BigInt(8);\n\t\thead += BigInt(data[i]);\n\t}\n\tif (data.byteLength !== headLength) {\n\t\tlet view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\t\tlet decode = (start, end) => {\n\t\t\tlet length = end - start;\n\t\t\tif (length <= 40) {\n\t\t\t\tlet out = view.getBigUint64(start);\n\t\t\t\tfor (let i = start + 8; i < end; i += 8) {\n\t\t\t\t\tout <<= BigInt(64);\n\t\t\t\t\tout |= view.getBigUint64(i);\n\t\t\t\t}\n\t\t\t\treturn out;\n\t\t\t}\n\t\t\t// if (length === 8) return view.getBigUint64(start)\n\t\t\tlet middle = start + (length >> 4 << 3);\n\t\t\tlet left = decode(start, middle);\n\t\t\tlet right = decode(middle, end);\n\t\t\treturn (left << BigInt((end - middle) * 8)) | right;\n\t\t};\n\t\thead = (head << BigInt((view.byteLength - headLength) * 8)) | decode(headLength, view.byteLength);\n\t}\n\treturn head;\n};\n\nlet errors = {\n\tError, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, AggregateError: typeof AggregateError === 'function' ? AggregateError : null,\n};\ncurrentExtensions[0x65] = () => {\n\tlet data = read();\n\tif (!errors[data[0]]) {\n\t\tlet error = Error(data[1], { cause: data[2] });\n\t\terror.name = data[0];\n\t\treturn error;\n\t}\n\treturn errors[data[0]](data[1], { cause: data[2] });\n};\n\ncurrentExtensions[0x69] = (data) => {\n\t// id extension (for structured clones)\n\tif (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled');\n\tlet id = dataView.getUint32(position - 4);\n\tif (!referenceMap)\n\t\treferenceMap = new Map();\n\tlet token = src[position];\n\tlet target;\n\t// TODO: handle any other types that can cycle and make the code more robust if there are other extensions\n\tif (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)\n\t\ttarget = [];\n\telse if (token >= 0x80 && token < 0x90 || token == 0xde || token == 0xdf)\n\t\ttarget = new Map();\n\telse if ((token >= 0xc7 && token <= 0xc9 || token >= 0xd4 && token <= 0xd8) && src[position + 1] === 0x73)\n\t\ttarget = new Set();\n\telse\n\t\ttarget = {};\n\n\tlet refEntry = { target }; // a placeholder object\n\treferenceMap.set(id, refEntry);\n\tlet targetProperties = read(); // read the next value as the target object to id\n\tif (!refEntry.used) {\n\t\t// no cycle, can just use the returned read object\n\t\treturn refEntry.target = targetProperties; // replace the placeholder with the real one\n\t} else {\n\t\t// there is a cycle, so we have to assign properties to original target\n\t\tObject.assign(target, targetProperties);\n\t}\n\n\t// copy over map/set entries if we're able to\n\tif (target instanceof Map)\n\t\tfor (let [k, v] of targetProperties.entries()) target.set(k, v);\n\tif (target instanceof Set)\n\t\tfor (let i of Array.from(targetProperties)) target.add(i);\n\treturn target;\n};\n\ncurrentExtensions[0x70] = (data) => {\n\t// pointer extension (for structured clones)\n\tif (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled');\n\tlet id = dataView.getUint32(position - 4);\n\tlet refEntry = referenceMap.get(id);\n\trefEntry.used = true;\n\treturn refEntry.target;\n};\n\ncurrentExtensions[0x73] = () => new Set(read());\n\nexport const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');\n\nlet glbl = typeof globalThis === 'object' ? globalThis : window;\ncurrentExtensions[0x74] = (data) => {\n\tlet typeCode = data[0];\n\t// we always have to slice to get a new ArrayBuffer that is aligned\n\tlet buffer = Uint8Array.prototype.slice.call(data, 1).buffer;\n\n\tlet typedArrayName = typedArrays[typeCode];\n\tif (!typedArrayName) {\n\t\tif (typeCode === 16) return buffer;\n\t\tif (typeCode === 17) return new DataView(buffer);\n\t\tthrow new Error('Could not find typed array for code ' + typeCode);\n\t}\n\treturn new glbl[typedArrayName](buffer);\n};\ncurrentExtensions[0x78] = () => {\n\tlet data = read();\n\treturn new RegExp(data[0], data[1]);\n};\nconst TEMP_BUNDLE = [];\ncurrentExtensions[0x62] = (data) => {\n\tlet dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];\n\tlet dataPosition = position;\n\tposition += dataSize - data.length;\n\tbundledStrings = TEMP_BUNDLE;\n\tbundledStrings = [readOnlyJSString(), readOnlyJSString()];\n\tbundledStrings.position0 = 0;\n\tbundledStrings.position1 = 0;\n\tbundledStrings.postBundlePosition = position;\n\tposition = dataPosition;\n\treturn read();\n};\n\ncurrentExtensions[0xff] = (data) => {\n\t// 32-bit date extension\n\tif (data.length == 4)\n\t\treturn new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000);\n\telse if (data.length == 8)\n\t\treturn new Date(\n\t\t\t((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +\n\t\t\t((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000);\n\telse if (data.length == 12)\n\t\treturn new Date(\n\t\t\t((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +\n\t\t\t(((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000);\n\telse\n\t\treturn new Date('invalid');\n};\n// registration of bulk record definition?\n// currentExtensions[0x52] = () =>\n\nfunction saveState(callback) {\n\tif (currentUnpackr && currentUnpackr._onSaveState)\n\t\tcurrentUnpackr._onSaveState();\n\tlet savedSrcEnd = srcEnd;\n\tlet savedPosition = position;\n\tlet savedStringPosition = stringPosition;\n\tlet savedSrcStringStart = srcStringStart;\n\tlet savedSrcStringEnd = srcStringEnd;\n\tlet savedSrcString = srcString;\n\tlet savedStrings = strings;\n\tlet savedReferenceMap = referenceMap;\n\tlet savedBundledStrings = bundledStrings;\n\n\t// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)\n\tlet savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed\n\tlet savedStructures = currentStructures;\n\tlet savedStructuresContents = currentStructures.slice(0, currentStructures.length);\n\tlet savedPackr = currentUnpackr;\n\tlet savedSequentialMode = sequentialMode;\n\tlet value = callback();\n\tsrcEnd = savedSrcEnd;\n\tposition = savedPosition;\n\tstringPosition = savedStringPosition;\n\tsrcStringStart = savedSrcStringStart;\n\tsrcStringEnd = savedSrcStringEnd;\n\tsrcString = savedSrcString;\n\tstrings = savedStrings;\n\treferenceMap = savedReferenceMap;\n\tbundledStrings = savedBundledStrings;\n\tsrc = savedSrc;\n\tsequentialMode = savedSequentialMode;\n\tcurrentStructures = savedStructures;\n\tcurrentStructures.splice(0, currentStructures.length, ...savedStructuresContents);\n\tcurrentUnpackr = savedPackr;\n\tdataView = new DataView(src.buffer, src.byteOffset, src.byteLength);\n\treturn value;\n}\nexport function clearSource() {\n\tsrc = null;\n\treferenceMap = null;\n\tcurrentStructures = null;\n}\n\nexport function addExtension(extension) {\n\tif (extension.unpack)\n\t\tcurrentExtensions[extension.type] = extension.unpack;\n\telse\n\t\tcurrentExtensions[extension.type] = extension;\n}\n\nexport const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding\nfor (let i = 0; i < 256; i++) {\n\tmult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));\n}\nexport const Decoder = Unpackr;\nvar defaultUnpackr = new Unpackr({ useRecords: false });\nexport const unpack = defaultUnpackr.unpack;\nexport const unpackMultiple = defaultUnpackr.unpackMultiple;\nexport const decode = defaultUnpackr.unpack;\nexport const FLOAT32_OPTIONS = {\n\tNEVER: 0,\n\tALWAYS: 1,\n\tDECIMAL_ROUND: 3,\n\tDECIMAL_FIT: 4\n};\nlet f32Array = new Float32Array(1);\nlet u8Array = new Uint8Array(f32Array.buffer, 0, 4);\nexport function roundFloat32(float32Number) {\n\tf32Array[0] = float32Number;\n\tlet multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)];\n\treturn ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier;\n}\n// Marker for downstream libraries (e.g. structon) to detect per-instance\n// struct-decoding hooks (this._readStruct, this._onLoadedStructures,\n// this._onSaveState).  See `checkedRead` for the dispatch.\nUnpackr.SUPPORTS_STRUCT_HOOKS = true;\n","import { Unpackr, mult10, C1Type, typedArrays, addExtension as unpackAddExtension } from './unpack.js';\nlet textEncoder;\ntry {\n\ttextEncoder = new TextEncoder();\n} catch (error) {}\nlet extensions, extensionClasses;\nconst hasNodeBuffer = typeof Buffer !== 'undefined';\nconst ByteArrayAllocate = hasNodeBuffer ?\n\tfunction(length) { return Buffer.allocUnsafeSlow(length); } : Uint8Array;\nconst ByteArray = hasNodeBuffer ? Buffer : Uint8Array;\nconst MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;\nlet target, keysTarget;\nlet targetView;\nlet position = 0;\nlet safeEnd;\nlet bundledStrings = null;\nconst MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.\nconst hasNonLatin = /[\\u0080-\\uFFFF]/;\nexport const RECORD_SYMBOL = Symbol('record-id');\nexport class Packr extends Unpackr {\n\tconstructor(options) {\n\t\tsuper(options);\n\t\tthis.offset = 0;\n\t\tlet typeBuffer;\n\t\tlet start;\n\t\tlet hasSharedUpdate;\n\t\tlet structures;\n\t\tlet referenceMap;\n\t\tlet encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {\n\t\t\treturn target.utf8Write(string, position, target.byteLength - position);\n\t\t} : (textEncoder && textEncoder.encodeInto) ?\n\t\t\tfunction(string, position) {\n\t\t\t\treturn textEncoder.encodeInto(string, target.subarray(position)).written;\n\t\t\t} : false;\n\n\t\tlet packr = this;\n\t\tif (!options)\n\t\t\toptions = {};\n\t\tlet isSequential = options && options.sequential;\n\t\tlet hasSharedStructures = options.structures || options.saveStructures;\n\t\tlet maxSharedStructures = options.maxSharedStructures;\n\t\tif (maxSharedStructures == null)\n\t\t\tmaxSharedStructures = hasSharedStructures ? 32 : 0;\n\t\tif (maxSharedStructures > 8160)\n\t\t\tthrow new Error('Maximum maxSharedStructure is 8160');\n\t\tif (options.structuredClone && options.moreTypes == undefined) {\n\t\t\tthis.moreTypes = true;\n\t\t}\n\t\tlet maxOwnStructures = options.maxOwnStructures;\n\t\tif (maxOwnStructures == null)\n\t\t\tmaxOwnStructures = hasSharedStructures ? 32 : 64;\n\t\tif (!this.structures && options.useRecords != false)\n\t\t\tthis.structures = [];\n\t\t// two byte record ids for shared structures\n\t\tlet useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);\n\t\tlet sharedLimitId = maxSharedStructures + 0x40;\n\t\tlet maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;\n\t\tif (maxStructureId > 8256) {\n\t\t\tthrow new Error('Maximum maxSharedStructure + maxOwnStructure is 8192');\n\t\t}\n\t\tlet recordIdsToRemove = [];\n\t\tlet transitionsCount = 0;\n\t\tlet serializationsSinceTransitionRebuild = 0;\n\n\t\tthis.pack = this.encode = function(value, encodeOptions) {\n\t\t\tif (!target) {\n\t\t\t\ttarget = new ByteArrayAllocate(8192);\n\t\t\t\ttargetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));\n\t\t\t\tposition = 0;\n\t\t\t}\n\t\t\tsafeEnd = target.length - 10;\n\t\t\tif (safeEnd - position < 0x800) {\n\t\t\t\t// don't start too close to the end,\n\t\t\t\ttarget = new ByteArrayAllocate(target.length);\n\t\t\t\ttargetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));\n\t\t\t\tsafeEnd = target.length - 10;\n\t\t\t\tposition = 0;\n\t\t\t} else\n\t\t\t\tposition = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster\n\t\t\tstart = position;\n\t\t\tif (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);\n\t\t\treferenceMap = packr.structuredClone ? new Map() : null;\n\t\t\tif (packr.bundleStrings && typeof value !== 'string') {\n\t\t\t\tbundledStrings = [];\n\t\t\t\tbundledStrings.size = Infinity; // force a new bundle start on first string\n\t\t\t} else\n\t\t\t\tbundledStrings = null;\n\t\t\tstructures = packr.structures;\n\t\t\tif (structures) {\n\t\t\t\tif (structures.uninitialized)\n\t\t\t\t\tstructures = packr._mergeStructures(packr.getStructures());\n\t\t\t\tlet sharedLength = structures.sharedLength || 0;\n\t\t\t\tif (sharedLength > maxSharedStructures) {\n\t\t\t\t\t//if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids\n\t\t\t\t\tthrow new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength);\n\t\t\t\t}\n\t\t\t\tif (!structures.transitions) {\n\t\t\t\t\t// rebuild our structure transitions\n\t\t\t\t\tstructures.transitions = Object.create(null);\n\t\t\t\t\tfor (let i = 0; i < sharedLength; i++) {\n\t\t\t\t\t\tlet keys = structures[i];\n\t\t\t\t\t\tif (!keys)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tlet nextTransition, transition = structures.transitions;\n\t\t\t\t\t\tfor (let j = 0, l = keys.length; j < l; j++) {\n\t\t\t\t\t\t\tlet key = keys[j];\n\t\t\t\t\t\t\tnextTransition = transition[key];\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i + 0x40;\n\t\t\t\t\t}\n\t\t\t\t\tthis.lastNamedStructuresLength = sharedLength;\n\t\t\t\t}\n\t\t\t\tif (!isSequential) {\n\t\t\t\t\tstructures.nextId = sharedLength + 0x40;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasSharedUpdate)\n\t\t\t\thasSharedUpdate = false;\n\t\t\tlet encodingError;\n\t\t\ttry {\n\t\t\t\tif (packr._writeStruct && value && typeof value === 'object') {\n\t\t\t\t\tif (value.constructor === Object) writeStruct(value); // simple object\n\t\t\t\t\telse if (value.constructor !== Map && !Array.isArray(value) && !extensionClasses.some(extClass => value instanceof extClass)) {\n\t\t\t\t\t\t// allow user classes, if they don't need special handling (but do use toJSON if available)\n\t\t\t\t\t\twriteStruct(value.toJSON ? value.toJSON() : value);\n\t\t\t\t\t} else pack(value);\n\t\t\t\t} else\n\t\t\t\t\tpack(value);\n\t\t\t\tlet lastBundle = bundledStrings;\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\twriteBundles(start, pack, 0);\n\t\t\t\tif (referenceMap && referenceMap.idsToInsert) {\n\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);\n\t\t\t\t\tlet i = idsToInsert.length;\n\t\t\t\t\tlet incrementPosition = -1;\n\t\t\t\t\twhile (lastBundle && i > 0) {\n\t\t\t\t\t\tlet insertionPoint = idsToInsert[--i].offset + start;\n\t\t\t\t\t\tif (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)\n\t\t\t\t\t\t\tincrementPosition = 0;\n\t\t\t\t\t\tif (insertionPoint > (lastBundle.position + start)) {\n\t\t\t\t\t\t\tif (incrementPosition >= 0)\n\t\t\t\t\t\t\t\tincrementPosition += 6;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (incrementPosition >= 0) {\n\t\t\t\t\t\t\t\t// update the bundle reference now\n\t\t\t\t\t\t\t\ttargetView.setUint32(lastBundle.position + start,\n\t\t\t\t\t\t\t\t\ttargetView.getUint32(lastBundle.position + start) + incrementPosition);\n\t\t\t\t\t\t\t\tincrementPosition = -1; // reset\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlastBundle = lastBundle.previous;\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (incrementPosition >= 0 && lastBundle) {\n\t\t\t\t\t\t// update the bundle reference now\n\t\t\t\t\t\ttargetView.setUint32(lastBundle.position + start,\n\t\t\t\t\t\t\ttargetView.getUint32(lastBundle.position + start) + incrementPosition);\n\t\t\t\t\t}\n\t\t\t\t\tposition += idsToInsert.length * 6;\n\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\tmakeRoom(position);\n\t\t\t\t\tpackr.offset = position;\n\t\t\t\t\tlet serialized = insertIds(target.subarray(start, position), idsToInsert);\n\t\t\t\t\treferenceMap = null;\n\t\t\t\t\treturn serialized;\n\t\t\t\t}\n\t\t\t\tpackr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially\n\t\t\t\tif (encodeOptions & REUSE_BUFFER_MODE) {\n\t\t\t\t\ttarget.start = start;\n\t\t\t\t\ttarget.end = position;\n\t\t\t\t\treturn target;\n\t\t\t\t}\n\t\t\t\treturn target.subarray(start, position); // position can change if we call pack again in saveStructures, so we get the buffer now\n\t\t\t} catch(error) {\n\t\t\t\tencodingError = error;\n\t\t\t\tthrow error;\n\t\t\t} finally {\n\t\t\t\tif (structures) {\n\t\t\t\t\tresetStructures();\n\t\t\t\t\tif (hasSharedUpdate && packr.saveStructures) {\n\t\t\t\t\t\tlet sharedLength = structures.sharedLength || 0;\n\t\t\t\t\t\t// we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save\n\t\t\t\t\t\tlet returnBuffer = target.subarray(start, position);\n\t\t\t\t\t\tlet newSharedData = (packr._prepareStructures || prepareStructures)(structures, packr);\n\t\t\t\t\t\tif (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time\n\t\t\t\t\t\t\tif (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {\n\t\t\t\t\t\t\t\t// The save was declined (a concurrent writer updated the shared structures,\n\t\t\t\t\t\t\t\t// or the store transaction did not durably commit). Our in-memory\n\t\t\t\t\t\t\t\t// structures + transition trie may now reference record ids that were\n\t\t\t\t\t\t\t\t// never persisted; re-packing as-is would re-emit the same record pointing\n\t\t\t\t\t\t\t\t// at an unpersisted structure (-> \"Record id is not defined\" on decode).\n\t\t\t\t\t\t\t\t// Mark structures uninitialized so the re-pack reloads durable structures\n\t\t\t\t\t\t\t\t// via getStructures, rebuilds the transition trie, and re-mints + re-saves.\n\t\t\t\t\t\t\t\tstructures.uninitialized = true;\n\t\t\t\t\t\t\t\treturn packr.pack(value, encodeOptions);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpackr.lastNamedStructuresLength = sharedLength;\n\t\t\t\t\t\t\t// don't keep large buffers around\n\t\t\t\t\t\t\tif (target.length > 0x40000000) target = null;\n\t\t\t\t\t\t\treturn returnBuffer;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)\n\t\t\t\tif (target.length > 0x40000000) target = null;\n\t\t\t\tif (encodeOptions & RESET_BUFFER_MODE)\n\t\t\t\t\tposition = start;\n\t\t\t}\n\t\t};\n\t\tconst resetStructures = () => {\n\t\t\tif (serializationsSinceTransitionRebuild < 10)\n\t\t\t\tserializationsSinceTransitionRebuild++;\n\t\t\tlet sharedLength = structures.sharedLength || 0;\n\t\t\tif (structures.length > sharedLength && !isSequential)\n\t\t\t\tstructures.length = sharedLength;\n\t\t\tif (transitionsCount > 10000) {\n\t\t\t\t// force a rebuild occasionally after a lot of transitions so it can get cleaned up\n\t\t\t\tstructures.transitions = null;\n\t\t\t\tserializationsSinceTransitionRebuild = 0;\n\t\t\t\ttransitionsCount = 0;\n\t\t\t\tif (recordIdsToRemove.length > 0)\n\t\t\t\t\trecordIdsToRemove = [];\n\t\t\t} else if (recordIdsToRemove.length > 0 && !isSequential) {\n\t\t\t\tfor (let i = 0, l = recordIdsToRemove.length; i < l; i++) {\n\t\t\t\t\trecordIdsToRemove[i][RECORD_SYMBOL] = 0;\n\t\t\t\t}\n\t\t\t\trecordIdsToRemove = [];\n\t\t\t}\n\t\t};\n\t\tconst packArray = (value) => {\n\t\t\tvar length = value.length;\n\t\t\tif (length < 0x10) {\n\t\t\t\ttarget[position++] = 0x90 | length;\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xdc;\n\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xdd;\n\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\tposition += 4;\n\t\t\t}\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tpack(value[i]);\n\t\t\t}\n\t\t};\n\t\tconst pack = (value) => {\n\t\t\tif (position > safeEnd)\n\t\t\t\ttarget = makeRoom(position);\n\n\t\t\tvar type = typeof value;\n\t\t\tvar length;\n\t\t\tif (type === 'string') {\n\t\t\t\tlet strLength = value.length;\n\t\t\t\tif (bundledStrings && strLength >= 4 && strLength < 0x1000) {\n\t\t\t\t\tif ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {\n\t\t\t\t\t\tlet extStart;\n\t\t\t\t\t\tlet maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;\n\t\t\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\t\t\ttarget = makeRoom(position + maxBytes);\n\t\t\t\t\t\tlet lastBundle;\n\t\t\t\t\t\tif (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle\n\t\t\t\t\t\t\tlastBundle = bundledStrings;\n\t\t\t\t\t\t\ttarget[position] = 0xc8; // ext 16\n\t\t\t\t\t\t\tposition += 3; // reserve for the writing bundle size\n\t\t\t\t\t\t\ttarget[position++] = 0x62; // 'b'\n\t\t\t\t\t\t\textStart = position - start;\n\t\t\t\t\t\t\tposition += 4; // reserve for writing bundle reference\n\t\t\t\t\t\t\twriteBundles(start, pack, 0); // write the last bundles\n\t\t\t\t\t\t\ttargetView.setUint16(extStart + start - 3, position - start - extStart);\n\t\t\t\t\t\t} else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)\n\t\t\t\t\t\t\ttarget[position++] = 0xd6; // fixext 4\n\t\t\t\t\t\t\ttarget[position++] = 0x62; // 'b'\n\t\t\t\t\t\t\textStart = position - start;\n\t\t\t\t\t\t\tposition += 4; // reserve for writing bundle reference\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbundledStrings = ['', '']; // create new ones\n\t\t\t\t\t\tbundledStrings.previous = lastBundle;\n\t\t\t\t\t\tbundledStrings.size = 0;\n\t\t\t\t\t\tbundledStrings.position = extStart;\n\t\t\t\t\t}\n\t\t\t\t\tlet twoByte = hasNonLatin.test(value);\n\t\t\t\t\tbundledStrings[twoByte ? 0 : 1] += value;\n\t\t\t\t\ttarget[position++] = 0xc1;\n\t\t\t\t\tpack(twoByte ? -strLength : strLength);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet headerSize;\n\t\t\t\t// first we estimate the header size, so we can write to the correct location\n\t\t\t\tif (strLength < 0x20) {\n\t\t\t\t\theaderSize = 1;\n\t\t\t\t} else if (strLength < 0x100) {\n\t\t\t\t\theaderSize = 2;\n\t\t\t\t} else if (strLength < 0x10000) {\n\t\t\t\t\theaderSize = 3;\n\t\t\t\t} else {\n\t\t\t\t\theaderSize = 5;\n\t\t\t\t}\n\t\t\t\tlet maxBytes = strLength * 3;\n\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\ttarget = makeRoom(position + maxBytes);\n\n\t\t\t\tif (strLength < 0x40 || !encodeUtf8) {\n\t\t\t\t\tlet i, c1, c2, strPosition = position + headerSize;\n\t\t\t\t\tfor (i = 0; i < strLength; i++) {\n\t\t\t\t\t\tc1 = value.charCodeAt(i);\n\t\t\t\t\t\tif (c1 < 0x80) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1;\n\t\t\t\t\t\t} else if (c1 < 0x800) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 | 0xc0;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80;\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t(c1 & 0xfc00) === 0xd800 &&\n\t\t\t\t\t\t\t((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tc1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 18 | 0xf0;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 & 0x3f | 0x80;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 | 0xe0;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80;\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlength = strPosition - position - headerSize;\n\t\t\t\t} else {\n\t\t\t\t\tlength = encodeUtf8(value, position + headerSize);\n\t\t\t\t}\n\n\t\t\t\tif (length < 0x20) {\n\t\t\t\t\ttarget[position++] = 0xa0 | length;\n\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\tif (headerSize < 2) {\n\t\t\t\t\t\ttarget.copyWithin(position + 2, position + 1, position + 1 + length);\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xd9;\n\t\t\t\t\ttarget[position++] = length;\n\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\tif (headerSize < 3) {\n\t\t\t\t\t\ttarget.copyWithin(position + 3, position + 2, position + 2 + length);\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xda;\n\t\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t\t} else {\n\t\t\t\t\tif (headerSize < 5) {\n\t\t\t\t\t\ttarget.copyWithin(position + 5, position + 3, position + 3 + length);\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xdb;\n\t\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\t\tposition += 4;\n\t\t\t\t}\n\t\t\t\tposition += length;\n\t\t\t} else if (type === 'number') {\n\t\t\t\tif (value >>> 0 === value) {// positive integer, 32-bit or less\n\t\t\t\t\t// positive uint\n\t\t\t\t\tif (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this._writeStruct)) {\n\t\t\t\t\t\ttarget[position++] = value;\n\t\t\t\t\t} else if (value < 0x100) {\n\t\t\t\t\t\ttarget[position++] = 0xcc;\n\t\t\t\t\t\ttarget[position++] = value;\n\t\t\t\t\t} else if (value < 0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0xcd;\n\t\t\t\t\t\ttarget[position++] = value >> 8;\n\t\t\t\t\t\ttarget[position++] = value & 0xff;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0xce;\n\t\t\t\t\t\ttargetView.setUint32(position, value);\n\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t}\n\t\t\t\t} else if (value >> 0 === value) { // negative integer\n\t\t\t\t\tif (value >= -0x20) {\n\t\t\t\t\t\ttarget[position++] = 0x100 + value;\n\t\t\t\t\t} else if (value >= -0x80) {\n\t\t\t\t\t\ttarget[position++] = 0xd0;\n\t\t\t\t\t\ttarget[position++] = value + 0x100;\n\t\t\t\t\t} else if (value >= -0x8000) {\n\t\t\t\t\t\ttarget[position++] = 0xd1;\n\t\t\t\t\t\ttargetView.setInt16(position, value);\n\t\t\t\t\t\tposition += 2;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0xd2;\n\t\t\t\t\t\ttargetView.setInt32(position, value);\n\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet useFloat32;\n\t\t\t\t\tif ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {\n\t\t\t\t\t\ttarget[position++] = 0xca;\n\t\t\t\t\t\ttargetView.setFloat32(position, value);\n\t\t\t\t\t\tlet xShifted;\n\t\t\t\t\t\tif (useFloat32 < 4 ||\n\t\t\t\t\t\t\t\t// this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\t\t\t((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {\n\t\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tposition--; // move back into position for writing a double\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xcb;\n\t\t\t\t\ttargetView.setFloat64(position, value);\n\t\t\t\t\tposition += 8;\n\t\t\t\t}\n\t\t\t} else if (type === 'object' || type === 'function') {\n\t\t\t\tif (!value)\n\t\t\t\t\ttarget[position++] = 0xc0;\n\t\t\t\telse {\n\t\t\t\t\tif (referenceMap) {\n\t\t\t\t\t\tlet referee = referenceMap.get(value);\n\t\t\t\t\t\tif (referee) {\n\t\t\t\t\t\t\tif (!referee.id) {\n\t\t\t\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);\n\t\t\t\t\t\t\t\treferee.id = idsToInsert.push(referee);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0xd6; // fixext 4\n\t\t\t\t\t\t\ttarget[position++] = 0x70; // \"p\" for pointer\n\t\t\t\t\t\t\ttargetView.setUint32(position, referee.id);\n\t\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\treferenceMap.set(value, { offset: position - start });\n\t\t\t\t\t}\n\t\t\t\t\tlet constructor = value.constructor;\n\t\t\t\t\tif (constructor === Object) {\n\t\t\t\t\t\twriteObject(value);\n\t\t\t\t\t} else if (constructor === Array) {\n\t\t\t\t\t\tpackArray(value);\n\t\t\t\t\t} else if (constructor === Map) {\n\t\t\t\t\t\tif (this.mapAsEmptyObject) target[position++] = 0x80;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tlength = value.size;\n\t\t\t\t\t\t\tif (length < 0x10) {\n\t\t\t\t\t\t\t\ttarget[position++] = 0x80 | length;\n\t\t\t\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\t\t\t\ttarget[position++] = 0xde;\n\t\t\t\t\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\t\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttarget[position++] = 0xdf;\n\t\t\t\t\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\t\t\t\t\tposition += 4;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (let [key, entryValue] of value) {\n\t\t\t\t\t\t\t\tpack(key);\n\t\t\t\t\t\t\t\tpack(entryValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = 0, l = extensions.length; i < l; i++) {\n\t\t\t\t\t\t\tlet extensionClass = extensionClasses[i];\n\t\t\t\t\t\t\tif (value instanceof extensionClass) {\n\t\t\t\t\t\t\t\tlet extension = extensions[i];\n\t\t\t\t\t\t\t\tif (extension.write) {\n\t\t\t\t\t\t\t\t\tif (extension.type) {\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd4; // one byte \"tag\" extension\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = extension.type;\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = 0;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tlet writeResult = extension.write.call(this, value);\n\t\t\t\t\t\t\t\t\tif (writeResult === value) { // avoid infinite recursion\n\t\t\t\t\t\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\t\t\tpackArray(value);\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\twriteObject(value);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tpack(writeResult);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet currentTarget = target;\n\t\t\t\t\t\t\t\tlet currentTargetView = targetView;\n\t\t\t\t\t\t\t\tlet currentPosition = position;\n\t\t\t\t\t\t\t\ttarget = null;\n\t\t\t\t\t\t\t\tlet result;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tresult = extension.pack.call(this, value, (size) => {\n\t\t\t\t\t\t\t\t\t\t// restore target and use it\n\t\t\t\t\t\t\t\t\t\ttarget = currentTarget;\n\t\t\t\t\t\t\t\t\t\tcurrentTarget = null;\n\t\t\t\t\t\t\t\t\t\tposition += size;\n\t\t\t\t\t\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\t\t\t\t\t\tmakeRoom(position);\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\ttarget, targetView, position: position - size\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t}, pack);\n\t\t\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\t\t\t// restore current target information (unless already restored)\n\t\t\t\t\t\t\t\t\tif (currentTarget) {\n\t\t\t\t\t\t\t\t\t\ttarget = currentTarget;\n\t\t\t\t\t\t\t\t\t\ttargetView = currentTargetView;\n\t\t\t\t\t\t\t\t\t\tposition = currentPosition;\n\t\t\t\t\t\t\t\t\t\tsafeEnd = target.length - 10;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\t\t\tif (result.length + position > safeEnd)\n\t\t\t\t\t\t\t\t\t\tmakeRoom(result.length + position);\n\t\t\t\t\t\t\t\t\tposition = writeExtensionData(result, target, position, extension.type);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// check isArray after extensions, because extensions can extend Array\n\t\t\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\t\t\tpackArray(value);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// use this as an alternate mechanism for expressing how to serialize\n\t\t\t\t\t\t\tif (value.toJSON) {\n\t\t\t\t\t\t\t\tconst json = value.toJSON();\n\t\t\t\t\t\t\t\t// if for some reason value.toJSON returns itself it'll loop forever\n\t\t\t\t\t\t\t\tif (json !== value)\n\t\t\t\t\t\t\t\t\treturn pack(json);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// if there is a writeFunction, use it, otherwise just encode as undefined\n\t\t\t\t\t\t\tif (type === 'function')\n\t\t\t\t\t\t\t\treturn pack(this.writeFunction && this.writeFunction(value));\n\n\t\t\t\t\t\t\t// no extension found, write as plain object\n\t\t\t\t\t\t\twriteObject(value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (type === 'boolean') {\n\t\t\t\ttarget[position++] = value ? 0xc3 : 0xc2;\n\t\t\t} else if (type === 'bigint') {\n\t\t\t\tif (value < 0x8000000000000000 && value >= -0x8000000000000000) {\n\t\t\t\t\t// use a signed int as long as it fits\n\t\t\t\t\ttarget[position++] = 0xd3;\n\t\t\t\t\ttargetView.setBigInt64(position, value);\n\t\t\t\t} else if (value < 0x10000000000000000 && value > 0) {\n\t\t\t\t\t// if we can fit an unsigned int, use that\n\t\t\t\t\ttarget[position++] = 0xcf;\n\t\t\t\t\ttargetView.setBigUint64(position, value);\n\t\t\t\t} else {\n\t\t\t\t\t// overflow\n\t\t\t\t\tif (this.largeBigIntToFloat) {\n\t\t\t\t\t\ttarget[position++] = 0xcb;\n\t\t\t\t\t\ttargetView.setFloat64(position, Number(value));\n\t\t\t\t\t} else if (this.largeBigIntToString) {\n\t\t\t\t\t\treturn pack(value.toString());\n\t\t\t\t\t} else if (this.useBigIntExtension || this.moreTypes) {\n\t\t\t\t\t\tlet empty = value < 0 ? BigInt(-1) : BigInt(0);\n\n\t\t\t\t\t\tlet array;\n\t\t\t\t\t\tif (value >> BigInt(0x10000) === empty) {\n\t\t\t\t\t\t\tlet mask = BigInt(0x10000000000000000) - BigInt(1); // literal would overflow\n\t\t\t\t\t\t\tlet chunks = [];\n\t\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\t\tchunks.push(value & mask);\n\t\t\t\t\t\t\t\tif ((value >> BigInt(63)) === empty) break;\n\t\t\t\t\t\t\t\tvalue >>= BigInt(64);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tarray = new Uint8Array(new BigUint64Array(chunks).buffer);\n\t\t\t\t\t\t\tarray.reverse();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlet invert = value < 0;\n\t\t\t\t\t\t\tlet string = (invert ? ~value : value).toString(16);\n\t\t\t\t\t\t\tif (string.length % 2) {\n\t\t\t\t\t\t\t\tstring = '0' + string;\n\t\t\t\t\t\t\t} else if (parseInt(string.charAt(0), 16) >= 8) {\n\t\t\t\t\t\t\t\tstring = '00' + string;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (hasNodeBuffer) {\n\t\t\t\t\t\t\t\tarray = Buffer.from(string, 'hex');\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tarray = new Uint8Array(string.length / 2);\n\t\t\t\t\t\t\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\t\t\t\t\t\t\tarray[i] = parseInt(string.slice(i * 2, i * 2 + 2), 16);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (invert) {\n\t\t\t\t\t\t\t\tfor (let i = 0; i < array.length; i++) array[i] = ~array[i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (array.length + position > safeEnd)\n\t\t\t\t\t\t\tmakeRoom(array.length + position);\n\t\t\t\t\t\tposition = writeExtensionData(array, target, position, 0x42);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +\n\t\t\t\t\t\t\t' useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set' +\n\t\t\t\t\t\t\t' largeBigIntToString to convert to string');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tposition += 8;\n\t\t\t} else if (type === 'undefined') {\n\t\t\t\tif (this.encodeUndefinedAsNil)\n\t\t\t\t\ttarget[position++] = 0xc0;\n\t\t\t\telse {\n\t\t\t\t\ttarget[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite\n\t\t\t\t\ttarget[position++] = 0;\n\t\t\t\t\ttarget[position++] = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new Error('Unknown type: ' + type);\n\t\t\t}\n\t\t};\n\n\t\tconst writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues) ? (object) => {\n\t\t\t// this method is slightly slower, but generates \"preferred serialization\" (optimally small for smaller objects)\n\t\t\tlet keys;\n\t\t\tif (this.skipValues) {\n\t\t\t\tkeys = [];\n\t\t\t\tfor (let key in object) {\n\t\t\t\t\tif ((typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) &&\n\t\t\t\t\t\t!this.skipValues.includes(object[key]))\n\t\t\t\t\t\tkeys.push(key);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tkeys = Object.keys(object);\n\t\t\t}\n\t\t\tlet length = keys.length;\n\t\t\tif (length < 0x10) {\n\t\t\t\ttarget[position++] = 0x80 | length;\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xde;\n\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xdf;\n\t\t\t\ttargetView.setUint32(position, length);\n\t\t\t\tposition += 4;\n\t\t\t}\n\t\t\tlet key;\n\t\t\tif (this.coercibleKeyAsNumber) {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tkey = keys[i];\n\t\t\t\t\tlet num = Number(key);\n\t\t\t\t\tpack(isNaN(num) ? key : num);\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tpack(key = keys[i]);\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\ttarget[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards\n\t\t\tlet objectOffset = position - start;\n\t\t\tposition += 2;\n\t\t\tlet size = 0;\n\t\t\tfor (let key in object) {\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tpack(key);\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t\tsize++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (size > 0xffff) {\n\t\t\t\tthrow new Error('Object is too large to serialize with fast 16-bit map size,' +\n\t\t\t\t' use the \"variableMapSize\" option to serialize this object');\n\t\t\t}\n\t\t\ttarget[objectOffset++ + start] = size >> 8;\n\t\t\ttarget[objectOffset + start] = size & 0xff;\n\t\t};\n\n\t\tconst writeRecord = this.useRecords === false ? writePlainObject :\n\t\t(options.progressiveRecords && !useTwoByteRecords) ?  // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)\n\t\t(object) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));\n\t\t\tlet objectOffset = position++ - start;\n\t\t\tlet wroteKeys;\n\t\t\tfor (let key in object) {\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tnextTransition = transition[key];\n\t\t\t\t\tif (nextTransition)\n\t\t\t\t\t\ttransition = nextTransition;\n\t\t\t\t\telse {\n\t\t\t\t\t\t// record doesn't exist, create full new record and insert it\n\t\t\t\t\t\tlet keys = Object.keys(object);\n\t\t\t\t\t\tlet lastTransition = transition;\n\t\t\t\t\t\ttransition = structures.transitions;\n\t\t\t\t\t\tlet newTransitions = 0;\n\t\t\t\t\t\tfor (let i = 0, l = keys.length; i < l; i++) {\n\t\t\t\t\t\t\tlet key = keys[i];\n\t\t\t\t\t\t\tnextTransition = transition[key];\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null);\n\t\t\t\t\t\t\t\tnewTransitions++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (objectOffset + start + 1 == position) {\n\t\t\t\t\t\t\t// first key, so we don't need to insert, we can just write record directly\n\t\t\t\t\t\t\tposition--;\n\t\t\t\t\t\t\tnewRecord(transition, keys, newTransitions);\n\t\t\t\t\t\t} else // otherwise we need to insert the record, moving existing data after the record\n\t\t\t\t\t\t\tinsertNewRecord(transition, keys, objectOffset, newTransitions);\n\t\t\t\t\t\twroteKeys = true;\n\t\t\t\t\t\ttransition = lastTransition[key];\n\t\t\t\t\t}\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!wroteKeys) {\n\t\t\t\tlet recordId = transition[RECORD_SYMBOL];\n\t\t\t\tif (recordId)\n\t\t\t\t\ttarget[objectOffset + start] = recordId;\n\t\t\t\telse\n\t\t\t\t\tinsertNewRecord(transition, Object.keys(object), objectOffset, 0);\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));\n\t\t\tlet newTransitions = 0;\n\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\tnextTransition = transition[key];\n\t\t\t\tif (!nextTransition) {\n\t\t\t\t\tnextTransition = transition[key] = Object.create(null);\n\t\t\t\t\tnewTransitions++;\n\t\t\t\t}\n\t\t\t\ttransition = nextTransition;\n\t\t\t}\n\t\t\tlet recordId = transition[RECORD_SYMBOL];\n\t\t\tif (recordId) {\n\t\t\t\tif (recordId >= 0x60 && useTwoByteRecords) {\n\t\t\t\t\ttarget[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;\n\t\t\t\t\ttarget[position++] = recordId >> 5;\n\t\t\t\t} else\n\t\t\t\t\ttarget[position++] = recordId;\n\t\t\t} else {\n\t\t\t\tnewRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);\n\t\t\t}\n\t\t\t// now write the values\n\t\t\tfor (let key in object)\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tpack(object[key]);\n\t\t\t\t}\n\t\t};\n\n\t\t// create reference to useRecords if useRecords is a function\n\t\tconst checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;\n\n\t\tconst writeObject = checkUseRecords ? (object) => {\n\t\t\tcheckUseRecords(object) ? writeRecord(object) : writePlainObject(object);\n\t\t} : writeRecord;\n\n\t\tconst writeStruct = (object) => {\n\t\t\tlet newPosition = packr._writeStruct(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {\n\t\t\t\tif (notifySharedUpdate)\n\t\t\t\t\treturn hasSharedUpdate = true;\n\t\t\t\tposition = newPosition;\n\t\t\t\tlet startTarget = target;\n\t\t\t\tpack(value);\n\t\t\t\tresetStructures();\n\t\t\t\tif (startTarget !== target) {\n\t\t\t\t\treturn { position, targetView, target }; // indicate the buffer was re-allocated\n\t\t\t\t}\n\t\t\t\treturn position;\n\t\t\t});\n\t\t\tif (newPosition === 0) // bail and go to a msgpack object\n\t\t\t\treturn writeObject(object);\n\t\t\tposition = newPosition;\n\t\t};\n\n\t\tconst makeRoom = (end) => {\n\t\t\tlet newSize;\n\t\t\tif (end > 0x1000000) {\n\t\t\t\t// special handling for really large buffers\n\t\t\t\tif ((end - start) > MAX_BUFFER_SIZE)\n\t\t\t\t\tthrow new Error('Packed buffer would be larger than maximum buffer size');\n\t\t\t\tnewSize = Math.min(MAX_BUFFER_SIZE,\n\t\t\t\t\tMath.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);\n\t\t\t} else // faster handling for smaller buffers\n\t\t\t\tnewSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;\n\t\t\tlet newBuffer = new ByteArrayAllocate(newSize);\n\t\t\ttargetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));\n\t\t\tend = Math.min(end, target.length);\n\t\t\tif (target.copy)\n\t\t\t\ttarget.copy(newBuffer, 0, start, end);\n\t\t\telse\n\t\t\t\tnewBuffer.set(target.slice(start, end));\n\t\t\tposition -= start;\n\t\t\tstart = 0;\n\t\t\tsafeEnd = newBuffer.length - 10;\n\t\t\treturn target = newBuffer;\n\t\t};\n\t\tconst newRecord = (transition, keys, newTransitions) => {\n\t\t\tlet recordId = structures.nextId;\n\t\t\tif (!recordId)\n\t\t\t\trecordId = 0x40;\n\t\t\tif (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {\n\t\t\t\trecordId = structures.nextOwnId;\n\t\t\t\tif (!(recordId < maxStructureId))\n\t\t\t\t\trecordId = sharedLimitId;\n\t\t\t\tstructures.nextOwnId = recordId + 1;\n\t\t\t} else {\n\t\t\t\tif (recordId >= maxStructureId)// cycle back around\n\t\t\t\t\trecordId = sharedLimitId;\n\t\t\t\tstructures.nextId = recordId + 1;\n\t\t\t}\n\t\t\tlet highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;\n\t\t\ttransition[RECORD_SYMBOL] = recordId;\n\t\t\ttransition.__keys__ = keys;\n\t\t\tstructures[recordId - 0x40] = keys;\n\n\t\t\tif (recordId < sharedLimitId) {\n\t\t\t\tkeys.isShared = true;\n\t\t\t\tstructures.sharedLength = recordId - 0x3f;\n\t\t\t\thasSharedUpdate = true;\n\t\t\t\tif (highByte >= 0) {\n\t\t\t\t\ttarget[position++] = (recordId & 0x1f) + 0x60;\n\t\t\t\t\ttarget[position++] = highByte;\n\t\t\t\t} else {\n\t\t\t\t\ttarget[position++] = recordId;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (highByte >= 0) {\n\t\t\t\t\ttarget[position++] = 0xd5; // fixext 2\n\t\t\t\t\ttarget[position++] = 0x72; // \"r\" record defintion extension type\n\t\t\t\t\ttarget[position++] = (recordId & 0x1f) + 0x60;\n\t\t\t\t\ttarget[position++] = highByte;\n\t\t\t\t} else {\n\t\t\t\t\ttarget[position++] = 0xd4; // fixext 1\n\t\t\t\t\ttarget[position++] = 0x72; // \"r\" record defintion extension type\n\t\t\t\t\ttarget[position++] = recordId;\n\t\t\t\t}\n\n\t\t\t\tif (newTransitions)\n\t\t\t\t\ttransitionsCount += serializationsSinceTransitionRebuild * newTransitions;\n\t\t\t\t// record the removal of the id, we can maintain our shared structure\n\t\t\t\tif (recordIdsToRemove.length >= maxOwnStructures)\n\t\t\t\t\trecordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones\n\t\t\t\trecordIdsToRemove.push(transition);\n\t\t\t\tpack(keys);\n\t\t\t}\n\t\t};\n\t\tconst insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {\n\t\t\tlet mainTarget = target;\n\t\t\tlet mainPosition = position;\n\t\t\tlet mainSafeEnd = safeEnd;\n\t\t\tlet mainStart = start;\n\t\t\ttarget = keysTarget;\n\t\t\tposition = 0;\n\t\t\tstart = 0;\n\t\t\tif (!target)\n\t\t\t\tkeysTarget = target = new ByteArrayAllocate(8192);\n\t\t\tsafeEnd = target.length - 10;\n\t\t\tnewRecord(transition, keys, newTransitions);\n\t\t\tkeysTarget = target;\n\t\t\tlet keysPosition = position;\n\t\t\ttarget = mainTarget;\n\t\t\tposition = mainPosition;\n\t\t\tsafeEnd = mainSafeEnd;\n\t\t\tstart = mainStart;\n\t\t\tif (keysPosition > 1) {\n\t\t\t\tlet newEnd = position + keysPosition - 1;\n\t\t\t\tif (newEnd > safeEnd)\n\t\t\t\t\tmakeRoom(newEnd);\n\t\t\t\tlet insertionPosition = insertionOffset + start;\n\t\t\t\ttarget.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);\n\t\t\t\ttarget.set(keysTarget.slice(0, keysPosition), insertionPosition);\n\t\t\t\tposition = newEnd;\n\t\t\t} else {\n\t\t\t\ttarget[insertionOffset + start] = keysTarget[0];\n\t\t\t}\n\t\t};\n\t}\n\tuseBuffer(buffer) {\n\t\t// this means we are finished using our own buffer and we can write over it safely\n\t\ttarget = buffer;\n\t\ttarget.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength));\n\t\ttargetView = target.dataView;\n\t\tposition = 0;\n\t}\n\tset position (value) {\n\t\tposition = value;\n\t}\n\tget position() {\n\t\treturn position;\n\t}\n\tclearSharedData() {\n\t\tif (this.structures)\n\t\t\tthis.structures = [];\n\t\tif (this.typedStructs)\n\t\t\tthis.typedStructs = [];\n\t}\n}\n\nextensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, DataView, C1Type ];\nextensions = [{\n\tpack(date, allocateForWrite, pack) {\n\t\tlet seconds = date.getTime() / 1000;\n\t\tif ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 32\n\t\t\tlet { target, targetView, position} = allocateForWrite(6);\n\t\t\ttarget[position++] = 0xd6;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttargetView.setUint32(position, seconds);\n\t\t} else if (seconds > 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 64\n\t\t\tlet { target, targetView, position} = allocateForWrite(10);\n\t\t\ttarget[position++] = 0xd7;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttargetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));\n\t\t\ttargetView.setUint32(position + 4, seconds);\n\t\t} else if (isNaN(seconds)) {\n\t\t\tif (this.onInvalidDate) {\n\t\t\t\tallocateForWrite(0);\n\t\t\t\treturn pack(this.onInvalidDate());\n\t\t\t}\n\t\t\t// Intentionally invalid timestamp\n\t\t\tlet { target, targetView, position} = allocateForWrite(3);\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttarget[position++] = 0xff;\n\t\t} else {\n\t\t\t// Timestamp 96\n\t\t\tlet { target, targetView, position} = allocateForWrite(15);\n\t\t\ttarget[position++] = 0xc7;\n\t\t\ttarget[position++] = 12;\n\t\t\ttarget[position++] = 0xff;\n\t\t\ttargetView.setUint32(position, date.getMilliseconds() * 1000000);\n\t\t\ttargetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));\n\t\t}\n\t}\n}, {\n\tpack(set, allocateForWrite, pack) {\n\t\tif (this.setAsEmptyObject) {\n\t\t\tallocateForWrite(0);\n\t\t\treturn pack({});\n\t\t}\n\t\tlet array = Array.from(set);\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0x73; // 's' for Set\n\t\t\ttarget[position++] = 0;\n\t\t}\n\t\tpack(array);\n\t}\n}, {\n\tpack(error, allocateForWrite, pack) {\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0x65; // 'e' for error\n\t\t\ttarget[position++] = 0;\n\t\t}\n\t\tpack([ error.name, error.message, error.cause ]);\n\t}\n}, {\n\tpack(regex, allocateForWrite, pack) {\n\t\tlet { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);\n\t\tif (this.moreTypes) {\n\t\t\ttarget[position++] = 0xd4;\n\t\t\ttarget[position++] = 0x78; // 'x' for regeXp\n\t\t\ttarget[position++] = 0;\n\t\t}\n\t\tpack([ regex.source, regex.flags ]);\n\t}\n}, {\n\tpack(arrayBuffer, allocateForWrite) {\n\t\tif (this.moreTypes)\n\t\t\twriteExtBuffer(arrayBuffer, 0x10, allocateForWrite);\n\t\telse\n\t\t\twriteBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);\n\t}\n}, {\n\tpack(typedArray, allocateForWrite) {\n\t\tlet constructor = typedArray.constructor;\n\t\tif (constructor !== ByteArray && this.moreTypes)\n\t\t\twriteExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);\n\t\telse\n\t\t\twriteBuffer(typedArray, allocateForWrite);\n\t}\n}, {\n\tpack(arrayBuffer, allocateForWrite) {\n\t\tif (this.moreTypes)\n\t\t\twriteExtBuffer(arrayBuffer, 0x11, allocateForWrite);\n\t\telse\n\t\t\twriteBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);\n\t}\n}, {\n\tpack(c1, allocateForWrite) { // specific 0xC1 object\n\t\tlet { target, position} = allocateForWrite(1);\n\t\ttarget[position] = 0xc1;\n\t}\n}];\n\nfunction writeExtBuffer(typedArray, type, allocateForWrite, encode) {\n\tlet length = typedArray.byteLength;\n\tif (length + 1 < 0x100) {\n\t\tvar { target, position } = allocateForWrite(4 + length);\n\t\ttarget[position++] = 0xc7;\n\t\ttarget[position++] = length + 1;\n\t} else if (length + 1 < 0x10000) {\n\t\tvar { target, position } = allocateForWrite(5 + length);\n\t\ttarget[position++] = 0xc8;\n\t\ttarget[position++] = (length + 1) >> 8;\n\t\ttarget[position++] = (length + 1) & 0xff;\n\t} else {\n\t\tvar { target, position, targetView } = allocateForWrite(7 + length);\n\t\ttarget[position++] = 0xc9;\n\t\ttargetView.setUint32(position, length + 1); // plus one for the type byte\n\t\tposition += 4;\n\t}\n\ttarget[position++] = 0x74; // \"t\" for typed array\n\ttarget[position++] = type;\n\tif (!typedArray.buffer) typedArray = new Uint8Array(typedArray);\n\ttarget.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);\n}\nfunction writeBuffer(buffer, allocateForWrite) {\n\tlet length = buffer.byteLength;\n\tvar target, position;\n\tif (length < 0x100) {\n\t\tvar { target, position } = allocateForWrite(length + 2);\n\t\ttarget[position++] = 0xc4;\n\t\ttarget[position++] = length;\n\t} else if (length < 0x10000) {\n\t\tvar { target, position } = allocateForWrite(length + 3);\n\t\ttarget[position++] = 0xc5;\n\t\ttarget[position++] = length >> 8;\n\t\ttarget[position++] = length & 0xff;\n\t} else {\n\t\tvar { target, position, targetView } = allocateForWrite(length + 5);\n\t\ttarget[position++] = 0xc6;\n\t\ttargetView.setUint32(position, length);\n\t\tposition += 4;\n\t}\n\ttarget.set(buffer, position);\n}\n\nfunction writeExtensionData(result, target, position, type) {\n\tlet length = result.length;\n\tswitch (length) {\n\t\tcase 1:\n\t\t\ttarget[position++] = 0xd4;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\ttarget[position++] = 0xd5;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\ttarget[position++] = 0xd6;\n\t\t\tbreak;\n\t\tcase 8:\n\t\t\ttarget[position++] = 0xd7;\n\t\t\tbreak;\n\t\tcase 16:\n\t\t\ttarget[position++] = 0xd8;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (length < 0x100) {\n\t\t\t\ttarget[position++] = 0xc7;\n\t\t\t\ttarget[position++] = length;\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xc8;\n\t\t\t\ttarget[position++] = length >> 8;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xc9;\n\t\t\t\ttarget[position++] = length >> 24;\n\t\t\t\ttarget[position++] = (length >> 16) & 0xff;\n\t\t\t\ttarget[position++] = (length >> 8) & 0xff;\n\t\t\t\ttarget[position++] = length & 0xff;\n\t\t\t}\n\t}\n\ttarget[position++] = type;\n\ttarget.set(result, position);\n\tposition += length;\n\treturn position;\n}\n\nfunction insertIds(serialized, idsToInsert) {\n\t// insert the ids that need to be referenced for structured clones\n\tlet nextId;\n\tlet distanceToMove = idsToInsert.length * 6;\n\tlet lastEnd = serialized.length - distanceToMove;\n\twhile (nextId = idsToInsert.pop()) {\n\t\tlet offset = nextId.offset;\n\t\tlet id = nextId.id;\n\t\tserialized.copyWithin(offset + distanceToMove, offset, lastEnd);\n\t\tdistanceToMove -= 6;\n\t\tlet position = offset + distanceToMove;\n\t\tserialized[position++] = 0xd6;\n\t\tserialized[position++] = 0x69; // 'i'\n\t\tserialized[position++] = id >> 24;\n\t\tserialized[position++] = (id >> 16) & 0xff;\n\t\tserialized[position++] = (id >> 8) & 0xff;\n\t\tserialized[position++] = id & 0xff;\n\t\tlastEnd = offset;\n\t}\n\treturn serialized;\n}\n\nfunction writeBundles(start, pack, incrementPosition) {\n\tif (bundledStrings.length > 0) {\n\t\ttargetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);\n\t\tbundledStrings.stringsPosition = position - start;\n\t\tlet writeStrings = bundledStrings;\n\t\tbundledStrings = null;\n\t\tpack(writeStrings[0]);\n\t\tpack(writeStrings[1]);\n\t}\n}\n\nexport function addExtension(extension) {\n\tif (extension.Class) {\n\t\tif (!extension.pack && !extension.write)\n\t\t\tthrow new Error('Extension has no pack or write function');\n\t\tif (extension.pack && !extension.type)\n\t\t\tthrow new Error('Extension has no type (numeric code to identify the extension)');\n\t\textensionClasses.unshift(extension.Class);\n\t\textensions.unshift(extension);\n\t}\n\tunpackAddExtension(extension);\n}\nfunction prepareStructures(structures, packr) {\n\tstructures.isCompatible = (existingStructures) => {\n\t\tlet compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);\n\t\tif (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction\n\t\t\tpackr._mergeStructures(existingStructures);\n\t\treturn compatible;\n\t};\n\treturn structures;\n}\n\n// Marker for downstream libraries (e.g. structon) to detect that this Packr\n// supports per-instance struct-encoding hooks (this._writeStruct,\n// this._prepareStructures).  See `pack` for the dispatch.\nPackr.SUPPORTS_STRUCT_HOOKS = true;\n\nlet defaultPackr = new Packr({ useRecords: false });\nexport const pack = defaultPackr.pack;\nexport const encode = defaultPackr.pack;\nexport const Encoder = Packr;\nexport { FLOAT32_OPTIONS } from './unpack.js';\nimport { FLOAT32_OPTIONS } from './unpack.js';\nexport const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS;\nexport const REUSE_BUFFER_MODE = 512;\nexport const RESET_BUFFER_MODE = 1024;\nexport const RESERVE_START_SPACE = 2048;\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst isLinux = () => process.platform === 'linux';\n\nlet report = null;\nconst getReport = () => {\n  if (!report) {\n    /* istanbul ignore next */\n    if (isLinux() && process.report) {\n      const orig = process.report.excludeNetwork;\n      process.report.excludeNetwork = true;\n      report = process.report.getReport();\n      process.report.excludeNetwork = orig;\n    } else {\n      report = {};\n    }\n  }\n  return report;\n};\n\nmodule.exports = { isLinux, getReport };\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst fs = require('fs');\n\nconst LDD_PATH = '/usr/bin/ldd';\nconst SELF_PATH = '/proc/self/exe';\nconst MAX_LENGTH = 2048;\n\n/**\n * Read the content of a file synchronous\n *\n * @param {string} path\n * @returns {Buffer}\n */\nconst readFileSync = (path) => {\n  const fd = fs.openSync(path, 'r');\n  const buffer = Buffer.alloc(MAX_LENGTH);\n  const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0);\n  fs.close(fd, () => {});\n  return buffer.subarray(0, bytesRead);\n};\n\n/**\n * Read the content of a file\n *\n * @param {string} path\n * @returns {Promise<Buffer>}\n */\nconst readFile = (path) => new Promise((resolve, reject) => {\n  fs.open(path, 'r', (err, fd) => {\n    if (err) {\n      reject(err);\n    } else {\n      const buffer = Buffer.alloc(MAX_LENGTH);\n      fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {\n        resolve(buffer.subarray(0, bytesRead));\n        fs.close(fd, () => {});\n      });\n    }\n  });\n});\n\nmodule.exports = {\n  LDD_PATH,\n  SELF_PATH,\n  readFileSync,\n  readFile\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst interpreterPath = (elf) => {\n  if (elf.length < 64) {\n    return null;\n  }\n  if (elf.readUInt32BE(0) !== 0x7F454C46) {\n    // Unexpected magic bytes\n    return null;\n  }\n  if (elf.readUInt8(4) !== 2) {\n    // Not a 64-bit ELF\n    return null;\n  }\n  if (elf.readUInt8(5) !== 1) {\n    // Not little-endian\n    return null;\n  }\n  const offset = elf.readUInt32LE(32);\n  const size = elf.readUInt16LE(54);\n  const count = elf.readUInt16LE(56);\n  for (let i = 0; i < count; i++) {\n    const headerOffset = offset + (i * size);\n    const type = elf.readUInt32LE(headerOffset);\n    if (type === 3) {\n      const fileOffset = elf.readUInt32LE(headerOffset + 8);\n      const fileSize = elf.readUInt32LE(headerOffset + 32);\n      return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\\0.*$/g, '');\n    }\n  }\n  return null;\n};\n\nmodule.exports = {\n  interpreterPath\n};\n","// Copyright 2017 Lovell Fuller and others.\n// SPDX-License-Identifier: Apache-2.0\n\n'use strict';\n\nconst childProcess = require('child_process');\nconst { isLinux, getReport } = require('./process');\nconst { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem');\nconst { interpreterPath } = require('./elf');\n\nlet cachedFamilyInterpreter;\nlet cachedFamilyFilesystem;\nlet cachedVersionFilesystem;\n\nconst command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true';\nlet commandOut = '';\n\nconst safeCommand = () => {\n  if (!commandOut) {\n    return new Promise((resolve) => {\n      childProcess.exec(command, (err, out) => {\n        commandOut = err ? ' ' : out;\n        resolve(commandOut);\n      });\n    });\n  }\n  return commandOut;\n};\n\nconst safeCommandSync = () => {\n  if (!commandOut) {\n    try {\n      commandOut = childProcess.execSync(command, { encoding: 'utf8' });\n    } catch (_err) {\n      commandOut = ' ';\n    }\n  }\n  return commandOut;\n};\n\n/**\n * A String constant containing the value `glibc`.\n * @type {string}\n * @public\n */\nconst GLIBC = 'glibc';\n\n/**\n * A Regexp constant to get the GLIBC Version.\n * @type {string}\n */\nconst RE_GLIBC_VERSION = /LIBC[a-z0-9 \\-).]*?(\\d+\\.\\d+)/i;\n\n/**\n * A String constant containing the value `musl`.\n * @type {string}\n * @public\n */\nconst MUSL = 'musl';\n\nconst isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-');\n\nconst familyFromReport = () => {\n  const report = getReport();\n  if (report.header && report.header.glibcVersionRuntime) {\n    return GLIBC;\n  }\n  if (Array.isArray(report.sharedObjects)) {\n    if (report.sharedObjects.some(isFileMusl)) {\n      return MUSL;\n    }\n  }\n  return null;\n};\n\nconst familyFromCommand = (out) => {\n  const [getconf, ldd1] = out.split(/[\\r\\n]+/);\n  if (getconf && getconf.includes(GLIBC)) {\n    return GLIBC;\n  }\n  if (ldd1 && ldd1.includes(MUSL)) {\n    return MUSL;\n  }\n  return null;\n};\n\nconst familyFromInterpreterPath = (path) => {\n  if (path) {\n    if (path.includes('/ld-musl-')) {\n      return MUSL;\n    } else if (path.includes('/ld-linux-')) {\n      return GLIBC;\n    }\n  }\n  return null;\n};\n\nconst getFamilyFromLddContent = (content) => {\n  content = content.toString();\n  if (content.includes('musl')) {\n    return MUSL;\n  }\n  if (content.includes('GNU C Library')) {\n    return GLIBC;\n  }\n  return null;\n};\n\nconst familyFromFilesystem = async () => {\n  if (cachedFamilyFilesystem !== undefined) {\n    return cachedFamilyFilesystem;\n  }\n  cachedFamilyFilesystem = null;\n  try {\n    const lddContent = await readFile(LDD_PATH);\n    cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n  } catch (e) {}\n  return cachedFamilyFilesystem;\n};\n\nconst familyFromFilesystemSync = () => {\n  if (cachedFamilyFilesystem !== undefined) {\n    return cachedFamilyFilesystem;\n  }\n  cachedFamilyFilesystem = null;\n  try {\n    const lddContent = readFileSync(LDD_PATH);\n    cachedFamilyFilesystem = getFamilyFromLddContent(lddContent);\n  } catch (e) {}\n  return cachedFamilyFilesystem;\n};\n\nconst familyFromInterpreter = async () => {\n  if (cachedFamilyInterpreter !== undefined) {\n    return cachedFamilyInterpreter;\n  }\n  cachedFamilyInterpreter = null;\n  try {\n    const selfContent = await readFile(SELF_PATH);\n    const path = interpreterPath(selfContent);\n    cachedFamilyInterpreter = familyFromInterpreterPath(path);\n  } catch (e) {}\n  return cachedFamilyInterpreter;\n};\n\nconst familyFromInterpreterSync = () => {\n  if (cachedFamilyInterpreter !== undefined) {\n    return cachedFamilyInterpreter;\n  }\n  cachedFamilyInterpreter = null;\n  try {\n    const selfContent = readFileSync(SELF_PATH);\n    const path = interpreterPath(selfContent);\n    cachedFamilyInterpreter = familyFromInterpreterPath(path);\n  } catch (e) {}\n  return cachedFamilyInterpreter;\n};\n\n/**\n * Resolves with the libc family when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst family = async () => {\n  let family = null;\n  if (isLinux()) {\n    family = await familyFromInterpreter();\n    if (!family) {\n      family = await familyFromFilesystem();\n      if (!family) {\n        family = familyFromReport();\n      }\n      if (!family) {\n        const out = await safeCommand();\n        family = familyFromCommand(out);\n      }\n    }\n  }\n  return family;\n};\n\n/**\n * Returns the libc family when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst familySync = () => {\n  let family = null;\n  if (isLinux()) {\n    family = familyFromInterpreterSync();\n    if (!family) {\n      family = familyFromFilesystemSync();\n      if (!family) {\n        family = familyFromReport();\n      }\n      if (!family) {\n        const out = safeCommandSync();\n        family = familyFromCommand(out);\n      }\n    }\n  }\n  return family;\n};\n\n/**\n * Resolves `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {Promise<boolean>}\n */\nconst isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC;\n\n/**\n * Returns `true` only when the platform is Linux and the libc family is not `glibc`.\n * @returns {boolean}\n */\nconst isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC;\n\nconst versionFromFilesystem = async () => {\n  if (cachedVersionFilesystem !== undefined) {\n    return cachedVersionFilesystem;\n  }\n  cachedVersionFilesystem = null;\n  try {\n    const lddContent = await readFile(LDD_PATH);\n    const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n    if (versionMatch) {\n      cachedVersionFilesystem = versionMatch[1];\n    }\n  } catch (e) {}\n  return cachedVersionFilesystem;\n};\n\nconst versionFromFilesystemSync = () => {\n  if (cachedVersionFilesystem !== undefined) {\n    return cachedVersionFilesystem;\n  }\n  cachedVersionFilesystem = null;\n  try {\n    const lddContent = readFileSync(LDD_PATH);\n    const versionMatch = lddContent.match(RE_GLIBC_VERSION);\n    if (versionMatch) {\n      cachedVersionFilesystem = versionMatch[1];\n    }\n  } catch (e) {}\n  return cachedVersionFilesystem;\n};\n\nconst versionFromReport = () => {\n  const report = getReport();\n  if (report.header && report.header.glibcVersionRuntime) {\n    return report.header.glibcVersionRuntime;\n  }\n  return null;\n};\n\nconst versionSuffix = (s) => s.trim().split(/\\s+/)[1];\n\nconst versionFromCommand = (out) => {\n  const [getconf, ldd1, ldd2] = out.split(/[\\r\\n]+/);\n  if (getconf && getconf.includes(GLIBC)) {\n    return versionSuffix(getconf);\n  }\n  if (ldd1 && ldd2 && ldd1.includes(MUSL)) {\n    return versionSuffix(ldd2);\n  }\n  return null;\n};\n\n/**\n * Resolves with the libc version when it can be determined, `null` otherwise.\n * @returns {Promise<?string>}\n */\nconst version = async () => {\n  let version = null;\n  if (isLinux()) {\n    version = await versionFromFilesystem();\n    if (!version) {\n      version = versionFromReport();\n    }\n    if (!version) {\n      const out = await safeCommand();\n      version = versionFromCommand(out);\n    }\n  }\n  return version;\n};\n\n/**\n * Returns the libc version when it can be determined, `null` otherwise.\n * @returns {?string}\n */\nconst versionSync = () => {\n  let version = null;\n  if (isLinux()) {\n    version = versionFromFilesystemSync();\n    if (!version) {\n      version = versionFromReport();\n    }\n    if (!version) {\n      const out = safeCommandSync();\n      version = versionFromCommand(out);\n    }\n  }\n  return version;\n};\n\nmodule.exports = {\n  GLIBC,\n  MUSL,\n  family,\n  familySync,\n  isNonGlibcLinux,\n  isNonGlibcLinuxSync,\n  version,\n  versionSync\n};\n","var fs = require('fs')\nvar path = require('path')\nvar url = require('url')\nvar os = require('os')\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar versions = process.versions\nvar abi = versions.modules\nif (versions.deno || process.isBun) {\n  // both Deno and Bun made the very poor decision to shoot themselves in the foot and lie about support for ABI\n  // (which they do not have)\n  abi = 'unsupported'\n}\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isMusl(platform) ? 'musl' : 'glibc')\n\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n  return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n  dir = path.resolve(dir || '.')\n  var packageName = ''\n  var packageNameError\n  try {\n    packageName = runtimeRequire(path.join(dir, 'package.json')).name;\n    var varName = packageName.toUpperCase().replace(/-/g, '_')\n    if (process.env[varName + '_PREBUILD']) dir = process.env[varName + '_PREBUILD']\n  } catch (err) {\n    packageNameError = err;\n  }\n  if (!prebuildsOnly) {\n    var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n    if (release) return release\n\n    var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n    if (debug) return debug\n  }\n\n  var prebuild = resolve(dir)\n  if (prebuild) return prebuild\n\n  var nearby = resolve(path.dirname(process.execPath))\n  if (nearby) return nearby\n\n  var platformPackage = (packageName[0] == '@' ? '' : '@' + packageName + '/') + packageName + '-' + platform + '-' + arch\n  var packageResolutionError\n  try {\n    var prebuildPackage = path.dirname(require('module').createRequire(url.pathToFileURL(path.join(dir, 'package.json'))).resolve(platformPackage))\n    return resolveFile(prebuildPackage)\n  } catch(error) {\n    packageResolutionError = error\n  }\n\n  var target = [\n    'platform=' + platform,\n    'arch=' + arch,\n    'runtime=' + runtime,\n    'abi=' + abi,\n    'uv=' + uv,\n    armv ? 'armv=' + armv : '',\n    'libc=' + libc,\n    'node=' + process.versions.node,\n    process.versions.electron ? 'electron=' + process.versions.electron : '',\n    typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n  ].filter(Boolean).join(' ')\n  let errMessage = 'No native build was found for ' + target + '\\n    attempted loading from: ' + dir + ' and package:' +\n    ' ' + platformPackage + '\\n';\n  if (packageNameError) {\n    errMessage += 'Error finding package.json: ' + packageNameError.message + '\\n';\n  }\n  if (packageResolutionError) {\n    errMessage += 'Error resolving package: ' + packageResolutionError.message + '\\n';\n  }\n  throw new Error(errMessage)\n\n  function resolve (dir) {\n    // Find matching \"prebuilds/<platform>-<arch>\" directory\n    var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n    var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n    if (!tuple) return\n    return resolveFile(path.join(dir, 'prebuilds', tuple.name))\n  }\n  function resolveFile (prebuilds) {\n    // Find most specific flavor first\n    var parsed = readdirSync(prebuilds).map(parseTags)\n    var candidates = parsed.filter(matchTags(runtime, abi))\n    var winner = candidates.sort(compareTags(runtime))[0]\n    if (winner) return path.join(prebuilds, winner.file)\n  }\n}\n\nfunction readdirSync (dir) {\n  try {\n    return fs.readdirSync(dir)\n  } catch (err) {\n    return []\n  }\n}\n\nfunction getFirst (dir, filter) {\n  var files = readdirSync(dir).filter(filter)\n  return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n  return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n  // Example: darwin-x64+arm64\n  var arr = name.split('-')\n  if (arr.length !== 2) return\n\n  var platform = arr[0]\n  var architectures = arr[1].split('+')\n\n  if (!platform) return\n  if (!architectures.length) return\n  if (!architectures.every(Boolean)) return\n\n  return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n  return function (tuple) {\n    if (tuple == null) return false\n    if (tuple.platform !== platform) return false\n    return tuple.architectures.includes(arch)\n  }\n}\n\nfunction compareTuples (a, b) {\n  // Prefer single-arch prebuilds over multi-arch\n  return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n  var arr = file.split('.')\n  var extension = arr.pop()\n  var tags = { file: file, specificity: 0 }\n\n  if (extension !== 'node') return\n\n  for (var i = 0; i < arr.length; i++) {\n    var tag = arr[i]\n\n    if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n      tags.runtime = tag\n    } else if (tag === 'napi') {\n      tags.napi = true\n    } else if (tag.slice(0, 3) === 'abi') {\n      tags.abi = tag.slice(3)\n    } else if (tag.slice(0, 2) === 'uv') {\n      tags.uv = tag.slice(2)\n    } else if (tag.slice(0, 4) === 'armv') {\n      tags.armv = tag.slice(4)\n    } else if (tag === 'glibc' || tag === 'musl') {\n      tags.libc = tag\n    } else {\n      continue\n    }\n\n    tags.specificity++\n  }\n\n  return tags\n}\n\nfunction matchTags (runtime, abi) {\n  return function (tags) {\n    if (tags == null) return false\n    if (tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n    if (tags.abi !== abi && !tags.napi) return false\n    if (tags.uv && tags.uv !== uv) return false\n    if (tags.armv && tags.armv !== armv) return false\n    if (tags.libc && tags.libc !== libc) return false\n\n    return true\n  }\n}\n\nfunction runtimeAgnostic (tags) {\n  return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n  // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n  return function (a, b) {\n    if (a.runtime !== b.runtime) {\n      return a.runtime === runtime ? -1 : 1\n    } else if (a.abi !== b.abi) {\n      return a.abi ? -1 : 1\n    } else if (a.specificity !== b.specificity) {\n      return a.specificity > b.specificity ? -1 : 1\n    } else {\n      return 0\n    }\n  }\n}\n\nfunction isNwjs () {\n  return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n  if (process.versions && process.versions.electron) return true\n  if (process.env.ELECTRON_RUN_AS_NODE) return true\n  return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isMusl (platform) {\n  if (platform !== 'linux') return false;\n  const { familySync, MUSL } = require('detect-libc');\n  return familySync() === MUSL;\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n  module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n  module.exports = require('./node-gyp-build.js')\n}\n","module.exports = require('node-gyp-build-optional-packages')(__dirname);","export { Packr, Encoder, addExtension, pack, encode, NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT, REUSE_BUFFER_MODE, RESET_BUFFER_MODE, RESERVE_START_SPACE } from './pack.js';\nexport { Unpackr, Decoder, C1, unpack, unpackMultiple, decode, FLOAT32_OPTIONS, clearSource, roundFloat32, isNativeAccelerationEnabled } from './unpack.js';\nexport { PackrStream, UnpackrStream, PackrStream as EncoderStream, UnpackrStream as DecoderStream } from './stream.js';\nexport { decodeIter, encodeIter } from './iterators.js';\nexport const useRecords = false;\nexport const mapsAsObjects = true;\nimport { setExtractor } from './unpack.js';\nimport { createRequire } from 'module';\n\nconst nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === 'true';\n\nif (!nativeAccelerationDisabled) {\n\tlet extractor;\n\ttry {\n\t\tif (typeof require == 'function')\n\t\t\textractor = require('msgpackr-extract');\n\t\telse\n\t\t\textractor = createRequire(import.meta.url)('msgpackr-extract');\n\t\tif (extractor)\n\t\t\tsetExtractor(extractor.extractStrings);\n\t} catch (error) {\n\t\t// native module is optional\n\t}\n}","/**\n * Serializes RPC protocol messages for transports.\n *\n * `RpcSerialization` is the boundary between `RpcMessage` envelopes and the\n * bytes or strings carried by a transport. This module provides built-in\n * serializers for JSON, newline-delimited JSON, JSON-RPC 2.0, and MessagePack,\n * including framed formats that can decode multiple messages from streaming\n * chunks.\n *\n * @since 4.0.0\n */\nimport * as Msgpackr from \"msgpackr\";\nimport * as Context from \"../../Context.js\";\nimport * as Data from \"../../Data.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport { hasProperty } from \"../../Predicate.js\";\n/**\n * Service that describes how RPC protocol messages are encoded and decoded,\n * including the content type and whether the serialization format provides\n * message framing.\n *\n * **When to use**\n *\n * Use to provide the serialization boundary shared by RPC clients and servers\n * for a chosen wire format.\n *\n * @category services\n * @since 4.0.0\n */\nexport class RpcSerialization extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcSerialization\") {}\n/**\n * Error raised when a streaming parser retains more data than its configured\n * buffer limit.\n *\n * @category errors\n * @since 4.0.0\n */\nexport class MaxBufferSizeExceeded extends /*#__PURE__*/Data.TaggedError(\"MaxBufferSizeExceeded\") {\n  get message() {\n    return `RPC serialization buffer exceeded the maximum size of ${this.maxBufferSize}`;\n  }\n}\nconst defaultMaxBufferSize = 16 * 1024 * 1024;\nconst isBufferSizeExceeded = (bufferSize, maxBufferSize) => maxBufferSize !== \"unbounded\" && bufferSize > maxBufferSize;\n/**\n * JSON RPC serialization for whole message payloads. It does not include\n * message framing, so it is intended for transports that frame responses\n * themselves.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const json = /*#__PURE__*/RpcSerialization.of({\n  contentType: \"application/json\",\n  includesFraming: false,\n  makeUnsafe: () => {\n    const decoder = new TextDecoder();\n    return {\n      decode: bytes => {\n        const decoded = JSON.parse(typeof bytes === \"string\" ? bytes : decoder.decode(bytes));\n        return Array.isArray(decoded) ? decoded : [decoded];\n      },\n      encode: response => JSON.stringify(response)\n    };\n  }\n});\n/**\n * Serializes RPC protocol messages as newline-delimited JSON, framing each message\n * with a trailing newline.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const makeNdjson = options => {\n  const maxBufferSize = options?.maxBufferSize ?? defaultMaxBufferSize;\n  return RpcSerialization.of({\n    contentType: \"application/ndjson\",\n    includesFraming: true,\n    makeUnsafe: () => {\n      const decoder = new TextDecoder();\n      let buffer = \"\";\n      const failMaxBufferSize = maxBufferSize => {\n        buffer = \"\";\n        throw new MaxBufferSizeExceeded({\n          maxBufferSize\n        });\n      };\n      return {\n        decode: bytes => {\n          buffer += typeof bytes === \"string\" ? bytes : decoder.decode(bytes);\n          let position = 0;\n          let nlIndex = buffer.indexOf(\"\\n\", position);\n          const items = [];\n          while (nlIndex !== -1) {\n            if (isBufferSizeExceeded(nlIndex - position, maxBufferSize)) {\n              failMaxBufferSize(maxBufferSize);\n            }\n            const item = JSON.parse(buffer.slice(position, nlIndex));\n            items.push(item);\n            position = nlIndex + 1;\n            nlIndex = buffer.indexOf(\"\\n\", position);\n          }\n          buffer = buffer.slice(position);\n          if (isBufferSizeExceeded(buffer.length, maxBufferSize)) {\n            failMaxBufferSize(maxBufferSize);\n          }\n          return items;\n        },\n        encode: response => {\n          if (Array.isArray(response)) {\n            if (response.length === 0) return undefined;\n            let data = \"\";\n            for (let i = 0; i < response.length; i++) {\n              data += JSON.stringify(response[i]) + \"\\n\";\n            }\n            return data;\n          }\n          return JSON.stringify(response) + \"\\n\";\n        }\n      };\n    }\n  });\n};\n/**\n * Default newline-delimited JSON RPC serialization.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const ndjson = /*#__PURE__*/makeNdjson();\n/**\n * Creates a JSON-RPC 2.0 serialization for RPC protocol messages without\n * additional message framing.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const jsonRpc = options => RpcSerialization.of({\n  contentType: options?.contentType ?? \"application/json\",\n  includesFraming: false,\n  makeUnsafe: () => {\n    const decoder = new TextDecoder();\n    const batches = new Map();\n    return {\n      decode: bytes => {\n        const decoded = JSON.parse(typeof bytes === \"string\" ? bytes : decoder.decode(bytes));\n        return decodeJsonRpcRaw(decoded, batches);\n      },\n      encode: response => {\n        const encoded = encodeJsonRpcResponse(response, batches);\n        return encoded && JSON.stringify(encoded);\n      }\n    };\n  }\n});\n/**\n * Creates a newline-delimited JSON-RPC 2.0 serialization for RPC protocol\n * messages.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const ndJsonRpc = options => RpcSerialization.of({\n  contentType: options?.contentType ?? \"application/json-rpc\",\n  includesFraming: true,\n  makeUnsafe: () => {\n    const parser = makeNdjson({\n      maxBufferSize: options?.maxBufferSize\n    }).makeUnsafe();\n    const batches = new Map();\n    return {\n      decode: bytes => {\n        const frames = parser.decode(bytes);\n        if (frames.length === 0) return [];\n        const messages = [];\n        for (let i = 0; i < frames.length; i++) {\n          const frame = frames[i];\n          messages.push(...decodeJsonRpcRaw(frame, batches));\n        }\n        return messages;\n      },\n      encode: response => {\n        const encoded = encodeJsonRpcResponse(response, batches);\n        return encoded && parser.encode(encoded);\n      }\n    };\n  }\n});\nfunction decodeJsonRpcRaw(decoded, batches) {\n  if (Array.isArray(decoded)) {\n    const batch = {\n      size: 0,\n      responses: new Map()\n    };\n    const messages = [];\n    for (let i = 0; i < decoded.length; i++) {\n      const message = decodeJsonRpcMessage(decoded[i]);\n      messages.push(message);\n      if (message._tag === \"Request\") {\n        batch.size++;\n        batches.set(message.id, batch);\n      }\n    }\n    return messages;\n  }\n  return [decodeJsonRpcMessage(decoded)];\n}\nfunction decodeJsonRpcMessage(decoded) {\n  if (Object.hasOwn(decoded, \"method\")) {\n    const request = decoded;\n    if (Predicate.isNullish(request.id) && request.method.startsWith(\"@effect/rpc/\")) {\n      const tag = request.method.slice(\"@effect/rpc/\".length);\n      const requestId = request.params?.requestId;\n      return requestId ? {\n        _tag: tag,\n        requestId\n      } : {\n        _tag: tag\n      };\n    }\n    return {\n      _tag: \"Request\",\n      id: request.id ?? \"\",\n      tag: request.method,\n      payload: request.params ?? null,\n      headers: request.headers ?? [],\n      ...(Predicate.hasProperty(request, \"id\") ? {} : {\n        isNotification: true\n      }),\n      ...(request.spanId ? {\n        traceId: request.traceId,\n        spanId: request.spanId,\n        sampled: request.sampled\n      } : {})\n    };\n  }\n  const response = decoded;\n  const hasError = Object.hasOwn(response, \"error\");\n  if (hasError && response.error && response.error._tag === \"Defect\") {\n    return {\n      _tag: \"Defect\",\n      defect: response.error.data\n    };\n  } else if (Object.hasOwn(response, \"chunk\") && response.chunk === true) {\n    return {\n      _tag: \"Chunk\",\n      requestId: response.id ?? \"\",\n      values: response.result\n    };\n  }\n  return {\n    _tag: \"Exit\",\n    requestId: response.id ?? \"\",\n    exit: hasError && response.error != null ? {\n      _tag: \"Failure\",\n      cause: response.error._tag === \"Cause\" ? response.error.data : [{\n        _tag: \"Die\",\n        defect: response.error\n      }]\n    } : {\n      _tag: \"Success\",\n      value: response.result\n    }\n  };\n}\nfunction encodeJsonRpcRaw(response, batches) {\n  if (!(\"requestId\" in response)) {\n    return encodeJsonRpcMessage(response);\n  }\n  const batch = batches.get(response.requestId);\n  if (batch) {\n    batches.delete(response.requestId);\n    batch.responses.set(response.requestId, response);\n    if (batch.size === batch.responses.size) {\n      return Array.from(batch.responses.values(), encodeJsonRpcMessage);\n    }\n    return undefined;\n  }\n  return encodeJsonRpcMessage(response);\n}\nfunction encodeJsonRpcResponse(response, batches) {\n  if (Array.isArray(response) === false) {\n    return encodeJsonRpcRaw(response, batches);\n  }\n  if (response.length === 0) {\n    return undefined;\n  }\n  const encoded = [];\n  for (let i = 0; i < response.length; i++) {\n    const current = encodeJsonRpcRaw(response[i], batches);\n    if (current !== undefined) {\n      encoded.push(current);\n    }\n  }\n  if (encoded.length === 0) {\n    return undefined;\n  }\n  if (encoded.length === 1) {\n    return encoded[0];\n  }\n  const messages = [];\n  for (let i = 0; i < encoded.length; i++) {\n    const current = encoded[i];\n    if (Array.isArray(current)) {\n      messages.push(...current);\n    } else {\n      messages.push(current);\n    }\n  }\n  return messages;\n}\nfunction encodeJsonRpcMessage(response) {\n  switch (response._tag) {\n    case \"Request\":\n      return {\n        jsonrpc: \"2.0\",\n        method: response.tag,\n        params: response.payload,\n        id: response.id,\n        headers: response.headers,\n        traceId: response.traceId,\n        spanId: response.spanId,\n        sampled: response.sampled\n      };\n    case \"Ping\":\n    case \"Pong\":\n    case \"Interrupt\":\n    case \"Ack\":\n    case \"Eof\":\n      return {\n        jsonrpc: \"2.0\",\n        method: `@effect/rpc/${response._tag}`,\n        params: \"requestId\" in response ? {\n          requestId: response.requestId\n        } : undefined\n      };\n    case \"Chunk\":\n      return {\n        jsonrpc: \"2.0\",\n        chunk: true,\n        id: response.requestId,\n        result: response.values\n      };\n    case \"Exit\":\n      {\n        if (response.exit._tag === \"Success\") {\n          return {\n            jsonrpc: \"2.0\",\n            id: response.requestId ?? undefined,\n            result: response.exit.value\n          };\n        }\n        const failure = response.exit.cause.find(failure => failure._tag === \"Fail\");\n        const error = failure?._tag === \"Fail\" ? failure.error : undefined;\n        return {\n          jsonrpc: \"2.0\",\n          id: response.requestId ?? undefined,\n          error: response.exit._tag === \"Failure\" ? {\n            _tag: \"Cause\",\n            code: error && Predicate.hasProperty(error, \"code\") ? Number(error.code) : 0,\n            message: error && hasProperty(error, \"message\") ? error.message : JSON.stringify(response.exit.cause),\n            data: response.exit.cause\n          } : undefined\n        };\n      }\n    case \"Defect\":\n      return {\n        jsonrpc: \"2.0\",\n        id: jsonRpcInternalError,\n        error: {\n          _tag: \"Defect\",\n          code: 1,\n          message: \"A defect occurred\",\n          data: response.defect\n        }\n      };\n    case \"ClientProtocolError\":\n      return {};\n  }\n}\nconst jsonRpcInternalError = -32603;\n/**\n * Create a MessagePack serialization with custom msgpackr options.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const makeMsgPack = options => {\n  const {\n    maxBufferSize = defaultMaxBufferSize,\n    ...msgpackOptions\n  } = options ?? {};\n  return RpcSerialization.of({\n    contentType: \"application/msgpack\",\n    includesFraming: true,\n    makeUnsafe: () => {\n      const unpackr = new Msgpackr.Unpackr(msgpackOptions);\n      const packr = new Msgpackr.Packr(msgpackOptions);\n      const encoder = new TextEncoder();\n      let incomplete = undefined;\n      const failMaxBufferSize = maxBufferSize => {\n        incomplete = undefined;\n        throw new MaxBufferSizeExceeded({\n          maxBufferSize\n        });\n      };\n      return {\n        decode(bytes) {\n          let buf = typeof bytes === \"string\" ? encoder.encode(bytes) : bytes;\n          if (incomplete !== undefined) {\n            if (isBufferSizeExceeded(incomplete.length + buf.length, maxBufferSize)) {\n              failMaxBufferSize(maxBufferSize);\n            }\n            const prev = buf;\n            bytes = new Uint8Array(incomplete.length + buf.length);\n            bytes.set(incomplete);\n            bytes.set(prev, incomplete.length);\n            buf = bytes;\n            incomplete = undefined;\n          }\n          try {\n            return unpackr.unpackMultiple(buf);\n          } catch (error_) {\n            const error = error_;\n            if (error.incomplete) {\n              incomplete = buf.subarray(error.lastPosition);\n              if (isBufferSizeExceeded(incomplete.length, maxBufferSize)) {\n                failMaxBufferSize(maxBufferSize);\n              }\n              return error.values ?? [];\n            }\n            throw error_;\n          }\n        },\n        encode: response => packr.pack(response)\n      };\n    }\n  });\n};\n/**\n * Default MessagePack RPC serialization using record support and built-in\n * message framing.\n *\n * @category serialization\n * @since 4.0.0\n */\nexport const msgPack = /*#__PURE__*/makeMsgPack({\n  useRecords: true\n});\n/**\n * RPC serialization layer that uses JSON for serialization.\n *\n * **When to use**\n *\n * Use when you have a transport protocol that already provides message framing.\n *\n * @see {@link layerNdjson} for transports that need newline-delimited framing\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/Layer.succeed(RpcSerialization)(json);\n/**\n * RPC serialization layer that uses NDJSON for serialization.\n *\n * **When to use**\n *\n * Use when you have a transport protocol that does not provide message framing.\n *\n * @see {@link layerJson} for transports that already provide message framing\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerNdjson = /*#__PURE__*/Layer.succeed(RpcSerialization)(ndjson);\n/**\n * RPC serialization layer that uses NDJSON with custom streaming options.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerNdjsonWith = options => Layer.succeed(RpcSerialization)(makeNdjson(options));\n/**\n * RPC serialization layer that uses JSON-RPC for serialization.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerJsonRpc = options => Layer.succeed(RpcSerialization)(jsonRpc(options));\n/**\n * RPC serialization layer that uses newline-delimited JSON-RPC for\n * serialization.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerNdJsonRpc = options => Layer.succeed(RpcSerialization)(ndJsonRpc(options));\n/**\n * RPC serialization layer that uses MessagePack for serialization.\n *\n * **Details**\n *\n * MessagePack has a more compact binary format compared to JSON and NDJSON. It\n * also has better support for binary data.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerMsgPack = /*#__PURE__*/Layer.succeed(RpcSerialization)(msgPack);\n/**\n * RPC serialization layer that uses MessagePack with custom options.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerMsgPackWith = options => Layer.succeed(RpcSerialization)(makeMsgPack(options));\n//# sourceMappingURL=RpcSerialization.js.map","import * as Effect from \"../../Effect.js\";\nimport * as Semaphore from \"../../Semaphore.js\";\n/**\n * Builds a service with a `run` method that buffers writes until `run` installs\n * a writer, replays buffered writes with their original contexts, and restores\n * the previous writer when the run ends.\n *\n * @category services\n * @since 4.0.0\n */\nexport const withRun = () => f => Effect.suspend(() => {\n  const semaphore = Semaphore.makeUnsafe(1);\n  let buffer = [];\n  let write = (...args) => Effect.contextWith(context => {\n    buffer.push([args, context]);\n    return Effect.void;\n  });\n  return Effect.map(f((...args) => write(...args)), a => ({\n    ...a,\n    run(f) {\n      return semaphore.withPermits(1)(Effect.gen(function* () {\n        const prev = write;\n        write = f;\n        for (const [args, context] of buffer) {\n          yield* Effect.provideContext(Effect.suspend(() => f(...args)), context);\n        }\n        buffer = [];\n        return yield* Effect.onExit(Effect.never, () => {\n          write = prev;\n          return Effect.void;\n        });\n      }));\n    }\n  }));\n});\n/**\n * Builds an RPC client protocol service that tracks active client IDs and\n * buffers server responses per client until that client's `run` handler is\n * installed.\n *\n * @category services\n * @since 4.0.0\n */\nexport const withRunClient = f => Effect.suspend(() => {\n  const clientIds = new Set();\n  const clientBuffers = new Map();\n  const clientWrites = new Map();\n  let write = (clientId, data) => Effect.contextWith(context => {\n    let buffer = clientBuffers.get(clientId);\n    if (!buffer) {\n      buffer = [];\n      clientBuffers.set(clientId, buffer);\n    }\n    buffer.push([data, context]);\n    return Effect.void;\n  });\n  return Effect.map(f((clientId, data) => {\n    const clientWrite = clientWrites.get(clientId);\n    if (clientWrite) {\n      return clientWrite(data);\n    }\n    return write(clientId, data);\n  }, clientIds), a => ({\n    ...a,\n    run(clientId, f) {\n      return Effect.gen(function* () {\n        clientIds.add(clientId);\n        clientWrites.set(clientId, f);\n        const buffer = clientBuffers.get(clientId);\n        if (buffer) {\n          clientBuffers.delete(clientId);\n          for (const [args, context] of buffer) {\n            yield* Effect.provideContext(Effect.suspend(() => f(args)), context);\n          }\n        }\n        return yield* Effect.onExit(Effect.never, () => {\n          clientIds.delete(clientId);\n          clientWrites.delete(clientId);\n          return Effect.void;\n        });\n      });\n    }\n  }));\n});\n//# sourceMappingURL=Utils.js.map","import * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { constVoid, dual, flow, identity } from \"../../Function.js\";\nimport * as InternalRecord from \"../../internal/record.js\";\nimport * as Latch from \"../../Latch.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Pool from \"../../Pool.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Result from \"../../Result.js\";\nimport * as Schedule from \"../../Schedule.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpBody from \"../http/HttpBody.js\";\nimport * as HttpClient from \"../http/HttpClient.js\";\nimport { HttpClientErrorSchema } from \"../http/HttpClientError.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as Socket from \"../socket/Socket.js\";\nimport * as Transferable from \"../workers/Transferable.js\";\nimport * as Worker from \"../workers/Worker.js\";\nimport * as Rpc from \"./Rpc.js\";\nimport { RpcClientDefect, RpcClientError } from \"./RpcClientError.js\";\nimport { constPing, isTerminalResponse, RequestId } from \"./RpcMessage.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nimport * as RpcSerialization from \"./RpcSerialization.js\";\nimport * as RpcWorker from \"./RpcWorker.js\";\nimport { withRunClient } from \"./Utils.js\";\nlet requestIdCounter = 0;\n/**\n * Creates an RPC client for an already-decoded message channel, returning the\n * client API together with a `write` function for delivering server messages\n * back to the client.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n  const spanPrefix = options?.spanPrefix ?? \"RpcClient\";\n  const supportsAck = options?.supportsAck ?? true;\n  const disableTracing = options?.disableTracing ?? false;\n  const generateRequestId = options?.generateRequestId ?? (() => requestIdCounter++);\n  const services = yield* Effect.context();\n  const scope = Context.get(services, Scope.Scope);\n  const entries = new Map();\n  const hooks = yield* Effect.serviceOption(RequestHooks);\n  let isShutdown = false;\n  yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {\n    isShutdown = true;\n    return clearEntries(Exit.interrupt(parent.id));\n  }));\n  const clearEntries = Effect.fnUntraced(function* (exit) {\n    for (const [id, entry] of entries) {\n      entries.delete(id);\n      if (entry._tag === \"Queue\") {\n        yield* exit._tag === \"Success\" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, exit.cause);\n      } else {\n        entry.resume(exit);\n      }\n    }\n  });\n  const onRequest = rpc => {\n    const isStream = RpcSchema.isStreamSchema(rpc.successSchema);\n    const middleware = getRpcClientMiddleware(rpc);\n    return (payload, opts) => {\n      const headers = opts?.headers ? Headers.fromInput(opts.headers) : Headers.empty;\n      const context = opts?.context ?? Context.empty();\n      if (!isStream) {\n        const onRequest = span => onEffectRequest(rpc, middleware, span, rpc.payloadSchema.make(payload), headers, context, opts?.discard ?? false);\n        return disableTracing ? onRequest(undefined) : Effect.useSpan(`${spanPrefix}.${rpc._tag}`, {\n          attributes: options.spanAttributes\n        }, onRequest);\n      }\n      const queue = onStreamRequest(rpc, middleware, rpc.payloadSchema.make(payload), headers, opts?.streamBufferSize ?? 16, context);\n      if (opts?.asQueue) return queue;\n      return Stream.unwrap(Effect.map(queue, Stream.fromQueue));\n    };\n  };\n  const onEffectRequest = (rpc, middleware, span, payload, headers, context, discard) => Effect.withFiber(parentFiber => {\n    if (isShutdown) {\n      return Effect.interrupt;\n    }\n    const id = generateRequestId();\n    const onStart = Option.isSome(hooks) && hooks.value.onRequestStart ? hooks.value.onRequestStart({\n      id,\n      tag: rpc._tag,\n      stream: false\n    }) : Effect.void;\n    const send = middleware(message => options.onFromClient({\n      message,\n      context,\n      discard\n    }), {\n      _tag: \"Request\",\n      id,\n      tag: rpc._tag,\n      payload,\n      ...(span ? {\n        traceId: span.traceId,\n        spanId: span.spanId,\n        sampled: span.sampled\n      } : {}),\n      headers: Headers.merge(parentFiber.getRef(CurrentHeaders), headers)\n    });\n    if (discard) {\n      return onStart.pipe(Effect.andThen(send));\n    }\n    let fiber;\n    return Effect.onInterrupt(Effect.callback(resume => {\n      const entry = {\n        _tag: \"Effect\",\n        rpc,\n        context,\n        resume(exit) {\n          resume(exit);\n          if (fiber && !fiber.pollUnsafe()) {\n            parentFiber.currentDispatcher.scheduleTask(() => {\n              fiber.interruptUnsafe(parentFiber.id);\n            }, 0);\n          }\n        }\n      };\n      entries.set(id, entry);\n      fiber = onStart.pipe(Effect.andThen(send), span ? Effect.withParentSpan(span, {\n        captureStackTrace: false\n      }) : identity, Effect.runForkWith(parentFiber.context));\n      fiber.addObserver(exit => {\n        if (exit._tag === \"Failure\") {\n          return resume(exit);\n        }\n      });\n    }), interruptors => {\n      const entry = entries.get(id);\n      entries.delete(id);\n      return Effect.andThen(Fiber.interrupt(fiber), sendInterrupt(id, Array.from(interruptors), context, entry?.rpc._tag));\n    });\n  });\n  const onStreamRequest = Effect.fnUntraced(function* (rpc, middleware, payload, headers, streamBufferSize, context) {\n    if (isShutdown) {\n      return yield* Effect.interrupt;\n    }\n    const span = disableTracing ? undefined : yield* Effect.makeSpanScoped(`${spanPrefix}.${rpc._tag}`, {\n      attributes: options.spanAttributes\n    });\n    const fiber = Fiber.getCurrent();\n    const id = generateRequestId();\n    const onStart = Option.isSome(hooks) && hooks.value.onRequestStart ? hooks.value.onRequestStart({\n      id,\n      tag: rpc._tag,\n      stream: true\n    }) : Effect.void;\n    const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n    yield* Scope.addFinalizerExit(scope, exit => {\n      const entry = entries.get(id);\n      if (!entry) return Effect.void;\n      entries.delete(id);\n      return sendInterrupt(id, Exit.isFailure(exit) ? Array.from(Cause.interruptors(exit.cause)) : [], context, entry.rpc._tag);\n    });\n    const queue = yield* Queue.bounded(streamBufferSize);\n    entries.set(id, {\n      _tag: \"Queue\",\n      rpc,\n      queue,\n      scope,\n      context,\n      chunkCount: 0\n    });\n    yield* onStart.pipe(Effect.andThen(middleware(message => options.onFromClient({\n      message,\n      context,\n      discard: false\n    }), {\n      _tag: \"Request\",\n      id,\n      tag: rpc._tag,\n      payload,\n      ...(span ? {\n        traceId: span.traceId,\n        spanId: span.spanId,\n        sampled: span.sampled\n      } : {}),\n      headers: Headers.merge(fiber.getRef(CurrentHeaders), headers)\n    }))).pipe(span ? Effect.withParentSpan(span, {\n      captureStackTrace: false\n    }) : identity, Effect.catchCause(error => Queue.failCause(queue, error)), Effect.interruptible, Effect.forkIn(scope, {\n      startImmediately: true\n    }));\n    return queue;\n  });\n  const getRpcClientMiddleware = rpc => {\n    const middlewares = [];\n    for (const tag of rpc.middlewares.values()) {\n      const middleware = services.mapUnsafe.get(`${tag.key}/Client`);\n      if (!middleware) continue;\n      middlewares.push(middleware);\n    }\n    if (middlewares.length === 0) {\n      return (send, request) => send(request);\n    }\n    return function loop(send, request, index = middlewares.length - 1) {\n      if (index === -1) {\n        return send(request);\n      }\n      return middlewares[index]({\n        rpc,\n        request,\n        next(request) {\n          return loop(send, request, index - 1);\n        }\n      });\n    };\n  };\n  const sendInterrupt = (requestId, interruptors, context, tag) => (Option.isSome(hooks) && hooks.value.onRequestInterrupt ? hooks.value.onRequestInterrupt({\n    id: requestId,\n    tag\n  }) : Effect.void).pipe(Effect.andThen(Effect.callback(resume => {\n    const parentFiber = Fiber.getCurrent();\n    const fiber = options.onFromClient({\n      message: {\n        _tag: \"Interrupt\",\n        requestId,\n        interruptors\n      },\n      context,\n      discard: false\n    }).pipe(Effect.timeout(1000), Effect.runForkWith(parentFiber.context));\n    fiber.addObserver(() => {\n      resume(Effect.void);\n    });\n  })));\n  const write = message => {\n    switch (message._tag) {\n      case \"Chunk\":\n        {\n          const requestId = message.requestId;\n          const entry = entries.get(requestId);\n          if (!entry || entry._tag !== \"Queue\") return Effect.void;\n          const chunkCount = entry.chunkCount += message.values.length;\n          const onChunk = Option.isSome(hooks) && hooks.value.onRequestChunk ? hooks.value.onRequestChunk({\n            id: requestId,\n            tag: entry.rpc._tag,\n            chunkCount\n          }) : Effect.void;\n          return Queue.offerAll(entry.queue, message.values).pipe(Effect.andThen(onChunk), supportsAck ? Effect.flatMap(() => options.onFromClient({\n            message: {\n              _tag: \"Ack\",\n              requestId: message.requestId\n            },\n            context: entry.context,\n            discard: false\n          })) : identity, Effect.catchCause(cause => Queue.failCause(entry.queue, cause)));\n        }\n      case \"Exit\":\n        {\n          const requestId = message.requestId;\n          const entry = entries.get(requestId);\n          if (!entry) return Effect.void;\n          entries.delete(requestId);\n          const onExit = Option.isSome(hooks) && hooks.value.onRequestExit ? hooks.value.onRequestExit({\n            id: requestId,\n            tag: entry.rpc._tag,\n            stream: entry._tag === \"Queue\",\n            exit: message.exit\n          }) : Effect.void;\n          if (entry._tag === \"Effect\") {\n            return onExit.pipe(Effect.andThen(Effect.sync(() => {\n              entry.resume(message.exit);\n            })));\n          }\n          return onExit.pipe(Effect.andThen(message.exit._tag === \"Success\" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, message.exit.cause)));\n        }\n      case \"Defect\":\n        {\n          return clearEntries(Exit.die(message.defect));\n        }\n      case \"ClientEnd\":\n        {\n          return Effect.void;\n        }\n    }\n  };\n  let client;\n  if (options.flatten) {\n    const fns = new Map();\n    client = function client(tag, payload, options) {\n      let fn = fns.get(tag);\n      if (!fn) {\n        fn = onRequest(group.requests.get(tag));\n        fns.set(tag, fn);\n      }\n      return fn(payload, options);\n    };\n  } else {\n    client = {};\n    group.requests.forEach(rpc => {\n      InternalRecord.assignProperty(client, rpc._tag, onRequest(rpc));\n    });\n  }\n  return {\n    client,\n    write\n  };\n});\nlet clientIdCounter = 0;\n/**\n * Creates a schema-aware RPC client for a group using the current client\n * `Protocol`, encoding requests and decoding server responses.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n  const clientId = clientIdCounter++;\n  const {\n    run,\n    send,\n    supportsAck,\n    supportsTransferables\n  } = yield* Protocol;\n  const entries = new Map();\n  const {\n    client,\n    write\n  } = yield* makeNoSerialization(group, {\n    ...options,\n    supportsAck,\n    onFromClient({\n      message\n    }) {\n      switch (message._tag) {\n        case \"Request\":\n          {\n            const rpc = group.requests.get(message.tag);\n            const collector = supportsTransferables ? Transferable.makeCollectorUnsafe() : undefined;\n            const fiber = Fiber.getCurrent();\n            const entry = {\n              rpc,\n              context: collector ? Context.add(fiber.context, Transferable.Collector, collector) : fiber.context,\n              schemas: rpcSchemas(rpc)\n            };\n            entries.set(message.id, entry);\n            return entry.schemas.encodePayload(message.payload).pipe(Effect.provideContext(entry.context), Effect.orDie, Effect.flatMap(payload => send(clientId, {\n              ...message,\n              id: message.id,\n              payload,\n              headers: Object.entries(message.headers)\n            }, collector && collector.readUnsafe())));\n          }\n        case \"Ack\":\n          {\n            const entry = entries.get(message.requestId);\n            if (!entry) return Effect.void;\n            return send(clientId, {\n              _tag: \"Ack\",\n              requestId: message.requestId\n            });\n          }\n        case \"Interrupt\":\n          {\n            const entry = entries.get(message.requestId);\n            if (!entry) return Effect.void;\n            entries.delete(message.requestId);\n            return send(clientId, {\n              _tag: \"Interrupt\",\n              requestId: message.requestId\n            });\n          }\n        case \"Eof\":\n          {\n            return Effect.void;\n          }\n      }\n    }\n  });\n  yield* run(clientId, message => {\n    switch (message._tag) {\n      case \"Chunk\":\n        {\n          const requestId = RequestId(message.requestId);\n          const entry = entries.get(requestId);\n          if (!entry || Option.isNone(entry.schemas.decodeChunk)) return Effect.void;\n          return entry.schemas.decodeChunk.value(message.values).pipe(Effect.provideContext(entry.context), Effect.orDie, Effect.flatMap(chunk => write({\n            _tag: \"Chunk\",\n            clientId: 0,\n            requestId: RequestId(message.requestId),\n            values: chunk\n          })), Effect.onError(cause => write({\n            _tag: \"Exit\",\n            clientId: 0,\n            requestId: RequestId(message.requestId),\n            exit: Exit.failCause(cause)\n          })));\n        }\n      case \"Exit\":\n        {\n          const requestId = RequestId(message.requestId);\n          const entry = entries.get(requestId);\n          if (!entry) return Effect.void;\n          entries.delete(requestId);\n          return entry.schemas.decodeExit(message.exit).pipe(Effect.provideContext(entry.context), Effect.orDie, Effect.matchCauseEffect({\n            onSuccess: exit => write({\n              _tag: \"Exit\",\n              clientId: 0,\n              requestId,\n              exit\n            }),\n            onFailure: cause => write({\n              _tag: \"Exit\",\n              clientId: 0,\n              requestId,\n              exit: Exit.failCause(cause)\n            })\n          }));\n        }\n      case \"Defect\":\n        {\n          return write({\n            _tag: \"Defect\",\n            clientId: 0,\n            defect: decodeDefect(message.defect)\n          });\n        }\n      case \"ClientProtocolError\":\n        {\n          const exit = Exit.fail(message.error);\n          return Effect.forEach(entries.keys(), requestId => write({\n            _tag: \"Exit\",\n            clientId: 0,\n            requestId,\n            exit: exit\n          }));\n        }\n      default:\n        {\n          return Effect.void;\n        }\n    }\n  }).pipe(Effect.catchCause(Effect.logError), Effect.interruptible, Effect.forkScoped);\n  return client;\n});\nconst rpcSchemasCache = /*#__PURE__*/new WeakMap();\nconst rpcSchemas = rpc => {\n  let entry = rpcSchemasCache.get(rpc);\n  if (entry !== undefined) {\n    return entry;\n  }\n  const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n  entry = {\n    decodeChunk: Option.map(streamSchemas, streamSchemas => Schema.decodeUnknownEffect(Schema.toCodecJson(Schema.NonEmptyArray(streamSchemas.success)))),\n    encodePayload: Schema.encodeEffect(Schema.toCodecJson(rpc.payloadSchema)),\n    decodeExit: Schema.decodeUnknownEffect(Schema.toCodecJson(Rpc.exitSchema(rpc)))\n  };\n  rpcSchemasCache.set(rpc, entry);\n  return entry;\n};\n/**\n * Fiber reference containing headers that are merged into outgoing RPC\n * client requests.\n *\n * **When to use**\n *\n * Use to set request headers that should be automatically merged into outgoing\n * RPC client messages.\n *\n * @category services\n * @since 4.0.0\n */\nexport const CurrentHeaders = /*#__PURE__*/Context.Reference(\"effect/rpc/RpcClient/CurrentHeaders\", {\n  defaultValue: () => Headers.empty\n});\n/**\n * Runs an effect with additional RPC client headers, merging them with the\n * current `CurrentHeaders` value for outgoing requests.\n *\n * @category headers\n * @since 4.0.0\n */\nexport const withHeaders = /*#__PURE__*/dual(2, (effect, headers) => Effect.updateService(effect, CurrentHeaders, Headers.merge(Headers.fromInput(headers))));\n/**\n * Defines the service interface for an RPC client transport, responsible for running the\n * receive loop and sending encoded client messages.\n *\n * **When to use**\n *\n * Use to provide the transport boundary for RPC clients over HTTP, WebSocket,\n * workers, sockets, or custom protocols.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Protocol extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcClient/Protocol\") {\n  /**\n   * Creates a client protocol service from the supplied RPC request runner.\n   *\n   * @since 4.0.0\n   */\n  static make = withRunClient;\n}\n/**\n * Creates a client `Protocol` that sends each RPC request through the supplied\n * `HttpClient` and decodes responses with the current `RpcSerialization`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolHttp = client => Protocol.make(Effect.fnUntraced(function* (writeResponse) {\n  const serialization = yield* RpcSerialization.RpcSerialization;\n  const isFramed = serialization.includesFraming;\n  const httpClientError = cause => new RpcClientError({\n    reason: HttpClientErrorSchema.fromHttpClientError(cause)\n  });\n  const protocolDefect = (message, cause) => new RpcClientError({\n    reason: new RpcClientDefect({\n      message,\n      cause\n    })\n  });\n  const emptyResponseError = request => protocolDefect(\"Received empty HTTP response from RPC server\", request);\n  const incompleteResponseError = request => protocolDefect(\"HTTP response ended before RPC request completed\", request);\n  const send = Effect.fnUntraced(function* (clientId, request) {\n    if (request._tag !== \"Request\") {\n      return;\n    }\n    const parser = serialization.makeUnsafe();\n    const encoded = parser.encode(request);\n    const body = typeof encoded === \"string\" ? HttpBody.text(encoded, serialization.contentType) : HttpBody.uint8Array(encoded, serialization.contentType);\n    const response = yield* client.post(\"\", {\n      body\n    }).pipe(Effect.mapError(httpClientError));\n    if (!isFramed) {\n      const text = yield* response.text.pipe(Effect.mapError(httpClientError));\n      const responses = yield* Effect.try({\n        try: () => parser.decode(text),\n        catch: cause => protocolDefect(\"Error decoding HTTP response\", cause)\n      });\n      if (!Array.isArray(responses)) {\n        return yield* protocolDefect(\"Expected an array of responses\", responses);\n      }\n      if (responses.length === 0) {\n        return yield* emptyResponseError(request);\n      }\n      let completed = false;\n      let i = 0;\n      yield* Effect.whileLoop({\n        while: () => i < responses.length,\n        body: () => {\n          const response = responses[i++];\n          if (isTerminalResponse(response)) {\n            completed = true;\n          }\n          return writeResponse(clientId, response);\n        },\n        step: constVoid\n      });\n      if (!completed) {\n        return yield* incompleteResponseError(request);\n      }\n      return;\n    }\n    let hasResponse = false;\n    let completed = false;\n    yield* Stream.runForEachArray(response.stream, chunk => Effect.try({\n      try: () => chunk.flatMap(parser.decode),\n      catch: cause => protocolDefect(\"Error decoding HTTP response\", cause)\n    }).pipe(Effect.flatMap(responses => {\n      if (responses.length === 0) return Effect.void;\n      hasResponse = true;\n      let i = 0;\n      return Effect.whileLoop({\n        while: () => i < responses.length,\n        body: () => {\n          const response = responses[i++];\n          if (isTerminalResponse(response)) {\n            completed = true;\n          }\n          return writeResponse(clientId, response);\n        },\n        step: constVoid\n      });\n    }))).pipe(Effect.mapError(cause => cause instanceof RpcClientError ? cause : httpClientError(cause)));\n    if (!hasResponse) {\n      return yield* emptyResponseError(request);\n    } else if (!completed) {\n      return yield* incompleteResponseError(request);\n    }\n  });\n  return {\n    send,\n    supportsAck: false,\n    supportsTransferables: false\n  };\n}));\n/**\n * Provides a client `Protocol` backed by `HttpClient`, targeting the configured\n * URL and optionally transforming the client before use.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolHttp = options => Layer.effect(Protocol)(Effect.flatMap(HttpClient.HttpClient, client => {\n  client = HttpClient.mapRequest(client, HttpClientRequest.prependUrl(options.url));\n  return makeProtocolHttp(options.transformClient ? options.transformClient(client) : client);\n}));\n/**\n * Creates a client `Protocol` over the current `Socket`, using the current\n * `RpcSerialization`, connection hooks, ping timeouts, and the configured retry\n * policy.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(function* (writeResponse, clientIds) {\n  const socket = yield* Socket.Socket;\n  const serialization = yield* RpcSerialization.RpcSerialization;\n  const hooks = yield* Effect.serviceOption(ConnectionHooks);\n  const requestClientMap = new Map();\n  const write = yield* socket.writer;\n  let parser = serialization.makeUnsafe();\n  const pinger = yield* makePinger(write(parser.encode(constPing)), Option.isSome(hooks) ? hooks.value : undefined);\n  let currentError;\n  const onOpen = Effect.suspend(() => {\n    currentError = undefined;\n    return Option.isSome(hooks) ? hooks.value.onConnect : Effect.void;\n  });\n  const broadcast = response => Effect.forEach(clientIds, clientId => writeResponse(clientId, response));\n  yield* Effect.suspend(() => {\n    parser = serialization.makeUnsafe();\n    pinger.reset();\n    return socket.runRaw(message => {\n      try {\n        const responses = parser.decode(message);\n        if (responses.length === 0) return;\n        let i = 0;\n        return Effect.whileLoop({\n          while: () => i < responses.length,\n          body: () => {\n            const response = responses[i++];\n            if (response._tag === \"Pong\") {\n              return pinger.onPong;\n            }\n            if (Object.hasOwn(response, \"requestId\")) {\n              const requestId = response.requestId;\n              const clientId = requestClientMap.get(requestId);\n              if (clientId !== undefined) {\n                if (response._tag === \"Exit\") {\n                  requestClientMap.delete(requestId);\n                }\n                return writeResponse(clientId, response);\n              }\n            }\n            return broadcast(response);\n          },\n          step: constVoid\n        });\n      } catch (defect) {\n        return broadcast({\n          _tag: \"ClientProtocolError\",\n          error: new RpcClientError({\n            reason: new RpcClientDefect({\n              message: \"Error decoding message\",\n              cause: defect\n            })\n          })\n        });\n      }\n    }, {\n      onOpen\n    }).pipe(Effect.raceFirst(Effect.flatMap(pinger.timeout, () => (Option.isSome(hooks) && hooks.value.onPingTimeout ? hooks.value.onPingTimeout : Effect.void).pipe(Effect.andThen(Effect.fail(new Socket.SocketError({\n      reason: new Socket.SocketOpenError({\n        kind: \"Timeout\",\n        cause: new Error(\"ping timeout\")\n      })\n    })))))));\n  }).pipe(Effect.flatMap(() => Effect.fail(new Socket.SocketError({\n    reason: new Socket.SocketCloseError({\n      code: 1000\n    })\n  }))), Option.isSome(hooks) ? Effect.ensuring(hooks.value.onDisconnect) : identity, Effect.tapCause(cause => {\n    const error = Cause.findError(cause);\n    const hasError = Result.isSuccess(error);\n    if (options?.retryTransientErrors && hasError && error.success.reason._tag === \"SocketOpenError\") {\n      return Effect.void;\n    }\n    currentError = new RpcClientError({\n      reason: hasError ? error.success.reason : new RpcClientDefect({\n        message: \"Unknown socket error\",\n        cause: Cause.squash(cause)\n      })\n    });\n    return broadcast({\n      _tag: \"ClientProtocolError\",\n      error: currentError\n    });\n  }), Effect.retry(options?.retryPolicy ?? defaultRetryPolicy), Effect.annotateLogs({\n    module: \"RpcClient\",\n    method: \"makeProtocolSocket\"\n  }), Effect.forkScoped);\n  return {\n    send(clientId, request) {\n      if (currentError) {\n        return Effect.fail(currentError);\n      }\n      if (request._tag === \"Request\") {\n        requestClientMap.set(request.id, clientId);\n      }\n      const encoded = parser.encode(request);\n      if (encoded === undefined) return Effect.void;\n      return Effect.orDie(write(encoded));\n    },\n    supportsAck: true,\n    supportsTransferables: false\n  };\n}));\nconst defaultRetryPolicy = /*#__PURE__*/Schedule.min([/*#__PURE__*/Schedule.exponential(500, 1.5), /*#__PURE__*/Schedule.spaced(5000)]);\nconst makePinger = /*#__PURE__*/Effect.fnUntraced(function* (writePing, hooks) {\n  let recievedPong = true;\n  const latch = Latch.makeUnsafe();\n  const reset = () => {\n    recievedPong = true;\n    latch.closeUnsafe();\n  };\n  const onPong = Effect.sync(() => {\n    recievedPong = true;\n  }).pipe(Effect.andThen(hooks?.onPong ?? Effect.void));\n  yield* Effect.suspend(() => {\n    if (!recievedPong) return latch.open;\n    recievedPong = false;\n    return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));\n  }).pipe(Effect.delay(\"5 seconds\"), Effect.ignore, Effect.forever, Effect.interruptible, Effect.forkScoped);\n  return {\n    timeout: latch.await,\n    reset,\n    onPong\n  };\n});\n/**\n * Provides a client `Protocol` backed by the current `Socket` and\n * `RpcSerialization` services.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolSocket = options => Layer.effect(Protocol)(makeProtocolSocket(options));\n/**\n * Creates a client `Protocol` backed by a pool of workers, routing RPC requests\n * to workers and supporting transferable values when the platform does.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(function* (writeResponse, clientIds) {\n  const worker = yield* Worker.WorkerPlatform;\n  const scope = yield* Effect.scope;\n  let workerId = 0;\n  const initialMessage = yield* Effect.serviceOption(RpcWorker.InitialMessage);\n  const hooks = yield* Effect.serviceOption(ConnectionHooks);\n  const entries = new Map();\n  const broadcast = response => Effect.forEach(clientIds, clientId => writeResponse(clientId, response));\n  const acquire = Effect.gen(function* () {\n    const id = workerId++;\n    const backing = yield* worker.spawn(id);\n    yield* backing.run(response => {\n      if (response._tag === \"Exit\") {\n        const entry = entries.get(response.requestId);\n        if (entry) {\n          entries.delete(response.requestId);\n          entry.latch.openUnsafe();\n          return writeResponse(entry.clientId, response);\n        }\n      } else if (response._tag === \"Defect\") {\n        for (const [requestId, entry] of entries) {\n          entries.delete(requestId);\n          entry.latch.openUnsafe();\n        }\n        return broadcast(response);\n      } else if (\"requestId\" in response) {\n        const entry = entries.get(response.requestId);\n        if (entry) {\n          return writeResponse(entry.clientId, response);\n        }\n      }\n      return broadcast(response);\n    }, {\n      onSpawn: Option.isSome(initialMessage) ? Effect.flatMap(initialMessage.value, ([value, transfers]) => Effect.orDie(backing.send({\n        _tag: \"InitialMessage\",\n        value\n      }, transfers))) : undefined\n    }).pipe(Effect.tapCause(cause => {\n      const error = Cause.findError(cause);\n      return broadcast({\n        _tag: \"ClientProtocolError\",\n        error: new RpcClientError({\n          reason: Result.isSuccess(error) ? error.success.reason : new RpcClientDefect({\n            message: \"Error in worker\",\n            cause: Cause.squash(cause)\n          })\n        })\n      });\n    }), Effect.retry(Schedule.spaced(1000)), Effect.annotateLogs({\n      module: \"RpcClient\",\n      method: \"makeProtocolWorker\"\n    }), Effect.interruptible, Effect.forkScoped);\n    return backing;\n  });\n  const pool = \"minSize\" in options ? yield* Pool.makeWithTTL({\n    acquire,\n    min: options.minSize,\n    max: options.maxSize,\n    concurrency: options.concurrency,\n    targetUtilization: options.targetUtilization,\n    timeToLive: options.timeToLive\n  }) : yield* Pool.make({\n    acquire,\n    size: options.size,\n    concurrency: options.concurrency,\n    targetUtilization: options.targetUtilization\n  });\n  yield* Scope.addFinalizer(scope, Effect.sync(() => {\n    for (const entry of entries.values()) {\n      entry.latch.openUnsafe();\n    }\n    entries.clear();\n  }));\n  const send = (clientId, request, transferables) => {\n    switch (request._tag) {\n      case \"Request\":\n        {\n          return Pool.get(pool).pipe(Effect.flatMap(worker => {\n            const latch = Latch.makeUnsafe(false);\n            entries.set(request.id, {\n              clientId,\n              worker,\n              latch\n            });\n            return Effect.flatMap(worker.send(request, transferables), () => latch.await);\n          }), Effect.scoped, Effect.orDie);\n        }\n      case \"Interrupt\":\n        {\n          const entry = entries.get(request.requestId);\n          if (!entry) return Effect.void;\n          entries.delete(request.requestId);\n          entry.latch.openUnsafe();\n          return Effect.orDie(entry.worker.send(request));\n        }\n      case \"Ack\":\n        {\n          const entry = entries.get(request.requestId);\n          if (!entry) return Effect.void;\n          return Effect.orDie(entry.worker.send(request));\n        }\n    }\n    return Effect.void;\n  };\n  yield* Effect.scoped(Pool.get(pool));\n  if (Option.isSome(hooks)) yield* hooks.value.onConnect;\n  return {\n    send,\n    supportsAck: true,\n    supportsTransferables: true\n  };\n}));\n/**\n * Provides a client `Protocol` backed by a worker pool using the current worker\n * platform and spawner services.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PURE__*/Layer.effect(Protocol));\n/**\n * @since 4.0.0\n * @category RequestHooks\n */\nexport class RequestHooks extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcClient/RequestHooks\") {}\n/**\n * Represents optional client protocol hooks that run when a transport connects\n * and disconnects.\n *\n * **When to use**\n *\n * Use to run setup or cleanup effects when an RPC client transport opens or\n * closes.\n *\n * @category services\n * @since 4.0.0\n */\nexport class ConnectionHooks extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcClient/ConnectionHooks\") {}\n// internal\nconst decodeDefect = /*#__PURE__*/Schema.decodeSync(/*#__PURE__*/Schema.Defect());\n//# sourceMappingURL=RpcClient.js.map","import * as Cause from \"../../Cause.js\";\nimport * as Context from \"../../Context.js\";\nimport * as Deferred from \"../../Deferred.js\";\nimport * as Effect from \"../../Effect.js\";\nimport * as Exit from \"../../Exit.js\";\nimport * as Fiber from \"../../Fiber.js\";\nimport { constant, constTrue, constVoid, identity } from \"../../Function.js\";\nimport { reportCauseUnsafe } from \"../../internal/effect.js\";\nimport * as Latch from \"../../Latch.js\";\nimport * as Layer from \"../../Layer.js\";\nimport * as Option from \"../../Option.js\";\nimport * as Predicate from \"../../Predicate.js\";\nimport * as Pull from \"../../Pull.js\";\nimport * as Queue from \"../../Queue.js\";\nimport * as Schedule from \"../../Schedule.js\";\nimport * as Schema from \"../../Schema.js\";\nimport * as Scope from \"../../Scope.js\";\nimport * as Semaphore from \"../../Semaphore.js\";\nimport { Stdio } from \"../../Stdio.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as Tracer from \"../../Tracer.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as HttpServerRequest from \"../http/HttpServerRequest.js\";\nimport * as HttpServerResponse from \"../http/HttpServerResponse.js\";\nimport * as Socket from \"../socket/Socket.js\";\nimport * as SocketServer from \"../socket/SocketServer.js\";\nimport * as Transferable from \"../workers/Transferable.js\";\nimport * as WorkerRunner from \"../workers/WorkerRunner.js\";\nimport * as Rpc from \"./Rpc.js\";\nimport { constEof, constPong, RequestId, ResponseDefectEncoded } from \"./RpcMessage.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nimport * as RpcSerialization from \"./RpcSerialization.js\";\nimport { withRun } from \"./Utils.js\";\n/**\n * Creates an RPC server for an already-decoded message channel, running\n * handlers for a group and sending decoded server responses through\n * `onFromServer`.\n *\n * @category constructors\n * @since 4.0.0\n */\nexport const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n  const enableTracing = options.disableTracing !== true;\n  const enableSpanPropagation = options.disableSpanPropagation !== true;\n  const supportsAck = options.disableClientAcks !== true;\n  const spanPrefix = options.spanPrefix ?? \"RpcServer\";\n  const concurrency = options.concurrency ?? \"unbounded\";\n  const disableFatalDefects = options.disableFatalDefects ?? false;\n  const services = yield* Effect.context();\n  const scope = Context.get(services, Scope.Scope);\n  const trackFiber = Fiber.runIn(Scope.forkUnsafe(scope, \"parallel\"));\n  const concurrencySemaphore = concurrency === \"unbounded\" ? undefined : yield* Semaphore.make(concurrency);\n  const clients = new Map();\n  let isShutdown = false;\n  const shutdownLatch = Latch.makeUnsafe(false);\n  yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {\n    isShutdown = true;\n    for (const client of clients.values()) {\n      client.ended = true;\n      if (client.fibers.size === 0) {\n        trackFiber(Effect.runForkWith(services)(endClient(client)));\n        continue;\n      }\n      for (const fiber of client.fibers.values()) {\n        fiber.interruptUnsafe(parent.id);\n      }\n    }\n    if (clients.size === 0) {\n      return Effect.void;\n    }\n    return shutdownLatch.await;\n  }));\n  const disconnect = clientId => Effect.withFiber(parent => {\n    const client = clients.get(clientId);\n    if (!client) return Effect.void;\n    for (const fiber of client.fibers.values()) {\n      fiber.interruptUnsafe(parent.id);\n    }\n    clients.delete(clientId);\n    return Effect.void;\n  });\n  const write = (clientId, message, opts) => Effect.catchDefect(Effect.withFiber(requestFiber => {\n    if (isShutdown) return Effect.interrupt;\n    let client = clients.get(clientId);\n    if (!client) {\n      client = {\n        id: clientId,\n        latches: new Map(),\n        fibers: new Map(),\n        ended: false,\n        serverClient: new Rpc.ServerClient(clientId)\n      };\n      clients.set(clientId, client);\n    } else if (client.ended) {\n      return Effect.interrupt;\n    }\n    switch (message._tag) {\n      case \"Request\":\n        {\n          return handleRequest(requestFiber, client, message, opts);\n        }\n      case \"Ack\":\n        {\n          const latch = client.latches.get(message.requestId);\n          return latch ? latch.open : Effect.void;\n        }\n      case \"Interrupt\":\n        {\n          const fiber = client.fibers.get(message.requestId);\n          if (fiber) {\n            fiber.interruptUnsafe(requestFiber.id, RpcSchema.ClientAbort.annotation);\n            return Effect.void;\n          }\n          return options.onFromServer({\n            _tag: \"Exit\",\n            clientId,\n            requestId: message.requestId,\n            exit: Exit.interrupt()\n          });\n        }\n      case \"Eof\":\n        {\n          client.ended = true;\n          if (client.fibers.size > 0) return Effect.void;\n          return endClient(client);\n        }\n      default:\n        {\n          return sendDefect(client, `Unknown request tag: ${message._tag}`);\n        }\n    }\n  }), defect => sendDefect(clients.get(clientId), defect));\n  const endClient = client => {\n    clients.delete(client.id);\n    const write = options.onFromServer({\n      _tag: \"ClientEnd\",\n      clientId: client.id\n    });\n    if (isShutdown && clients.size === 0) {\n      return Effect.andThen(write, shutdownLatch.open);\n    }\n    return write;\n  };\n  const handleRequest = (requestFiber, client, request, opts) => {\n    if (client.fibers.has(request.id)) {\n      return Effect.interrupt;\n    }\n    const rpc = group.requests.get(request.tag);\n    const entry = services.mapUnsafe.get(rpc?.key);\n    if (!rpc || !entry) {\n      const write = Effect.catchDefect(options.onFromServer({\n        _tag: \"Exit\",\n        clientId: client.id,\n        requestId: request.id,\n        exit: Exit.die(`Unknown request tag: ${request.tag}`)\n      }), defect => sendDefect(client, defect));\n      if (!client.ended || client.fibers.size > 0) return write;\n      return Effect.ensuring(write, endClient(client));\n    }\n    const isStream = RpcSchema.isStreamSchema(rpc.successSchema);\n    const metadata = {\n      rpc,\n      client: client.serverClient,\n      requestId: request.id,\n      headers: request.headers,\n      payload: request.payload\n    };\n    const result = entry.handler(request.payload, metadata);\n    // if the handler requested forking, then we skip the concurrency control\n    const isWrapper = Rpc.isWrapper(result);\n    const isFork = isWrapper && result.fork;\n    const isUninterruptible = isWrapper && result.uninterruptible;\n    // unwrap the fork data type\n    const streamOrEffect = isWrapper ? result.value : result;\n    const handler = isStream ? streamEffect(client, request, streamOrEffect) : streamOrEffect;\n    const withMiddleware = rpc.middlewares.size > 0 ? applyMiddleware(services, handler, metadata) : handler;\n    let responded = false;\n    const scope = Scope.makeUnsafe();\n    let deferred = undefined;\n    let effect = Effect.onExit(withMiddleware, exit => {\n      responded = true;\n      let write;\n      if (exit._tag === \"Success\") {\n        if (Deferred.isDeferred(exit.value)) {\n          deferred = exit.value;\n          write = Effect.void;\n        } else {\n          write = options.onFromServer({\n            _tag: \"Exit\",\n            clientId: client.id,\n            requestId: request.id,\n            exit: exit\n          });\n        }\n      } else if (!disableFatalDefects && Cause.hasDies(exit.cause) && !Cause.hasInterrupts(exit.cause)) {\n        write = sendDefect(client, Cause.squash(exit.cause));\n      } else {\n        write = options.onFromServer({\n          _tag: \"Exit\",\n          clientId: client.id,\n          requestId: request.id,\n          exit: exit\n        });\n      }\n      const close = Scope.closeUnsafe(scope, exit);\n      if (exit._tag === \"Failure\") {\n        reportCauseUnsafe(Fiber.getCurrent(), exit.cause);\n      }\n      return close ? Effect.ensuring(write, close) : write;\n    });\n    if (opts?.onRequest) {\n      effect = opts.onRequest(effect);\n    }\n    if (enableTracing) {\n      const parentSpan = requestFiber.context.mapUnsafe.get(Tracer.ParentSpan.key);\n      effect = Effect.withSpan(effect, `${spanPrefix}.${request.tag}`, {\n        captureStackTrace: false,\n        attributes: options.spanAttributes,\n        parent: enableSpanPropagation && request.spanId ? Tracer.externalSpan({\n          traceId: request.traceId,\n          spanId: request.spanId,\n          sampled: request.sampled\n        }) : undefined,\n        links: enableSpanPropagation && parentSpan ? [{\n          span: parentSpan,\n          attributes: {}\n        }] : undefined\n      });\n    }\n    if (!isFork && concurrencySemaphore) {\n      effect = concurrencySemaphore.withPermit(effect);\n    }\n    const context = new Map(entry.context.mapUnsafe);\n    requestFiber.context.mapUnsafe.forEach((value, key) => context.set(key, value));\n    context.set(Scope.Scope.key, scope);\n    const runFork = Effect.runForkWith(Context.makeUnsafe(context));\n    const fiber = trackFiber(runFork(effect, isUninterruptible ? {\n      uninterruptible: true\n    } : undefined));\n    client.fibers.set(request.id, fiber);\n    fiber.addObserver(function onExit(exit) {\n      if (deferred) {\n        const fiber = trackFiber(runFork(Effect.onExit(Deferred.await(deferred), exit => options.onFromServer({\n          _tag: \"Exit\",\n          clientId: client.id,\n          requestId: request.id,\n          exit: exit\n        }))));\n        client.fibers.set(request.id, fiber);\n        deferred = undefined;\n        fiber.addObserver(onExit);\n        return;\n      }\n      if (!responded && exit._tag === \"Failure\") {\n        trackFiber(runFork(options.onFromServer({\n          _tag: \"Exit\",\n          clientId: client.id,\n          requestId: request.id,\n          exit: Exit.interrupt()\n        })));\n      }\n      client.fibers.delete(request.id);\n      client.latches.delete(request.id);\n      if (client.ended && client.fibers.size === 0) {\n        trackFiber(runFork(endClient(client)));\n      }\n    });\n    return Effect.void;\n  };\n  const streamEffect = (client, request, stream) => {\n    let latch = client.latches.get(request.id);\n    if (supportsAck && !latch) {\n      latch = Latch.makeUnsafe(false);\n      client.latches.set(request.id, latch);\n    }\n    if (Effect.isEffect(stream)) {\n      return stream.pipe(Effect.flatMap(queue => Effect.whileLoop({\n        while: constTrue,\n        body: constant(Effect.flatMap(Queue.takeAll(queue), values => {\n          const write = options.onFromServer({\n            _tag: \"Chunk\",\n            clientId: client.id,\n            requestId: request.id,\n            values\n          });\n          if (!latch) return write;\n          latch.closeUnsafe();\n          return Effect.flatMap(write, () => latch.await);\n        })),\n        step: constVoid\n      })), Pull.catchDone(() => Effect.void), Effect.scoped);\n    }\n    return Stream.runForEachArray(stream, values => {\n      const write = options.onFromServer({\n        _tag: \"Chunk\",\n        clientId: client.id,\n        requestId: request.id,\n        values\n      });\n      if (!latch) return write;\n      latch.closeUnsafe();\n      return Effect.andThen(write, latch.await);\n    });\n  };\n  const sendDefect = (client, defect) => Effect.suspend(() => {\n    const shouldEnd = client.ended && client.fibers.size === 0;\n    const write = options.onFromServer({\n      _tag: \"Defect\",\n      clientId: client.id,\n      defect\n    });\n    if (!shouldEnd) return write;\n    return Effect.andThen(write, endClient(client));\n  });\n  return identity({\n    write,\n    disconnect\n  });\n});\nconst applyMiddleware = (context, handler, options) => {\n  for (const service of options.rpc.middlewares) {\n    const middleware = Context.getUnsafe(context, service);\n    handler = middleware(handler, options);\n  }\n  return handler;\n};\n/**\n * Runs an RPC server for a group using the current server `Protocol`, decoding\n * requests, invoking handlers, encoding responses, and managing in-flight\n * request lifetime.\n *\n * @category running\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n  const {\n    disconnects,\n    end,\n    run,\n    send,\n    supportsAck,\n    supportsSpanPropagation,\n    supportsTransferables\n  } = yield* Protocol;\n  const services = yield* Effect.context();\n  const scope = yield* Scope.make();\n  const server = yield* makeNoSerialization(group, {\n    ...options,\n    disableClientAcks: !supportsAck,\n    disableSpanPropagation: !supportsSpanPropagation,\n    onFromServer(response) {\n      const client = clients.get(response.clientId);\n      if (!client) return Effect.void;\n      switch (response._tag) {\n        case \"Chunk\":\n          {\n            const schemas = client.schemas.get(response.requestId);\n            if (!schemas) return Effect.void;\n            return handleEncode(client, response.requestId, schemas.encodeDefect, schemas.collector, Effect.provideContext(schemas.encodeChunk(response.values), schemas.context), values => ({\n              _tag: \"Chunk\",\n              requestId: response.requestId,\n              values\n            }));\n          }\n        case \"Exit\":\n          {\n            const schemas = client.schemas.get(response.requestId);\n            if (!schemas) return Effect.void;\n            client.schemas.delete(response.requestId);\n            return handleEncode(client, response.requestId, schemas.encodeDefect, schemas.collector, Effect.provideContext(schemas.encodeExit(response.exit), schemas.context), exit => ({\n              _tag: \"Exit\",\n              requestId: response.requestId,\n              exit\n            }));\n          }\n        case \"Defect\":\n          {\n            return sendDefect(client, response.defect);\n          }\n        case \"ClientEnd\":\n          {\n            clients.delete(response.clientId);\n            return end(response.clientId);\n          }\n      }\n    }\n  }).pipe(Scope.provide(scope));\n  // handle disconnects\n  yield* Effect.forkChild(Effect.whileLoop({\n    while: constTrue,\n    body: constant(Effect.flatMap(Queue.take(disconnects), clientId => {\n      clients.delete(clientId);\n      return server.disconnect(clientId);\n    })),\n    step: constVoid\n  }));\n  const schemasCache = new WeakMap();\n  const getSchemas = rpc => {\n    let schemas = schemasCache.get(rpc);\n    if (!schemas) {\n      const entry = services.mapUnsafe.get(rpc.key);\n      const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n      schemas = {\n        decode: Schema.decodeUnknownEffect(Schema.toCodecJson(rpc.payloadSchema)),\n        encodeChunk: Schema.encodeUnknownEffect(Schema.toCodecJson(Schema.Array(Option.isSome(streamSchemas) ? streamSchemas.value.success : Schema.Any))),\n        encodeExit: Schema.encodeUnknownEffect(Schema.toCodecJson(Rpc.exitSchema(rpc))),\n        encodeDefect: Schema.encodeUnknownEffect(Schema.toCodecJson(rpc.defectSchema)),\n        context: entry.context\n      };\n      schemasCache.set(rpc, schemas);\n    }\n    return schemas;\n  };\n  const clients = new Map();\n  const handleEncode = (client, requestId, encodeDefect, collector, effect, onSuccess) => (collector ? Effect.provideService(effect, Transferable.Collector, collector) : effect).pipe(Effect.flatMap(a => send(client.id, onSuccess(a), collector && collector.clearUnsafe())), Effect.catchCause(cause => {\n    client.schemas.delete(requestId);\n    const defect = Cause.squash(Cause.map(cause, e => e.issue.toString()));\n    return Effect.andThen(sendRequestDefect(client, requestId, encodeDefect, defect), server.write(client.id, {\n      _tag: \"Interrupt\",\n      requestId,\n      interruptors: []\n    }));\n  }));\n  const sendRequestDefect = (client, requestId, encodeDefect, defect) => Effect.catchCause(Effect.flatMap(encodeDefect(defect), encodedDefect => send(client.id, {\n    _tag: \"Exit\",\n    requestId,\n    exit: {\n      _tag: \"Failure\",\n      cause: [{\n        _tag: \"Die\",\n        defect: encodedDefect\n      }]\n    }\n  })), cause => sendDefect(client, Cause.squash(cause)));\n  const sendDefect = (client, defect) => Effect.catchCause(send(client.id, ResponseDefectEncoded(defect)), cause => Effect.annotateLogs(Effect.logDebug(cause), {\n    module: \"RpcServer\",\n    method: \"sendDefect\"\n  }));\n  // main server loop\n  return yield* run((clientId, request) => {\n    let client = clients.get(clientId);\n    if (!client) {\n      client = {\n        id: clientId,\n        schemas: new Map()\n      };\n      clients.set(clientId, client);\n    }\n    switch (request._tag) {\n      case \"Request\":\n        {\n          const tag = Object.hasOwn(request, \"tag\") ? request.tag : \"\";\n          let requestId;\n          switch (typeof request.id) {\n            case \"number\":\n            case \"string\":\n              {\n                requestId = RequestId(request.id);\n                break;\n              }\n            default:\n              {\n                return sendDefect(client, `Invalid request id: ${request.id}`);\n              }\n          }\n          const rpc = group.requests.get(tag);\n          if (!rpc) {\n            return sendRequestDefect(client, requestId, defect => Effect.succeed(defect), `Unknown request tag: ${tag}`);\n          }\n          const schemas = getSchemas(rpc);\n          return Effect.matchEffect(Effect.provideContext(schemas.decode(request.payload), schemas.context), {\n            onFailure: error => sendRequestDefect(client, requestId, schemas.encodeDefect, error.issue.toString()),\n            onSuccess: payload => {\n              client.schemas.set(requestId, supportsTransferables ? {\n                ...schemas,\n                collector: Transferable.makeCollectorUnsafe()\n              } : schemas);\n              return server.write(clientId, {\n                ...request,\n                id: requestId,\n                payload,\n                headers: Headers.fromInput(request.headers)\n              });\n            }\n          });\n        }\n      case \"Ping\":\n        {\n          return Effect.catchCause(send(client.id, constPong), cause => sendDefect(client, Cause.squash(cause)));\n        }\n      case \"Eof\":\n        {\n          return server.write(clientId, request);\n        }\n      case \"Ack\":\n        {\n          return server.write(clientId, {\n            ...request,\n            requestId: RequestId(request.requestId)\n          });\n        }\n      case \"Interrupt\":\n        {\n          return server.write(clientId, {\n            ...request,\n            requestId: RequestId(request.requestId),\n            interruptors: []\n          });\n        }\n      default:\n        {\n          return sendDefect(client, `Unknown request tag: ${request._tag}`);\n        }\n    }\n  }).pipe(Effect.tapCause(cause => Effect.logFatal(\"BUG: RpcServer protocol crashed\", cause)), Effect.onExit(exit => Scope.close(scope, exit)));\n});\n/**\n * Provides a scoped layer that starts an RPC server for a group using the\n * current server `Protocol`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (group, options) => Layer.effectDiscard(Effect.forkScoped(make(group, options)));\n/**\n * Creates a RPC server that registers a HTTP route with a `HttpRouter`.\n *\n * **Details**\n *\n * Defaults to using websockets for communication, but can be configured to use\n * HTTP.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerHttp = options => layer(options.group, options).pipe(Layer.provide(options.protocol === \"http\" ? layerProtocolHttp(options) : layerProtocolWebsocket(options)));\n/**\n * Defines the service interface for an RPC server transport, responsible for receiving\n * encoded client messages, sending encoded responses, tracking clients, and\n * declaring transport capabilities.\n *\n * **When to use**\n *\n * Use to provide the transport boundary for RPC servers over HTTP, WebSocket,\n * workers, sockets, or custom protocols.\n *\n * @category services\n * @since 4.0.0\n */\nexport class Protocol extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcServer/Protocol\") {\n  /**\n   * Creates a server protocol service from the supplied RPC implementation.\n   *\n   * @since 4.0.0\n   */\n  static make = /*#__PURE__*/withRun();\n}\n/**\n * Creates a server `Protocol` backed by the current `SocketServer`, accepting\n * socket connections and routing decoded RPC messages.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolSocketServer = /*#__PURE__*/Effect.gen(function* () {\n  const server = yield* SocketServer.SocketServer;\n  const {\n    onSocket,\n    protocol\n  } = yield* makeSocketProtocol;\n  yield* Effect.forkScoped(server.run(Effect.fnUntraced(onSocket, Effect.scoped)));\n  return protocol;\n});\n/**\n * RPC protocol that uses `SocketServer` for communication.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolSocketServer = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolSocketServer);\n/**\n * Creates a websocket server `Protocol` together with an HTTP effect that\n * upgrades the current request to a websocket and attaches it to the protocol.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffectWebsocket = /*#__PURE__*/Effect.gen(function* () {\n  const {\n    onSocket,\n    protocol\n  } = yield* makeSocketProtocol;\n  const httpEffect = Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const socket = yield* Effect.orDie(request.upgrade);\n    yield* onSocket(socket, Object.entries(request.headers));\n    return HttpServerResponse.empty();\n  });\n  return {\n    protocol,\n    httpEffect\n  };\n});\n/**\n * Creates a websocket server `Protocol` and registers its upgrade handler as a\n * GET route on the current `HttpRouter`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const {\n    httpEffect,\n    protocol\n  } = yield* makeProtocolWithHttpEffectWebsocket;\n  const router = yield* HttpRouter.HttpRouter;\n  yield* router.add(\"GET\", options.path, httpEffect);\n  return protocol;\n});\n/**\n * RPC protocol that uses WebSockets for communication.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWebsocket = options => {\n  return Layer.effect(Protocol)(makeProtocolWebsocket(options));\n};\n/**\n * Creates an HTTP request/response server `Protocol` together with an HTTP\n * effect that decodes the current request and streams or returns encoded RPC\n * responses.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffect = /*#__PURE__*/Effect.gen(function* () {\n  const serialization = yield* RpcSerialization.RpcSerialization;\n  const includesFraming = serialization.includesFraming;\n  const isBinary = !serialization.contentType.includes(\"json\");\n  const disconnects = yield* Queue.make();\n  let writeRequest;\n  let clientId = 0;\n  const clients = new Map();\n  const clientIds = new Set();\n  const encoder = new TextEncoder();\n  const httpEffect = Effect.gen(function* () {\n    const fiber = Fiber.getCurrent();\n    const request = Context.getUnsafe(fiber.context, HttpServerRequest.HttpServerRequest);\n    const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n    const requestHeaders = Object.entries(request.headers);\n    const data = yield* Effect.orDie(isBinary ? Effect.map(request.arrayBuffer, buf => new Uint8Array(buf)) : request.text);\n    const id = clientId++;\n    const queue = yield* Queue.make();\n    const parser = serialization.makeUnsafe();\n    const requestIds = [];\n    const offer = data => typeof data === \"string\" ? Queue.offer(queue, encoder.encode(data)) : Queue.offer(queue, data);\n    const client = {\n      write: !includesFraming ? response => Queue.offer(queue, response) : response => {\n        try {\n          const encoded = parser.encode(response);\n          if (encoded === undefined) return Effect.void;\n          return offer(encoded);\n        } catch (cause) {\n          return offer(parser.encode(ResponseDefectEncoded(cause)));\n        }\n      },\n      end: Queue.end(queue)\n    };\n    yield* Scope.addFinalizerExit(scope, () => {\n      clients.delete(id);\n      clientIds.delete(id);\n      Queue.offerUnsafe(disconnects, id);\n      if (queue.state._tag === \"Done\") return Effect.void;\n      return Effect.forEach(requestIds, requestId => writeRequest(id, {\n        _tag: \"Interrupt\",\n        requestId\n      }), {\n        discard: true\n      });\n    });\n    clients.set(id, client);\n    clientIds.add(id);\n    // @effect-diagnostics-next-line tryCatchInEffectGen:off\n    try {\n      const decoded = parser.decode(data);\n      for (let i = 0; i < decoded.length; i++) {\n        const message = decoded[i];\n        if (message._tag === \"Request\") {\n          requestIds.push(RequestId(message.id));\n          message.headers = requestHeaders.concat(message.headers);\n        }\n        yield* writeRequest(id, message);\n      }\n    } catch (cause) {\n      yield* client.write(ResponseDefectEncoded(cause));\n    }\n    yield* writeRequest(id, constEof);\n    if (!includesFraming) {\n      const responses = yield* Queue.collect(queue);\n      return HttpServerResponse.text(parser.encode(responses), {\n        contentType: serialization.contentType\n      });\n    }\n    const initialChunk = yield* Queue.takeAll(queue);\n    if (queue.state._tag === \"Done\") {\n      return HttpServerResponse.uint8Array(mergeUint8Arrays(initialChunk), {\n        contentType: serialization.contentType\n      });\n    }\n    return HttpServerResponse.stream(Stream.fromArray(initialChunk).pipe(Stream.concat(Stream.fromQueue(queue))), {\n      contentType: serialization.contentType\n    });\n  });\n  const protocol = yield* Protocol.make(writeRequest_ => {\n    writeRequest = writeRequest_;\n    return Effect.succeed({\n      disconnects,\n      send(clientId, response) {\n        const client = clients.get(clientId);\n        if (!client) return Effect.void;\n        return client.write(response);\n      },\n      end(clientId) {\n        const client = clients.get(clientId);\n        if (!client) return Effect.void;\n        return client.end;\n      },\n      clientIds: Effect.sync(() => clientIds),\n      initialMessage: Effect.succeedNone,\n      supportsAck: false,\n      supportsTransferables: false,\n      supportsSpanPropagation: false\n    });\n  });\n  return {\n    protocol,\n    httpEffect\n  };\n});\nconst mergeUint8Arrays = arrays => {\n  if (arrays.length === 0) return new Uint8Array(0);\n  if (arrays.length === 1) return arrays[0];\n  const length = arrays.reduce((acc, arr) => acc + arr.length, 0);\n  const result = new Uint8Array(length);\n  let offset = 0;\n  for (const arr of arrays) {\n    result.set(arr, offset);\n    offset += arr.length;\n  }\n  return result;\n};\n/**\n * Creates an HTTP server `Protocol` and registers its request handler as a POST\n * route on the current `HttpRouter`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolHttp = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n  const {\n    httpEffect,\n    protocol\n  } = yield* makeProtocolWithHttpEffect;\n  const router = yield* HttpRouter.HttpRouter;\n  yield* router.add(\"POST\", options.path, httpEffect);\n  return protocol;\n});\n/**\n * Provides a server `Protocol` that uses HTTP POST requests for RPC\n * communication.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolHttp = options => {\n  return Layer.effect(Protocol)(makeProtocolHttp(options));\n};\n/**\n * Starts an RPC server for a group and returns the HTTP request/response effect\n * that serves the non-websocket HTTP RPC protocol.\n *\n * @category running\n * @since 4.0.0\n */\nexport const toHttpEffect = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n  const {\n    httpEffect,\n    protocol\n  } = yield* makeProtocolWithHttpEffect;\n  yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n  // @effect-diagnostics-next-line returnEffectInGen:off\n  return httpEffect;\n});\n/**\n * Starts an RPC server for a group and returns the HTTP effect that upgrades\n * requests to the websocket RPC protocol.\n *\n * @category running\n * @since 4.0.0\n */\nexport const toHttpEffectWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n  const {\n    httpEffect,\n    protocol\n  } = yield* makeProtocolWithHttpEffectWebsocket;\n  yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n  // @effect-diagnostics-next-line returnEffectInGen:off\n  return httpEffect;\n});\n/**\n * Creates a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolStdio = /*#__PURE__*/Effect.gen(function* () {\n  const stdio = yield* Stdio;\n  const fiber = Fiber.getCurrent();\n  const serialization = yield* RpcSerialization.RpcSerialization;\n  return yield* Protocol.make(Effect.fnUntraced(function* (writeRequest) {\n    const queue = yield* Queue.make();\n    const parser = serialization.makeUnsafe();\n    yield* stdio.stdin.pipe(Stream.runForEach(data => {\n      const decoded = parser.decode(data);\n      if (decoded.length === 0) return Effect.void;\n      let i = 0;\n      return Effect.whileLoop({\n        while: () => i < decoded.length,\n        body: () => writeRequest(0, decoded[i++]),\n        step: constVoid\n      });\n    }), Effect.sandbox, Effect.tapError(Effect.logError), Effect.retry(Schedule.spaced(500)), Effect.ensuring(Effect.forkDetach(Fiber.interrupt(fiber), {\n      startImmediately: true\n    })), Effect.forkScoped);\n    yield* Stream.fromQueue(queue).pipe(Stream.run(stdio.stdout()), Effect.retry(Schedule.spaced(500)), Effect.forkScoped);\n    return {\n      disconnects: yield* Queue.make(),\n      send(_clientId, response) {\n        const responseEncoded = parser.encode(response);\n        if (responseEncoded === undefined) {\n          return Effect.void;\n        }\n        return Queue.offer(queue, responseEncoded);\n      },\n      end(_clientId) {\n        return Queue.end(queue);\n      },\n      clientIds: Effect.succeed(new Set([0])),\n      initialMessage: Effect.succeedNone,\n      supportsAck: true,\n      supportsTransferables: false,\n      supportsSpanPropagation: true\n    };\n  }));\n});\n/**\n * Provides a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolStdio = /*#__PURE__*/Layer.effect(Protocol, makeProtocolStdio);\n/**\n * Creates a server `Protocol` backed by `WorkerRunnerPlatform`, routing worker\n * messages to the RPC server and server responses back to workers.\n *\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWorkerRunner = /*#__PURE__*/Protocol.make(/*#__PURE__*/Effect.fnUntraced(function* (writeRequest) {\n  const fiber = Fiber.getCurrent();\n  const runner = yield* WorkerRunner.WorkerRunnerPlatform;\n  const backing = yield* runner.start();\n  const initialMessage = yield* Deferred.make();\n  const clientIds = new Set();\n  const disconnects = yield* Queue.make();\n  yield* backing.run((clientId, message) => {\n    clientIds.add(clientId);\n    if (message._tag === \"InitialMessage\") {\n      return Deferred.succeed(initialMessage, message.value);\n    }\n    return writeRequest(clientId, message);\n  }).pipe(Effect.tapCause(Effect.logError), Effect.onExit(() => Effect.sync(() => {\n    fiber.currentDispatcher.scheduleTask(() => fiber.interruptUnsafe(fiber.id), 0);\n  })), Effect.forkScoped);\n  if (backing.disconnects) {\n    yield* Queue.take(backing.disconnects).pipe(Effect.tap(clientId => {\n      clientIds.delete(clientId);\n      return Queue.offer(disconnects, clientId);\n    }), Effect.forkScoped);\n  }\n  return {\n    disconnects,\n    send: backing.send,\n    end(_clientId) {\n      return Effect.void;\n    },\n    clientIds: Effect.sync(() => clientIds),\n    initialMessage: Effect.asSome(Deferred.await(initialMessage)),\n    supportsAck: true,\n    supportsTransferables: true,\n    supportsSpanPropagation: true\n  };\n}));\n/**\n * Provides a server `Protocol` backed by the current `WorkerRunnerPlatform`.\n *\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWorkerRunner = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolWorkerRunner);\n// internal\nconst makeSocketProtocol = /*#__PURE__*/Effect.gen(function* () {\n  const serialization = yield* RpcSerialization.RpcSerialization;\n  const disconnects = yield* Queue.make();\n  let clientId = 0;\n  const clients = new Map();\n  const clientIds = new Set();\n  let writeRequest;\n  const onSocket = function* (socket, headers) {\n    const scope = yield* Effect.scope;\n    const parser = serialization.makeUnsafe();\n    const id = clientId++;\n    yield* Scope.addFinalizerExit(scope, () => {\n      clients.delete(id);\n      clientIds.delete(id);\n      return Queue.offer(disconnects, id);\n    });\n    const writeRaw = yield* socket.writer;\n    const write = response => {\n      try {\n        const encoded = parser.encode(response);\n        if (encoded === undefined) {\n          return Effect.void;\n        }\n        return Effect.orDie(writeRaw(encoded));\n      } catch (cause) {\n        return Effect.orDie(writeRaw(parser.encode(ResponseDefectEncoded(cause))));\n      }\n    };\n    clients.set(id, {\n      write\n    });\n    clientIds.add(id);\n    yield* socket.runRaw(data => {\n      try {\n        const decoded = parser.decode(data);\n        if (decoded.length === 0) return Effect.void;\n        let i = 0;\n        return Effect.whileLoop({\n          while: () => i < decoded.length,\n          body() {\n            const message = decoded[i++];\n            if (message._tag === \"Request\" && headers) {\n              ;\n              message.headers = headers.concat(message.headers);\n            }\n            return writeRequest(id, message);\n          },\n          step: constVoid\n        });\n      } catch (cause) {\n        if (Predicate.isTagged(cause, \"MaxBufferSizeExceeded\")) {\n          return writeRaw(new Socket.CloseEvent(1009, String(cause)));\n        }\n        return writeRaw(parser.encode(ResponseDefectEncoded(cause)));\n      }\n    }).pipe(Effect.catchReason(\"SocketError\", \"SocketCloseError\", _ => Effect.void), Effect.orDie);\n  };\n  const protocol = yield* Protocol.make(writeRequest_ => {\n    writeRequest = writeRequest_;\n    return Effect.succeed({\n      disconnects,\n      send: (clientId, response) => {\n        const client = clients.get(clientId);\n        if (!client) return Effect.void;\n        return Effect.orDie(client.write(response));\n      },\n      end(_clientId) {\n        return Effect.void;\n      },\n      clientIds: Effect.sync(() => clientIds),\n      initialMessage: Effect.succeedNone,\n      supportsAck: true,\n      supportsTransferables: false,\n      supportsSpanPropagation: true\n    });\n  });\n  return {\n    protocol,\n    onSocket\n  };\n});\n//# sourceMappingURL=RpcServer.js.map","/**\n * ProviderRegistry - Provider snapshot service.\n *\n * Owns provider install/auth/version/model snapshots and exposes the latest\n * provider state to transport layers.\n *\n * @module ProviderRegistry\n */\nimport type {\n  ProviderInstanceId,\n  ProviderDriverKind,\n  ServerProvider,\n  ServerProviderUpdateState,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\nimport type { ProviderMaintenanceCapabilities } from \"../providerMaintenance.ts\";\n\nexport type ProviderMaintenanceActionKind = \"update\";\n\nexport interface ProviderRegistryShape {\n  /**\n   * Read the latest provider snapshots for every configured instance.\n   * Multiple snapshots may share the same `provider` kind (multiple\n   * instances of the same driver) and disambiguate via `instanceId`.\n   */\n  readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Refresh all providers, or the default instance of the specified\n   * kind when supplied.\n   *\n   * Retained for back-compat with legacy call sites (WS refresh RPC,\n   * orchestration metrics). New code should prefer `refreshInstance`.\n   *\n   * @deprecated prefer `refreshInstance` for new call sites.\n   */\n  readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Refresh the specific configured instance. Returns the updated snapshot\n   * list. When the instance id is unknown the call resolves with the\n   * currently cached list (no error) — matching the legacy `refresh` shim\n   * behaviour so transport layers don't have to special-case unknowns.\n   */\n  readonly refreshInstance: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Resolve the maintenance capabilities owned by one live provider instance.\n   * Falls back to manual-only capabilities when the instance is not live.\n   */\n  readonly getProviderMaintenanceCapabilitiesForInstance: (\n    instanceId: ProviderInstanceId,\n    provider: ProviderDriverKind,\n  ) => Effect.Effect<ProviderMaintenanceCapabilities>;\n\n  /**\n   * Apply volatile maintenance-action state to one configured instance.\n   * This state is never persisted to disk. Today only update actions are\n   * projected onto `ServerProvider.updateState`; install/auth actions can\n   * extend this action map without adding driver-scoped APIs.\n   */\n  readonly setProviderMaintenanceActionState: (input: {\n    readonly instanceId: ProviderInstanceId;\n    readonly action: ProviderMaintenanceActionKind;\n    readonly state: ServerProviderUpdateState | null;\n  }) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Stream of provider snapshot updates — one emission per aggregated\n   * change. The array contains the full current state.\n   */\n  readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;\n}\n\nexport class ProviderRegistry extends Context.Service<ProviderRegistry, ProviderRegistryShape>()(\n  \"t3/provider/Services/ProviderRegistry\",\n) {}\n","import * as Effect from \"effect/Effect\";\nimport * as Ref from \"effect/Ref\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nexport interface ProviderMaintenanceCommandCoordinatorShape<E> {\n  readonly withCommandLock: <A, R>(input: {\n    readonly targetKey: string;\n    readonly lockKey: string;\n    readonly onQueued?: Effect.Effect<void, E, R>;\n    readonly run: Effect.Effect<A, E, R>;\n  }) => Effect.Effect<A, E, R>;\n}\n\nexport const makeProviderMaintenanceCommandCoordinator = Effect.fn(\n  \"makeProviderMaintenanceCommandCoordinator\",\n)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {\n  const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());\n  const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());\n\n  const acquireTarget = Effect.fn(\"acquireTarget\")(function* (targetKey: string) {\n    return yield* Ref.modify(runningTargetsRef, (runningTargets) => {\n      if (runningTargets.has(targetKey)) {\n        return [false, runningTargets] as const;\n      }\n      const next = new Set(runningTargets);\n      next.add(targetKey);\n      return [true, next] as const;\n    });\n  });\n\n  const releaseTarget = (targetKey: string) =>\n    Ref.update(runningTargetsRef, (runningTargets) => {\n      const next = new Set(runningTargets);\n      next.delete(targetKey);\n      return next;\n    });\n\n  const getLock = Effect.fn(\"getProviderMaintenanceCommandLock\")(function* (lockKey: string) {\n    const existing = (yield* Ref.get(locksRef)).get(lockKey);\n    if (existing) {\n      return existing;\n    }\n\n    const lock = yield* Semaphore.make(1);\n    return yield* Ref.modify(locksRef, (locks) => {\n      const current = locks.get(lockKey);\n      if (current) {\n        return [current, locks] as const;\n      }\n      const next = new Map(locks);\n      next.set(lockKey, lock);\n      return [lock, next] as const;\n    });\n  });\n\n  const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>[\"withCommandLock\"] = ({\n    targetKey,\n    lockKey,\n    onQueued,\n    run,\n  }) =>\n    Effect.gen(function* () {\n      const acquired = yield* acquireTarget(targetKey);\n      if (!acquired) {\n        return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));\n      }\n\n      return yield* Effect.gen(function* () {\n        const lock = yield* getLock(lockKey);\n        if (onQueued) {\n          yield* onQueued;\n        }\n        return yield* lock.withPermits(1)(run);\n      }).pipe(Effect.ensuring(releaseTarget(targetKey)));\n    });\n\n  return {\n    withCommandLock,\n  } satisfies ProviderMaintenanceCommandCoordinatorShape<E>;\n});\n","interface ParsedSemver {\n  readonly major: number;\n  readonly minor: number;\n  readonly patch: number;\n  readonly prerelease: ReadonlyArray<string>;\n}\n\nconst SEMVER_NUMBER_SEGMENT = /^\\d+$/;\n\nexport function normalizeSemverVersion(version: string): string {\n  const [main, prerelease] = version.trim().split(\"-\", 2);\n  const segments: string[] = [];\n  for (const segment of (main ?? \"\").split(\".\")) {\n    const trimmed = segment.trim();\n    if (trimmed.length > 0) {\n      segments.push(trimmed);\n    }\n  }\n\n  // Pad shorthand versions (\"20\" or \"20.1\") up to three segments so major-only\n  // and minor-only inputs parse and compare numerically. This matches\n  // satisfiesSemverRange, which already treats a missing minor/patch as 0. The\n  // length > 0 guard keeps empty/garbage input empty (parseSemver still\n  // rejects it), and inputs with more than three segments are left untouched.\n  while (segments.length > 0 && segments.length < 3) {\n    segments.push(\"0\");\n  }\n\n  return prerelease ? `${segments.join(\".\")}-${prerelease}` : segments.join(\".\");\n}\n\nexport function parseSemver(value: string): ParsedSemver | null {\n  const normalized = normalizeSemverVersion(value).replace(/^v/, \"\");\n  const [main = \"\", prerelease] = normalized.split(\"-\", 2);\n  const segments = main.split(\".\");\n  if (segments.length !== 3) {\n    return null;\n  }\n\n  const [majorSegment, minorSegment, patchSegment] = segments;\n  if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {\n    return null;\n  }\n  if (\n    !SEMVER_NUMBER_SEGMENT.test(majorSegment) ||\n    !SEMVER_NUMBER_SEGMENT.test(minorSegment) ||\n    !SEMVER_NUMBER_SEGMENT.test(patchSegment)\n  ) {\n    return null;\n  }\n\n  const major = Number.parseInt(majorSegment, 10);\n  const minor = Number.parseInt(minorSegment, 10);\n  const patch = Number.parseInt(patchSegment, 10);\n  if (![major, minor, patch].every(Number.isInteger)) {\n    return null;\n  }\n\n  return {\n    major,\n    minor,\n    patch,\n    prerelease: parsePrereleaseSegments(prerelease),\n  };\n}\n\nfunction parsePrereleaseSegments(prerelease: string | undefined): ReadonlyArray<string> {\n  if (prerelease === undefined) {\n    return [];\n  }\n  const segments: string[] = [];\n  for (const segment of prerelease.split(\".\")) {\n    const trimmed = segment.trim();\n    if (trimmed.length > 0) {\n      segments.push(trimmed);\n    }\n  }\n  return segments;\n}\n\nfunction comparePrereleaseIdentifier(left: string, right: string): number {\n  const leftNumeric = SEMVER_NUMBER_SEGMENT.test(left);\n  const rightNumeric = SEMVER_NUMBER_SEGMENT.test(right);\n\n  if (leftNumeric && rightNumeric) {\n    return Number.parseInt(left, 10) - Number.parseInt(right, 10);\n  }\n  if (leftNumeric) {\n    return -1;\n  }\n  if (rightNumeric) {\n    return 1;\n  }\n  return left.localeCompare(right);\n}\n\nexport function compareSemverVersions(left: string, right: string): number {\n  const parsedLeft = parseSemver(left);\n  const parsedRight = parseSemver(right);\n  if (!parsedLeft || !parsedRight) {\n    return left.localeCompare(right);\n  }\n\n  if (parsedLeft.major !== parsedRight.major) {\n    return parsedLeft.major - parsedRight.major;\n  }\n  if (parsedLeft.minor !== parsedRight.minor) {\n    return parsedLeft.minor - parsedRight.minor;\n  }\n  if (parsedLeft.patch !== parsedRight.patch) {\n    return parsedLeft.patch - parsedRight.patch;\n  }\n\n  if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {\n    return 0;\n  }\n  if (parsedLeft.prerelease.length === 0) {\n    return 1;\n  }\n  if (parsedRight.prerelease.length === 0) {\n    return -1;\n  }\n\n  const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);\n  for (let index = 0; index < length; index += 1) {\n    const leftIdentifier = parsedLeft.prerelease[index];\n    const rightIdentifier = parsedRight.prerelease[index];\n    if (leftIdentifier === undefined) {\n      return -1;\n    }\n    if (rightIdentifier === undefined) {\n      return 1;\n    }\n    const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);\n    if (comparison !== 0) {\n      return comparison;\n    }\n  }\n\n  return 0;\n}\n\n/**\n * Small semver range checker for CLI/runtime gates.\n *\n * Keep the function body valid plain JavaScript: SSH startup stringifies this\n * function and runs it on remote Node versions before TypeScript support is known.\n *\n * @param rawVersion Version string, with or without a leading `v`.\n * @param range Space-separated comparators, with `||` range groups.\n * @returns Whether `rawVersion` satisfies the supported range syntax.\n */\nexport const satisfiesSemverRange: (rawVersion: string, range: string) => boolean =\n  function satisfiesSemverRange(rawVersion, range) {\n    const normalizedVersion = String(rawVersion).trim().replace(/^v/, \"\");\n    const versionMatch = normalizedVersion.match(\n      /^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:-[0-9A-Za-z.-]+)?$/,\n    );\n    if (!versionMatch) {\n      return false;\n    }\n\n    const version = {\n      major: Number(versionMatch[1]),\n      minor: Number(versionMatch[2] || 0),\n      patch: Number(versionMatch[3] || 0),\n    };\n\n    return range.split(\"||\").some((group) => {\n      const comparators = group.trim().split(/\\s+/).filter(Boolean);\n      if (comparators.length === 0) {\n        return false;\n      }\n      return comparators.every((comparator) => {\n        const match = comparator.trim().match(/^(\\^|>=|>|<=|<|=)?\\s*v?(\\d+(?:\\.\\d+){0,2})$/);\n        if (!match) {\n          return false;\n        }\n        const targetVersion = match[2];\n        if (targetVersion === undefined) {\n          return false;\n        }\n        const targetMatch = targetVersion.match(/^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/);\n        if (!targetMatch) {\n          return false;\n        }\n        const target = {\n          major: Number(targetMatch[1]),\n          minor: Number(targetMatch[2] || 0),\n          patch: Number(targetMatch[3] || 0),\n        };\n        const compared =\n          version.major !== target.major\n            ? version.major > target.major\n              ? 1\n              : -1\n            : version.minor !== target.minor\n              ? version.minor > target.minor\n                ? 1\n                : -1\n              : version.patch !== target.patch\n                ? version.patch > target.patch\n                  ? 1\n                  : -1\n                : 0;\n        const operator = match[1] || \"=\";\n        switch (operator) {\n          case \"^\":\n            if (compared < 0) {\n              return false;\n            }\n            if (target.major > 0) {\n              return version.major === target.major;\n            }\n            if (target.minor > 0) {\n              return version.major === 0 && version.minor === target.minor;\n            }\n            return version.major === 0 && version.minor === 0 && version.patch === target.patch;\n          case \">=\":\n            return compared >= 0;\n          case \">\":\n            return compared > 0;\n          case \"<=\":\n            return compared <= 0;\n          case \"<\":\n            return compared < 0;\n          case \"=\":\n            return compared === 0;\n          default:\n            return false;\n        }\n      });\n    });\n  };\n","import {\n  ProviderDriverKind,\n  type ServerProvider,\n  type ServerProviderVersionAdvisory,\n} from \"@t3tools/contracts\";\nimport { compareSemverVersions } from \"@t3tools/shared/semver\";\nimport { resolveCommandPath } from \"@t3tools/shared/shell\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nconst LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;\nconst LATEST_VERSION_TIMEOUT_MS = 4_000;\nconst PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = \"Install the update now or review provider settings.\";\n\nconst compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>\n  Object.fromEntries(\n    Object.entries(input).flatMap(([key, value]) =>\n      Option.match(value, {\n        onNone: () => [],\n        onSome: (resolved) => [[key, resolved]],\n      }),\n    ),\n  );\n\nconst CommandLookupEnvConfig = Config.all({\n  PATH: Config.string(\"PATH\").pipe(Config.option),\n  Path: Config.string(\"Path\").pipe(Config.option),\n  path: Config.string(\"path\").pipe(Config.option),\n  PATHEXT: Config.string(\"PATHEXT\").pipe(Config.option),\n}).pipe(Config.map(compactEnv));\n\nconst readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));\n\nexport interface ProviderMaintenanceCapabilities {\n  readonly provider: ProviderDriverKind;\n  readonly packageName: string | null;\n  readonly update: ProviderMaintenanceCommandAction | null;\n}\n\nexport interface ProviderMaintenanceCommandAction {\n  readonly command: string;\n  readonly executable: string;\n  readonly args: ReadonlyArray<string>;\n  readonly lockKey: string;\n}\n\nexport interface ProviderMaintenanceCapabilityResolutionOptions {\n  readonly binaryPath?: string | null;\n  readonly env?: NodeJS.ProcessEnv;\n  readonly resolvedCommandPath?: string | null;\n  readonly realCommandPath?: string | null;\n}\n\nexport interface ProviderMaintenanceCapabilitiesResolver {\n  readonly resolve: (\n    options?: ProviderMaintenanceCapabilityResolutionOptions,\n  ) => ProviderMaintenanceCapabilities;\n}\n\nexport interface PackageManagedProviderMaintenanceDefinition {\n  readonly provider: ProviderDriverKind;\n  readonly npmPackageName: string;\n  readonly homebrewFormula: string | null;\n  readonly nativeUpdate: {\n    readonly executable: string;\n    readonly args: ReadonlyArray<string>;\n    readonly lockKey: string;\n    readonly isCommandPath: (commandPath: string) => boolean;\n  } | null;\n}\n\nexport interface ProviderVersionCacheEntry {\n  readonly expiresAt: number;\n  readonly version: string | null;\n}\n\nexport const ProviderVersionCache = Context.Reference<Map<string, ProviderVersionCacheEntry>>(\n  \"@t3tools/server/providerMaintenance/ProviderVersionCache\",\n  {\n    defaultValue: () => new Map(),\n  },\n);\nconst NpmLatestVersionResponse = Schema.Struct({\n  version: Schema.optional(Schema.String),\n});\n\nfunction nonEmptyString(value: unknown): string | null {\n  return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\nexport function makeProviderMaintenanceCapabilities(input: {\n  readonly provider: ProviderDriverKind;\n  readonly packageName: string | null;\n  readonly updateExecutable: string | null;\n  readonly updateArgs: ReadonlyArray<string>;\n  readonly updateLockKey: string | null;\n}): ProviderMaintenanceCapabilities {\n  const update =\n    input.updateExecutable === null || input.updateLockKey === null\n      ? null\n      : {\n          command: [input.updateExecutable, ...input.updateArgs].join(\" \"),\n          executable: input.updateExecutable,\n          args: input.updateArgs,\n          lockKey: input.updateLockKey,\n        };\n  return {\n    provider: input.provider,\n    packageName: input.packageName,\n    update,\n  };\n}\n\nexport function makeManualOnlyProviderMaintenanceCapabilities(input: {\n  readonly provider: ProviderDriverKind;\n  readonly packageName: string | null;\n}): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: input.provider,\n    packageName: input.packageName,\n    updateExecutable: null,\n    updateArgs: [],\n    updateLockKey: null,\n  });\n}\n\nfunction makeNpmGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"npm\",\n    updateArgs: [\"install\", \"-g\", `${definition.npmPackageName}@latest`],\n    updateLockKey: \"npm-global\",\n  });\n}\n\nfunction makeBunGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"bun\",\n    updateArgs: [\"i\", \"-g\", `${definition.npmPackageName}@latest`],\n    updateLockKey: \"bun-global\",\n  });\n}\n\nfunction makePnpmGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"pnpm\",\n    updateArgs: [\"add\", \"-g\", `${definition.npmPackageName}@latest`],\n    updateLockKey: \"pnpm-global\",\n  });\n}\n\nfunction makeVitePlusGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"vp\",\n    updateArgs: [\"i\", \"-g\", definition.npmPackageName],\n    updateLockKey: \"vite-plus-global\",\n  });\n}\n\nfunction makeHomebrewProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  if (!definition.homebrewFormula) {\n    return makeManualOnlyProviderMaintenanceCapabilities({\n      provider: definition.provider,\n      packageName: definition.npmPackageName,\n    });\n  }\n\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"brew\",\n    updateArgs: [\"upgrade\", definition.homebrewFormula],\n    updateLockKey: \"homebrew\",\n  });\n}\n\nfunction makeNativeProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities | null {\n  if (!definition.nativeUpdate) {\n    return null;\n  }\n\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: definition.nativeUpdate.executable,\n    updateArgs: definition.nativeUpdate.args,\n    updateLockKey: definition.nativeUpdate.lockKey,\n  });\n}\n\nexport function hasPathSeparator(value: string): boolean {\n  return value.includes(\"/\") || value.includes(\"\\\\\");\n}\n\nexport function normalizeCommandPath(commandPath: string): string {\n  return commandPath.replaceAll(\"\\\\\", \"/\").toLowerCase();\n}\n\nfunction isBunGlobalCommandPath(commandPath: string): boolean {\n  return normalizeCommandPath(commandPath).includes(\"/.bun/bin/\");\n}\n\nfunction isVitePlusGlobalCommandPath(commandPath: string): boolean {\n  return normalizeCommandPath(commandPath).includes(\"/.vite-plus/bin/\");\n}\n\nfunction isPnpmGlobalCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.includes(\"/.local/share/pnpm/\") ||\n    normalized.includes(\"/library/pnpm/\") ||\n    normalized.includes(\"/local/share/pnpm/\") ||\n    normalized.includes(\"/appdata/local/pnpm/\") ||\n    normalized.includes(\"/pnpm/global/\")\n  );\n}\n\nfunction isNpmGlobalCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.includes(\"/node_modules/.bin/\") ||\n    normalized.includes(\"/lib/node_modules/\") ||\n    normalized.includes(\"/npm/node_modules/\")\n  );\n}\n\nfunction isHomebrewCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.includes(\"/opt/homebrew/cellar/\") ||\n    normalized.includes(\"/usr/local/cellar/\") ||\n    normalized.includes(\"/homebrew/cellar/\") ||\n    normalized.includes(\"/opt/homebrew/caskroom/\") ||\n    normalized.includes(\"/usr/local/caskroom/\") ||\n    normalized.includes(\"/homebrew/caskroom/\") ||\n    normalized.startsWith(\"/opt/homebrew/bin/\") ||\n    normalized.startsWith(\"/usr/local/bin/\")\n  );\n}\n\nexport function resolvePackageManagedProviderMaintenance(\n  definition: PackageManagedProviderMaintenanceDefinition,\n  options?: ProviderMaintenanceCapabilityResolutionOptions,\n): ProviderMaintenanceCapabilities {\n  const binaryPath = nonEmptyString(options?.binaryPath);\n  if (!binaryPath) {\n    return makeNpmGlobalProviderMaintenanceCapabilities(definition);\n  }\n\n  const resolvedCommandPath =\n    options?.resolvedCommandPath ?? (hasPathSeparator(binaryPath) ? binaryPath : null);\n\n  if (resolvedCommandPath) {\n    const commandPaths = [\n      resolvedCommandPath,\n      ...(options?.realCommandPath ? [options.realCommandPath] : []),\n    ];\n\n    const nativeUpdate = definition.nativeUpdate;\n    if (\n      nativeUpdate &&\n      commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))\n    ) {\n      return (\n        makeNativeProviderMaintenanceCapabilities(definition) ??\n        makeNpmGlobalProviderMaintenanceCapabilities(definition)\n      );\n    }\n    if (commandPaths.some(isVitePlusGlobalCommandPath)) {\n      return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isBunGlobalCommandPath)) {\n      return makeBunGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isPnpmGlobalCommandPath)) {\n      return makePnpmGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isNpmGlobalCommandPath)) {\n      return makeNpmGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isHomebrewCommandPath)) {\n      return makeHomebrewProviderMaintenanceCapabilities(definition);\n    }\n  }\n\n  if (!hasPathSeparator(binaryPath)) {\n    return makeNpmGlobalProviderMaintenanceCapabilities(definition);\n  }\n\n  return makeManualOnlyProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n  });\n}\n\nexport function makePackageManagedProviderMaintenanceResolver(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilitiesResolver {\n  return {\n    resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),\n  };\n}\n\nexport function makeStaticProviderMaintenanceResolver(\n  capabilities: ProviderMaintenanceCapabilities,\n): ProviderMaintenanceCapabilitiesResolver {\n  return {\n    resolve: () => capabilities,\n  };\n}\n\nfunction makeManualProviderMaintenanceCapabilities(\n  provider: ProviderDriverKind,\n): ProviderMaintenanceCapabilities {\n  return makeManualOnlyProviderMaintenanceCapabilities({\n    provider,\n    packageName: null,\n  });\n}\n\nexport const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(\n  \"resolveProviderMaintenanceCapabilitiesEffect\",\n)(function* (\n  resolver: ProviderMaintenanceCapabilitiesResolver,\n  options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, \"realCommandPath\">,\n) {\n  const binaryPath = nonEmptyString(options?.binaryPath);\n  if (!binaryPath) {\n    return resolver.resolve(options);\n  }\n\n  const env = options?.env ?? (yield* readCommandLookupEnv);\n  const resolvedCommandPath =\n    (yield* resolveCommandPath(binaryPath, { env }).pipe(\n      Effect.catchTag(\"CommandResolutionError\", () => Effect.succeed(null)),\n    )) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);\n  if (!resolvedCommandPath) {\n    return resolver.resolve(options);\n  }\n\n  const fileSystem = yield* FileSystem.FileSystem;\n  const realCommandPath = yield* fileSystem\n    .realPath(resolvedCommandPath)\n    .pipe(Effect.orElseSucceed(() => resolvedCommandPath));\n  return resolver.resolve({\n    ...options,\n    env,\n    resolvedCommandPath,\n    realCommandPath,\n  });\n});\n\nfunction deriveVersionAdvisory(input: {\n  readonly currentVersion: string | null;\n  readonly latestVersion: string | null;\n}): Pick<ServerProviderVersionAdvisory, \"status\" | \"message\"> {\n  if (!input.currentVersion) {\n    return { status: \"unknown\", message: null };\n  }\n  if (!input.latestVersion) {\n    return { status: \"unknown\", message: null };\n  }\n  if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {\n    return {\n      status: \"behind_latest\",\n      message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,\n    };\n  }\n  return { status: \"current\", message: null };\n}\n\nexport function createProviderVersionAdvisory(input: {\n  readonly driver: ProviderDriverKind;\n  readonly currentVersion: string | null;\n  readonly latestVersion?: string | null;\n  readonly checkedAt?: string | null;\n  readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;\n}): ServerProviderVersionAdvisory {\n  const capabilities =\n    input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);\n  const latestVersion = input.latestVersion ?? null;\n  const advisory = deriveVersionAdvisory({\n    currentVersion: input.currentVersion,\n    latestVersion,\n  });\n\n  return {\n    status: advisory.status,\n    currentVersion: input.currentVersion,\n    latestVersion,\n    updateCommand: capabilities.update?.command ?? null,\n    canUpdate: capabilities.update !== null,\n    checkedAt: input.checkedAt ?? null,\n    message: advisory.message,\n  };\n}\n\nconst fetchNpmLatestVersion = Effect.fn(\"fetchNpmLatestVersion\")(function* (packageName: string) {\n  const client = yield* HttpClient.HttpClient;\n  const request = HttpClientRequest.get(\n    `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,\n  ).pipe(HttpClientRequest.setHeader(\"accept\", \"application/json\"));\n  const response = yield* client.execute(request).pipe(\n    Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),\n    Effect.orElseSucceed(() => Option.none()),\n  );\n  if (Option.isNone(response)) {\n    return null;\n  }\n  const httpResponse = response.value;\n  if (httpResponse.status < 200 || httpResponse.status >= 300) {\n    return null;\n  }\n  const payload = yield* httpResponse.json.pipe(\n    Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),\n    Effect.orElseSucceed(() => null),\n  );\n  return payload ? nonEmptyString(payload.version) : null;\n});\n\nexport const resolveLatestProviderVersion = Effect.fn(\"resolveLatestProviderVersion\")(function* (\n  maintenanceCapabilities: ProviderMaintenanceCapabilities,\n) {\n  const packageName = maintenanceCapabilities.packageName;\n  if (!packageName) {\n    return null;\n  }\n\n  const latestVersionCache = yield* ProviderVersionCache;\n  const cached = latestVersionCache.get(packageName);\n  const now = DateTime.toEpochMillis(yield* DateTime.now);\n  if (cached && cached.expiresAt > now) {\n    return cached.version;\n  }\n\n  const version = yield* fetchNpmLatestVersion(packageName);\n  latestVersionCache.set(packageName, {\n    expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,\n    version,\n  });\n  return version;\n});\n\nexport const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(\n  \"enrichProviderSnapshotWithVersionAdvisory\",\n)(function* (\n  snapshot: ServerProvider,\n  maintenanceCapabilities?: ProviderMaintenanceCapabilities,\n  options?: {\n    readonly enableProviderUpdateChecks: boolean | undefined;\n  },\n) {\n  const capabilities =\n    maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);\n  const shouldResolveLatestVersion =\n    options?.enableProviderUpdateChecks !== false &&\n    snapshot.enabled &&\n    snapshot.installed &&\n    Boolean(snapshot.version);\n  if (!shouldResolveLatestVersion) {\n    return {\n      ...snapshot,\n      versionAdvisory: createProviderVersionAdvisory({\n        driver: snapshot.driver,\n        currentVersion: snapshot.version,\n        checkedAt: snapshot.checkedAt,\n        maintenanceCapabilities: capabilities,\n      }),\n    };\n  }\n\n  const latestVersion = yield* resolveLatestProviderVersion(capabilities);\n  return {\n    ...snapshot,\n    versionAdvisory: createProviderVersionAdvisory({\n      driver: snapshot.driver,\n      currentVersion: snapshot.version,\n      latestVersion,\n      checkedAt: DateTime.formatIso(yield* DateTime.now),\n      maintenanceCapabilities: capabilities,\n    }),\n  };\n});\n","import {\n  defaultInstanceIdForDriver,\n  ProviderDriverKind,\n  ServerProviderUpdateError,\n  type ProviderInstanceId,\n  type ServerProvider,\n  type ServerProviderUpdatedPayload,\n  type ServerProviderUpdateState,\n} from \"@t3tools/contracts\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { ProviderRegistry } from \"./Services/ProviderRegistry.ts\";\nimport { makeProviderMaintenanceCommandCoordinator } from \"./providerMaintenanceCommandCoordinator.ts\";\nimport { enrichProviderSnapshotWithVersionAdvisory } from \"./providerMaintenance.ts\";\nimport type { ProviderMaintenanceCapabilities } from \"./providerMaintenance.ts\";\nimport { collectUint8StreamText } from \"../stream/collectUint8StreamText.ts\";\nconst isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);\n\nconst UPDATE_TIMEOUT_MS = 5 * 60_000;\nconst UPDATE_OUTPUT_MAX_BYTES = 10_000;\n\nexport interface ProviderMaintenanceCommandResult {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly exitCode: number | null;\n  readonly timedOut: boolean;\n  readonly stdoutTruncated: boolean;\n  readonly stderrTruncated: boolean;\n}\n\nexport interface ProviderMaintenanceRunnerShape {\n  readonly updateProvider: (\n    target:\n      | ProviderDriverKind\n      | {\n          readonly provider: ProviderDriverKind;\n          readonly instanceId?: ProviderInstanceId | undefined;\n        },\n  ) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;\n}\n\nexport class ProviderMaintenanceRunner extends Context.Service<\n  ProviderMaintenanceRunner,\n  ProviderMaintenanceRunnerShape\n>()(\"t3/provider/providerMaintenanceRunner\") {}\n\nclass ProviderMaintenanceCommandError extends Data.TaggedError(\"ProviderMaintenanceCommandError\")<{\n  readonly message: string;\n  readonly cause?: unknown;\n}> {}\n\ninterface VerifiedProviderRefresh {\n  readonly providers: ReadonlyArray<ServerProvider>;\n  readonly verifiedProviders: ReadonlyArray<ServerProvider>;\n}\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\nconst runProviderMaintenanceCommandWithSpawner = Effect.fn(\"ProviderMaintenanceRunner.runCommand\")(\n  function* (input: {\n    readonly spawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"];\n    readonly command: string;\n    readonly args: ReadonlyArray<string>;\n  }) {\n    const collectCommandResult = Effect.fn(\"ProviderMaintenanceRunner.collectCommandResult\")(\n      function* () {\n        // Resolve the executable for the host platform before spawning. On\n        // Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`),\n        // which a bare ChildProcess.spawn cannot launch (spawn npm ENOENT);\n        // resolveSpawnCommand finds the real `.cmd` and routes it through the\n        // shell. On Linux/macOS (incl. the WSL backend) this is a no-op.\n        const resolved = yield* resolveSpawnCommand(input.command, input.args);\n        const child = yield* input.spawner\n          .spawn(ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }))\n          .pipe(\n            Effect.mapError(\n              (cause) =>\n                new ProviderMaintenanceCommandError({\n                  message: `Failed to run update command ${input.command}: ${cause.message}`,\n                  cause,\n                }),\n            ),\n          );\n        yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));\n\n        const [stdout, stderr, exitCode] = yield* Effect.all(\n          [\n            collectUint8StreamText({\n              stream: child.stdout,\n              maxBytes: UPDATE_OUTPUT_MAX_BYTES,\n            }),\n            collectUint8StreamText({\n              stream: child.stderr,\n              maxBytes: UPDATE_OUTPUT_MAX_BYTES,\n            }),\n            child.exitCode,\n          ],\n          { concurrency: \"unbounded\" },\n        ).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderMaintenanceCommandError({\n                message: cause instanceof Error ? cause.message : \"Update command failed to run.\",\n                cause,\n              }),\n          ),\n        );\n\n        return {\n          stdout: stdout.text,\n          stderr: stderr.text,\n          exitCode: Number(exitCode),\n          timedOut: false,\n          stdoutTruncated: stdout.truncated,\n          stderrTruncated: stderr.truncated,\n        } satisfies ProviderMaintenanceCommandResult;\n      },\n    );\n\n    return yield* collectCommandResult().pipe(\n      Effect.scoped,\n      Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),\n      Effect.map((result) =>\n        Option.match(result, {\n          onSome: (value) => value,\n          onNone: () =>\n            ({\n              stdout: \"\",\n              stderr: \"\",\n              exitCode: null,\n              timedOut: true,\n              stdoutTruncated: false,\n              stderrTruncated: false,\n            }) satisfies ProviderMaintenanceCommandResult,\n        }),\n      ),\n    );\n  },\n);\n\nfunction trimNullable(value: string): string | null {\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction truncateText(value: string, maxLength: number): string {\n  return value.length <= maxLength ? value : value.slice(0, maxLength);\n}\n\nfunction commandOutput(result: ProviderMaintenanceCommandResult): string | null {\n  const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join(\"\\n\\n\"));\n  if (!output) {\n    return null;\n  }\n  return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);\n}\n\nfunction failureMessage(result: ProviderMaintenanceCommandResult): string {\n  if (result.timedOut) {\n    return \"Update timed out.\";\n  }\n  if (result.exitCode !== null && result.exitCode !== 0) {\n    return `Update command exited with code ${result.exitCode}.`;\n  }\n  return \"Update command failed.\";\n}\n\nfunction isOutdatedProvider(provider: ServerProvider | undefined): boolean {\n  return provider?.versionAdvisory?.status === \"behind_latest\";\n}\n\nfunction makeUpdateState(input: {\n  readonly status: ServerProviderUpdateState[\"status\"];\n  readonly startedAt: string | null;\n  readonly finishedAt: string | null;\n  readonly message: string | null;\n  readonly output?: string | null;\n}): ServerProviderUpdateState {\n  return {\n    status: input.status,\n    startedAt: input.startedAt,\n    finishedAt: input.finishedAt,\n    message: input.message,\n    output: input.output ?? null,\n  };\n}\n\nexport const make = Effect.fn(\"ProviderMaintenanceRunner.make\")(function* () {\n  const providerRegistry = yield* ProviderRegistry;\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const httpClient = yield* HttpClient.HttpClient;\n  const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>\n    runProviderMaintenanceCommandWithSpawner({\n      spawner,\n      command,\n      args,\n    });\n  const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({\n    makeAlreadyRunningError: () =>\n      new ServerProviderUpdateError({\n        provider: ProviderDriverKind.make(\"unknown\"),\n        reason: \"An update is already running for this provider.\",\n      }),\n  });\n\n  const verifyRefreshedProvider = (\n    provider: ProviderDriverKind,\n    maintenanceCapabilities: ProviderMaintenanceCapabilities,\n    instanceId: ProviderInstanceId,\n  ): Effect.Effect<VerifiedProviderRefresh> =>\n    providerRegistry.getProviders.pipe(\n      Effect.map((providers) => {\n        const instanceIds: Array<ProviderInstanceId> = [];\n        for (const candidate of providers) {\n          if (candidate.driver === provider && candidate.instanceId === instanceId) {\n            instanceIds.push(candidate.instanceId);\n          }\n        }\n        return instanceIds;\n      }),\n      Effect.flatMap((instanceIds) =>\n        instanceIds.length === 0\n          ? providerRegistry.refreshInstance(instanceId)\n          : Effect.forEach(\n              instanceIds,\n              (instanceId) => providerRegistry.refreshInstance(instanceId),\n              {\n                concurrency: \"unbounded\",\n                discard: true,\n              },\n            ).pipe(Effect.andThen(providerRegistry.getProviders)),\n      ),\n      Effect.flatMap((providers) => {\n        const refreshedProviders = providers.filter(\n          (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,\n        );\n        if (refreshedProviders.length === 0) {\n          return Effect.succeed<VerifiedProviderRefresh>({\n            providers,\n            verifiedProviders: [],\n          });\n        }\n        return Effect.forEach(\n          refreshedProviders,\n          (refreshedProvider) =>\n            enrichProviderSnapshotWithVersionAdvisory(\n              refreshedProvider,\n              maintenanceCapabilities,\n            ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),\n          {\n            concurrency: \"unbounded\",\n          },\n        ).pipe(\n          Effect.map(\n            (verifiedProviders): VerifiedProviderRefresh => ({\n              providers,\n              verifiedProviders,\n            }),\n          ),\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"Provider post-update version verification failed\", {\n              provider,\n              cause: Cause.pretty(cause),\n            }).pipe(\n              Effect.as<VerifiedProviderRefresh>({\n                providers,\n                verifiedProviders: refreshedProviders,\n              }),\n            ),\n          ),\n        );\n      }),\n    );\n\n  const updateProvider: ProviderMaintenanceRunnerShape[\"updateProvider\"] = Effect.fn(\n    \"ProviderMaintenanceRunner.updateProvider\",\n  )(function* (target) {\n    const provider = typeof target === \"string\" ? target : target.provider;\n    const instanceId =\n      typeof target === \"string\"\n        ? defaultInstanceIdForDriver(provider)\n        : (target.instanceId ?? defaultInstanceIdForDriver(provider));\n    const targetKey = `instance:${instanceId}`;\n    const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(\n      instanceId,\n      provider,\n    );\n    const update = capabilities.update;\n    if (!update) {\n      return yield* new ServerProviderUpdateError({\n        provider,\n        reason: \"This provider does not support one-click updates.\",\n      });\n    }\n\n    const setUpdateState = (state: ServerProviderUpdateState | null) =>\n      providerRegistry.setProviderMaintenanceActionState({\n        instanceId,\n        action: \"update\",\n        state,\n      });\n    const setQueuedState = setUpdateState(\n      makeUpdateState({\n        status: \"queued\",\n        startedAt: null,\n        finishedAt: null,\n        message: \"Waiting for another provider update to finish.\",\n      }),\n    ).pipe(Effect.asVoid);\n\n    const runProviderUpdate = Effect.fn(\"ProviderMaintenanceRunner.runProviderUpdate\")(\n      function* () {\n        const finish = (state: ServerProviderUpdateState) =>\n          setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));\n        const startedAtRef = yield* Ref.make<string | null>(null);\n\n        const runCommandAndVerify = Effect.fn(\"ProviderMaintenanceRunner.runCommandAndVerify\")(\n          function* () {\n            const startedAt = yield* nowIso;\n            yield* Ref.set(startedAtRef, startedAt);\n            yield* setUpdateState(\n              makeUpdateState({\n                status: \"running\",\n                startedAt,\n                finishedAt: null,\n                message: \"Updating provider.\",\n              }),\n            );\n\n            const result = yield* runMaintenanceCommand(update.executable, update.args);\n            const finishedAt = yield* nowIso;\n            if (result.timedOut || result.exitCode !== 0) {\n              return yield* finish(\n                makeUpdateState({\n                  status: \"failed\",\n                  startedAt,\n                  finishedAt,\n                  message: failureMessage(result),\n                  output: commandOutput(result),\n                }),\n              );\n            }\n\n            const { verifiedProviders } = yield* verifyRefreshedProvider(\n              provider,\n              capabilities,\n              instanceId,\n            );\n            const couldNotVerify = verifiedProviders.length === 0;\n            const stillOutdated =\n              couldNotVerify ||\n              verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));\n            return yield* finish(\n              makeUpdateState({\n                status: stillOutdated ? \"unchanged\" : \"succeeded\",\n                startedAt,\n                finishedAt,\n                message: couldNotVerify\n                  ? \"Update command completed, but T3 Code could not verify the provider version.\"\n                  : stillOutdated\n                    ? \"Update command completed, but T3 Code still detects an outdated provider version.\"\n                    : \"Provider updated.\",\n                output: commandOutput(result),\n              }),\n            );\n          },\n        );\n\n        const recordFailedUpdate = Effect.fn(\"ProviderMaintenanceRunner.recordFailedUpdate\")(\n          function* (cause: Cause.Cause<unknown>) {\n            const failure = Cause.squash(cause);\n            const startedAt = yield* Ref.get(startedAtRef);\n            return yield* finish(\n              makeUpdateState({\n                status: \"failed\",\n                startedAt,\n                finishedAt: yield* nowIso,\n                message: failure instanceof Error ? failure.message : \"Update command failed.\",\n                output: null,\n              }),\n            );\n          },\n        );\n\n        return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));\n      },\n    );\n\n    return yield* commandCoordinator\n      .withCommandLock({\n        targetKey,\n        lockKey: update.lockKey,\n        onQueued: setQueuedState,\n        run: runProviderUpdate(),\n      })\n      .pipe(\n        Effect.mapError((error) =>\n          isServerProviderUpdateError(error)\n            ? new ServerProviderUpdateError({\n                provider,\n                reason: error.reason,\n              })\n            : error,\n        ),\n      );\n  });\n\n  return ProviderMaintenanceRunner.of({\n    updateProvider,\n  });\n});\n\nexport const layer = Layer.effect(ProviderMaintenanceRunner, make());\n","import type {\n  OrchestrationEvent,\n  OrchestrationThreadActivity,\n  OrchestrationThreadDetailSnapshot,\n} from \"@t3tools/contracts\";\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : null;\n}\n\nfunction asTrimmedString(value: unknown): string | null {\n  if (typeof value !== \"string\") {\n    return null;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction pushChangedFile(target: string[], seen: Set<string>, value: unknown): void {\n  const normalized = asTrimmedString(value);\n  if (!normalized || seen.has(normalized)) {\n    return;\n  }\n  seen.add(normalized);\n  target.push(normalized);\n}\n\nfunction collectChangedFiles(\n  value: unknown,\n  target: string[],\n  seen: Set<string>,\n  depth: number,\n): void {\n  if (depth > 4 || target.length >= 12) {\n    return;\n  }\n  if (Array.isArray(value)) {\n    for (const entry of value) {\n      collectChangedFiles(entry, target, seen, depth + 1);\n      if (target.length >= 12) {\n        return;\n      }\n    }\n    return;\n  }\n\n  const record = asRecord(value);\n  if (!record) {\n    return;\n  }\n\n  pushChangedFile(target, seen, record.path);\n  pushChangedFile(target, seen, record.filePath);\n  pushChangedFile(target, seen, record.relativePath);\n  pushChangedFile(target, seen, record.filename);\n  pushChangedFile(target, seen, record.newPath);\n  pushChangedFile(target, seen, record.oldPath);\n\n  for (const nestedKey of [\n    \"item\",\n    \"result\",\n    \"input\",\n    \"data\",\n    \"changes\",\n    \"files\",\n    \"edits\",\n    \"patch\",\n    \"patches\",\n    \"operations\",\n  ]) {\n    if (!(nestedKey in record)) {\n      continue;\n    }\n    collectChangedFiles(record[nestedKey], target, seen, depth + 1);\n    if (target.length >= 12) {\n      return;\n    }\n  }\n}\n\nfunction projectCommandData(data: Record<string, unknown>): Record<string, unknown> | undefined {\n  const item = asRecord(data.item);\n  if (!item) {\n    return undefined;\n  }\n\n  const projectedItem: Record<string, unknown> = {};\n  if (\"command\" in item) {\n    projectedItem.command = item.command;\n  }\n\n  const input = asRecord(item.input);\n  if (input && \"command\" in input) {\n    projectedItem.input = { command: input.command };\n  }\n\n  const result = asRecord(item.result);\n  if (result && \"command\" in result) {\n    projectedItem.result = { command: result.command };\n  }\n\n  return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;\n}\n\nfunction summarizeToolTextOutput(value: string): string | null {\n  const lines: string[] = [];\n  for (const rawLine of value.split(/\\r?\\n/u)) {\n    const line = rawLine.replace(/\\s+/g, \" \").trim();\n    if (line.length > 0) {\n      lines.push(line);\n    }\n  }\n\n  const firstLine = lines.find((line) => line !== \"```\");\n  if (firstLine) {\n    return firstLine.length <= 84 ? firstLine : `${firstLine.slice(0, 83).trimEnd()}…`;\n  }\n  if (lines.length > 1) {\n    return `${lines.length.toLocaleString()} lines`;\n  }\n  return null;\n}\n\nfunction projectRawOutput(value: unknown): Record<string, unknown> | undefined {\n  const rawOutput = asRecord(value);\n  if (!rawOutput) {\n    return undefined;\n  }\n\n  if (typeof rawOutput.totalFiles === \"number\" && Number.isFinite(rawOutput.totalFiles)) {\n    return {\n      totalFiles: rawOutput.totalFiles,\n      ...(rawOutput.truncated === true ? { truncated: true } : {}),\n    };\n  }\n\n  const content = asTrimmedString(rawOutput.content);\n  if (content) {\n    const summary = summarizeToolTextOutput(content);\n    return summary ? { content: summary } : undefined;\n  }\n\n  const stdout = asTrimmedString(rawOutput.stdout);\n  if (stdout) {\n    const summary = summarizeToolTextOutput(stdout);\n    return summary ? { content: summary } : undefined;\n  }\n\n  return undefined;\n}\n\n/**\n * Removes activity payload fields that no current client reads while retaining\n * the full payload in persistence and the event store.\n */\nexport function projectActivityPayload(\n  activity: OrchestrationThreadActivity,\n): OrchestrationThreadActivity {\n  const payload = asRecord(activity.payload);\n  const data = asRecord(payload?.data);\n  if (!payload || !data || payload.itemType === \"mcp_tool_call\") {\n    return activity;\n  }\n\n  const projectedData: Record<string, unknown> = {};\n  const item = projectCommandData(data);\n  if (item) {\n    projectedData.item = item;\n  }\n  if (\"command\" in data) {\n    projectedData.command = data.command;\n  }\n\n  const changedFiles: string[] = [];\n  collectChangedFiles(data, changedFiles, new Set<string>(), 0);\n  if (changedFiles.length > 0) {\n    // Both clients discover file names by walking objects with path-like keys.\n    projectedData.files = changedFiles.map((path) => ({ path }));\n  }\n\n  if (\"toolCallId\" in data) {\n    projectedData.toolCallId = data.toolCallId;\n  }\n  if (\"kind\" in data) {\n    projectedData.kind = data.kind;\n  }\n\n  const rawOutput = projectRawOutput(data.rawOutput);\n  if (rawOutput) {\n    projectedData.rawOutput = rawOutput;\n  }\n\n  return {\n    ...activity,\n    payload: {\n      ...payload,\n      data: projectedData,\n    },\n  };\n}\n\n/**\n * Matches the validity rule in the web client's\n * `deriveLatestContextWindowSnapshot`: rows without a finite, non-negative\n * `usedTokens` are skipped during its backward walk, so they must not shadow\n * an earlier resolvable row here.\n */\nfunction isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {\n  if (activity.kind !== \"context-window.updated\") {\n    return false;\n  }\n  const payload = asRecord(activity.payload);\n  const usedTokens = payload?.usedTokens;\n  return typeof usedTokens === \"number\" && Number.isFinite(usedTokens) && usedTokens >= 0;\n}\n\n/**\n * Drops all but the last resolvable context-window activity per turn from a\n * snapshot. Clients only ever read the latest usage value (walking the array\n * backwards), so shipping the full history — often thousands of rows on long\n * threads — buys nothing. Retention is per turn rather than per thread because\n * a live `thread.reverted` makes the client discard whole turns; keeping each\n * turn's latest row means the meter can still resolve a value from the turns\n * that survive. Malformed rows pass through untouched rather than shadowing a\n * valid earlier row. Live `thread.activity-appended` events are untouched:\n * newer updates still stream through and supersede the retained rows on the\n * client.\n */\nfunction dropStaleContextWindowActivities(\n  activities: ReadonlyArray<OrchestrationThreadActivity>,\n): ReadonlyArray<OrchestrationThreadActivity> {\n  const latestIndexByTurn = new Map<string | null, number>();\n  for (let index = 0; index < activities.length; index += 1) {\n    if (isResolvableContextWindowActivity(activities[index]!)) {\n      latestIndexByTurn.set(activities[index]!.turnId, index);\n    }\n  }\n  if (latestIndexByTurn.size === 0) {\n    return activities;\n  }\n  return activities.filter(\n    (activity, index) =>\n      !isResolvableContextWindowActivity(activity) ||\n      latestIndexByTurn.get(activity.turnId) === index,\n  );\n}\n\nexport function projectThreadDetailSnapshot(\n  snapshot: OrchestrationThreadDetailSnapshot,\n): OrchestrationThreadDetailSnapshot {\n  return {\n    ...snapshot,\n    thread: {\n      ...snapshot.thread,\n      activities: dropStaleContextWindowActivities(snapshot.thread.activities).map(\n        projectActivityPayload,\n      ),\n    },\n  };\n}\n\nexport function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {\n  if (event.type !== \"thread.activity-appended\") {\n    return event;\n  }\n  return {\n    ...event,\n    payload: {\n      ...event.payload,\n      activity: projectActivityPayload(event.payload.activity),\n    },\n  };\n}\n","import * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport {\n  type ClientOrchestrationCommand,\n  type IsoDateTime,\n  type OrchestrationCommand,\n  OrchestrationDispatchCommandError,\n  PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,\n} from \"@t3tools/contracts\";\n\nimport { createAttachmentId, resolveAttachmentPath } from \"../attachmentStore.ts\";\nimport { ServerConfig } from \"../config.ts\";\nimport { parseBase64DataUrl } from \"../imageMime.ts\";\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\n\nexport const canonicalizeClientCommandTimestamps = (\n  command: ClientOrchestrationCommand,\n  receivedAt: IsoDateTime,\n): ClientOrchestrationCommand => {\n  const canonicalCommand =\n    \"createdAt\" in command\n      ? {\n          ...command,\n          createdAt: receivedAt,\n        }\n      : command;\n\n  if (canonicalCommand.type !== \"thread.turn.start\" || !canonicalCommand.bootstrap?.createThread) {\n    return canonicalCommand;\n  }\n\n  return {\n    ...canonicalCommand,\n    bootstrap: {\n      ...canonicalCommand.bootstrap,\n      createThread: {\n        ...canonicalCommand.bootstrap.createThread,\n        createdAt: receivedAt,\n      },\n    },\n  };\n};\n\nexport const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>\n  Effect.gen(function* () {\n    const receivedAt = DateTime.formatIso(yield* DateTime.now);\n    const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const serverConfig = yield* ServerConfig;\n    const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n\n    const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>\n      workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new OrchestrationDispatchCommandError({\n              message: cause.message,\n            }),\n        ),\n      );\n\n    const normalizeProjectWorkspaceRootForCreate = (\n      workspaceRoot: string,\n      createIfMissing: boolean | undefined,\n    ) =>\n      workspacePaths\n        .normalizeWorkspaceRoot(workspaceRoot, {\n          createIfMissing: createIfMissing === true,\n        })\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new OrchestrationDispatchCommandError({\n                message: cause.message,\n              }),\n          ),\n        );\n\n    if (canonicalCommand.type === \"project.create\") {\n      return {\n        ...canonicalCommand,\n        workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(\n          canonicalCommand.workspaceRoot,\n          canonicalCommand.createWorkspaceRootIfMissing,\n        ),\n        createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,\n      } satisfies OrchestrationCommand;\n    }\n\n    if (\n      canonicalCommand.type === \"project.meta.update\" &&\n      canonicalCommand.workspaceRoot !== undefined\n    ) {\n      return {\n        ...canonicalCommand,\n        workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),\n      } satisfies OrchestrationCommand;\n    }\n\n    if (canonicalCommand.type !== \"thread.turn.start\") {\n      return canonicalCommand as OrchestrationCommand;\n    }\n\n    const normalizedAttachments = yield* Effect.forEach(\n      canonicalCommand.message.attachments,\n      (attachment) =>\n        Effect.gen(function* () {\n          const parsed = parseBase64DataUrl(attachment.dataUrl);\n          if (!parsed || !parsed.mimeType.startsWith(\"image/\")) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: `Invalid image attachment payload for '${attachment.name}'.`,\n            });\n          }\n\n          const bytes = Buffer.from(parsed.base64, \"base64\");\n          if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: `Image attachment '${attachment.name}' is empty or too large.`,\n            });\n          }\n\n          const attachmentId = createAttachmentId(canonicalCommand.threadId);\n          if (!attachmentId) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: \"Failed to create a safe attachment id.\",\n            });\n          }\n\n          const persistedAttachment = {\n            type: \"image\" as const,\n            id: attachmentId,\n            name: attachment.name,\n            mimeType: parsed.mimeType.toLowerCase(),\n            sizeBytes: bytes.byteLength,\n          };\n\n          const attachmentPath = resolveAttachmentPath({\n            attachmentsDir: serverConfig.attachmentsDir,\n            attachment: persistedAttachment,\n          });\n          if (!attachmentPath) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: `Failed to resolve persisted path for '${attachment.name}'.`,\n            });\n          }\n\n          yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(\n            Effect.mapError(\n              () =>\n                new OrchestrationDispatchCommandError({\n                  message: `Failed to create attachment directory for '${attachment.name}'.`,\n                }),\n            ),\n          );\n          yield* fileSystem.writeFile(attachmentPath, bytes).pipe(\n            Effect.mapError(\n              () =>\n                new OrchestrationDispatchCommandError({\n                  message: `Failed to persist attachment '${attachment.name}'.`,\n                }),\n            ),\n          );\n\n          return persistedAttachment;\n        }),\n      { concurrency: 1 },\n    );\n\n    return {\n      ...canonicalCommand,\n      message: {\n        ...canonicalCommand.message,\n        attachments: normalizedAttachments,\n      },\n    } satisfies OrchestrationCommand;\n  });\n","/**\n * ProviderRuntimeIngestionService - Provider runtime ingestion service interface.\n *\n * Owns background workers that consume provider runtime streams and emit\n * orchestration commands/events.\n *\n * @module ProviderRuntimeIngestionService\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\nimport { ThreadId } from \"@t3tools/contracts\";\n\nexport class ProviderRuntimeReconciliationError extends Schema.TaggedErrorClass<ProviderRuntimeReconciliationError>()(\n  \"ProviderRuntimeReconciliationError\",\n  {\n    threadId: ThreadId,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Failed to reconcile provider thread '${this.threadId}': ${this.detail}`;\n  }\n}\n\n/**\n * ProviderRuntimeIngestionShape - Service API for runtime ingestion lifecycle.\n */\nexport interface ProviderRuntimeIngestionShape {\n  readonly reconcileThread: (\n    threadId: ThreadId,\n    options?: { readonly requireWritable?: boolean },\n  ) => Effect.Effect<void, ProviderRuntimeReconciliationError>;\n\n  /**\n   * Start ingesting provider runtime events into orchestration commands.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   *\n   * Uses an internal queue and continues after non-interrupt failures by\n   * logging warnings.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * ProviderRuntimeIngestionService - Service tag for runtime ingestion workers.\n */\nexport class ProviderRuntimeIngestionService extends Context.Service<\n  ProviderRuntimeIngestionService,\n  ProviderRuntimeIngestionShape\n>()(\"t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService\") {}\n","import { WS_METHODS } from \"@t3tools/contracts\";\nimport * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Metric from \"effect/Metric\";\nimport * as References from \"effect/References\";\nimport * as Stream from \"effect/Stream\";\n\nimport { outcomeFromExit } from \"./Attributes.ts\";\nimport { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from \"./Metrics.ts\";\n\nconst RPC_SPAN_PREFIX = \"ws.rpc\";\nconst DEFAULT_RPC_SPAN_ATTRIBUTES = {\n  \"rpc.transport\": \"websocket\",\n  \"rpc.system\": \"effect-rpc\",\n} as const;\nconst RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([\n  WS_METHODS.serverGetTraceDiagnostics,\n  WS_METHODS.serverGetProcessDiagnostics,\n  WS_METHODS.serverGetProcessResourceHistory,\n  WS_METHODS.serverSignalProcess,\n]);\n\nfunction shouldTraceRpc(method: string): boolean {\n  return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);\n}\n\nconst rpcSpanAttributes = (\n  method: string,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Record<string, unknown> => ({\n  ...DEFAULT_RPC_SPAN_ATTRIBUTES,\n  \"rpc.method\": method,\n  ...traceAttributes,\n});\n\nconst withRpcEffectTracing = <A, E, R>(\n  method: string,\n  effect: Effect.Effect<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Effect.Effect<A, E, R> =>\n  shouldTraceRpc(method)\n    ? effect.pipe(\n        Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {\n          attributes: rpcSpanAttributes(method, traceAttributes),\n        }),\n      )\n    : effect.pipe(Effect.provideService(References.TracerEnabled, false));\n\nconst withRpcStreamTracing = <A, E, R>(\n  method: string,\n  stream: Stream.Stream<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Stream.Stream<A, E, R> =>\n  shouldTraceRpc(method)\n    ? stream.pipe(\n        Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {\n          attributes: rpcSpanAttributes(method, traceAttributes),\n        }),\n      )\n    : stream.pipe(Stream.provideService(References.TracerEnabled, false));\n\nconst recordRpcStreamMetrics = <E>(\n  method: string,\n  startedAt: bigint,\n  exit: Exit.Exit<unknown, E>,\n): Effect.Effect<void, never, never> =>\n  Effect.gen(function* () {\n    const endedAt = yield* Clock.currentTimeNanos;\n    const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;\n\n    yield* Metric.update(\n      Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),\n      Duration.nanos(elapsedNanos),\n    );\n    yield* Metric.update(\n      Metric.withAttributes(\n        rpcRequestsTotal,\n        metricAttributes({\n          method,\n          outcome: outcomeFromExit(exit),\n        }),\n      ),\n      1,\n    );\n  });\n\nexport const observeRpcEffect = <A, E, R>(\n  method: string,\n  effect: Effect.Effect<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Effect.Effect<A, E, R> => {\n  const instrumented = effect.pipe(\n    withMetrics({\n      counter: rpcRequestsTotal,\n      timer: rpcRequestDuration,\n      attributes: {\n        method,\n      },\n    }),\n  );\n\n  return withRpcEffectTracing(method, instrumented, traceAttributes);\n};\n\nexport const observeRpcStream = <A, E, R>(\n  method: string,\n  stream: Stream.Stream<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Stream.Stream<A, E, R> => {\n  const instrumented = Stream.unwrap(\n    Effect.gen(function* () {\n      const startedAt = yield* Clock.currentTimeNanos;\n      return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));\n    }),\n  );\n\n  return withRpcStreamTracing(method, instrumented, traceAttributes);\n};\n\nexport const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(\n  method: string,\n  effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {\n  const instrumented = Stream.unwrap(\n    Effect.gen(function* () {\n      const startedAt = yield* Clock.currentTimeNanos;\n      const exit = yield* Effect.exit(effect);\n\n      if (Exit.isFailure(exit)) {\n        yield* recordRpcStreamMetrics(method, startedAt, exit);\n        return yield* Effect.failCause(exit.cause);\n      }\n\n      return exit.value.pipe(\n        Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),\n      );\n    }),\n  );\n\n  return withRpcStreamTracing(method, instrumented, traceAttributes);\n};\n","/**\n * ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.\n *\n * Maps a `ProviderInstanceId` (the new per-instance routing key) or a\n * `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete\n * adapter service (Codex, Claude, etc). It does not own session lifecycle\n * or routing rules; `ProviderService` uses this registry together with\n * `ProviderSessionDirectory`.\n *\n * During the driver/instance migration this tag exposes both flavours:\n *\n *   - `getByInstance` / `listInstances` — new per-instance routing. Callers\n *     that already know an `instanceId` (threads, sessions, events)\n *     should prefer these.\n *     (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D\n *     behaviour. New code should not grow additional callers of the kind-keyed\n *     methods; they exist so the settings UI, WS refresh RPC, and a handful\n *     of legacy persisted rows can still be routed during the rollout.\n *\n * @module ProviderAdapterRegistry\n */\nimport type { ProviderDriverKind, ProviderInstanceId } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { ProviderAdapterError, ProviderUnsupportedError } from \"../Errors.ts\";\nimport type { ProviderAdapterShape } from \"./ProviderAdapter.ts\";\nimport type { ProviderContinuationIdentity } from \"../ProviderDriver.ts\";\n\nexport interface ProviderInstanceRoutingInfo {\n  readonly instanceId: ProviderInstanceId;\n  readonly driverKind: ProviderDriverKind;\n  readonly displayName: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly enabled: boolean;\n  readonly continuationIdentity: ProviderContinuationIdentity;\n}\n\n/**\n * ProviderAdapterRegistryShape - Service API for adapter lookup.\n */\nexport interface ProviderAdapterRegistryShape {\n  /**\n   * Resolve the adapter for a specific instance id. Returns\n   * `ProviderUnsupportedError` if no such instance is currently registered\n   * (which covers \"never configured\" *and* \"configured but the driver is\n   * unavailable in this build\" — both surface the same failure to callers\n   * that expect a working adapter).\n   */\n  readonly getByInstance: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;\n\n  readonly getInstanceInfo: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;\n\n  /**\n   * List all live instance ids. Excludes unavailable/shadow instances —\n   * callers of this method want something they can pass to `getByInstance`.\n   */\n  readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;\n\n  /**\n   * Legacy: list provider kinds whose default instance is currently\n   * registered.\n   *\n   * @deprecated Prefer `listInstances`. Retained for migration-era call\n   * sites that iterate providers to build UI/metrics.\n   */\n  readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;\n\n  /**\n   * Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`.\n   * Emits one `void` tick whenever the set of live instances changes\n   * (instance added, removed, or rebuilt after a settings edit). Consumers\n   * that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s\n   * runtime event bus — re-pull `listInstances` on each tick and fork new\n   * subscriptions for instances they haven't seen yet.\n   */\n  readonly streamChanges: Stream.Stream<void>;\n\n  /**\n   * Acquire a change subscription synchronously in the caller's current fiber.\n   * Consumers that must avoid missing a publish between initial reconciliation\n   * and watcher startup should use this, then fork `Stream.fromSubscription`.\n   */\n  readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;\n}\n\n/**\n * ProviderAdapterRegistry - Service tag for provider adapter lookup.\n */\nexport class ProviderAdapterRegistry extends Context.Service<\n  ProviderAdapterRegistry,\n  ProviderAdapterRegistryShape\n>()(\"t3/provider/Services/ProviderAdapterRegistry\") {}\n","import type {\n  ProviderInstanceId,\n  ProviderDriverKind,\n  ProviderSessionRuntimeStatus,\n  RuntimeMode,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type {\n  ProviderSessionDirectoryPersistenceError,\n  ProviderValidationError,\n} from \"../Errors.ts\";\n\nexport interface ProviderRuntimeBinding {\n  readonly threadId: ThreadId;\n  readonly provider: ProviderDriverKind;\n  /**\n   * Routing key for the configured provider instance that owns this\n   * session. The persistence layer promotes legacy null rows before\n   * exposing bindings; runtime callers must not infer this from `provider`.\n   */\n  readonly providerInstanceId?: ProviderInstanceId;\n  readonly adapterKey?: string;\n  readonly status?: ProviderSessionRuntimeStatus;\n  readonly resumeCursor?: unknown | null;\n  readonly runtimePayload?: unknown | null;\n  readonly runtimeMode?: RuntimeMode;\n}\n\nexport interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {\n  readonly lastSeenAt: string;\n}\n\nexport type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;\n\nexport type ProviderSessionDirectoryWriteError =\n  | ProviderValidationError\n  | ProviderSessionDirectoryPersistenceError;\n\nexport interface ProviderSessionDirectoryShape {\n  readonly upsert: (\n    binding: ProviderRuntimeBinding,\n  ) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;\n\n  readonly getProvider: (\n    threadId: ThreadId,\n  ) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;\n\n  readonly getBinding: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;\n\n  readonly listThreadIds: () => Effect.Effect<\n    ReadonlyArray<ThreadId>,\n    ProviderSessionDirectoryPersistenceError\n  >;\n\n  readonly listBindings: () => Effect.Effect<\n    ReadonlyArray<ProviderRuntimeBindingWithMetadata>,\n    ProviderSessionDirectoryPersistenceError\n  >;\n}\n\nexport class ProviderSessionDirectory extends Context.Service<\n  ProviderSessionDirectory,\n  ProviderSessionDirectoryShape\n>()(\"t3/provider/Services/ProviderSessionDirectory\") {}\n","/**\n * ProviderService - Service interface for provider sessions, turns, and checkpoints.\n *\n * Acts as the cross-provider facade used by transports (WebSocket/RPC). It\n * resolves provider adapters through `ProviderAdapterRegistry`, routes\n * session-scoped calls via `ProviderSessionDirectory`, and exposes one unified\n * provider event stream to callers.\n *\n * Uses Effect `Context.Service` for dependency injection and returns typed\n * domain errors for validation, session, codex, and checkpoint workflows.\n *\n * @module ProviderService\n */\nimport type {\n  ProviderInterruptTurnInput,\n  ProviderInstanceId,\n  ProviderRespondToRequestInput,\n  ProviderRespondToUserInputInput,\n  ProviderRuntimeEvent,\n  ProviderSendTurnInput,\n  ProviderSession,\n  ProviderSessionStartInput,\n  ProviderStopSessionInput,\n  ThreadId,\n  ProviderTurnStartResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { ProviderServiceError } from \"../Errors.ts\";\nimport type {\n  ProviderAdapterCapabilities,\n  ProviderThreadSnapshot,\n} from \"./ProviderAdapter.ts\";\nimport type { ProviderInstanceRoutingInfo } from \"./ProviderAdapterRegistry.ts\";\n\n/**\n * ProviderServiceShape - Service API for provider session and turn orchestration.\n */\nexport interface ProviderServiceShape {\n  /**\n   * Start a provider session.\n   */\n  readonly startSession: (\n    threadId: ThreadId,\n    input: ProviderSessionStartInput,\n  ) => Effect.Effect<ProviderSession, ProviderServiceError>;\n\n  /**\n   * Send a provider turn.\n   */\n  readonly sendTurn: (\n    input: ProviderSendTurnInput,\n  ) => Effect.Effect<ProviderTurnStartResult, ProviderServiceError>;\n\n  /**\n   * Interrupt a running provider turn.\n   */\n  readonly interruptTurn: (\n    input: ProviderInterruptTurnInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Respond to a provider approval request.\n   */\n  readonly respondToRequest: (\n    input: ProviderRespondToRequestInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Respond to a provider structured user-input request.\n   */\n  readonly respondToUserInput: (\n    input: ProviderRespondToUserInputInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Stop a provider session.\n   */\n  readonly stopSession: (\n    input: ProviderStopSessionInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * List active provider sessions.\n   *\n   * Aggregates runtime session lists from all registered adapters.\n   */\n  readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;\n\n  /**\n   * Read capabilities for the adapter bound to a configured provider instance.\n   */\n  readonly getCapabilities: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;\n\n  readonly getInstanceInfo: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;\n\n  /** Read a bound provider thread without requiring an active writer session. */\n  readonly readThread: (\n    threadId: ThreadId,\n  ) => Effect.Effect<ProviderThreadSnapshot, ProviderServiceError>;\n\n  /** Ensure the daemon owns a writable session for an already-bound thread. */\n  readonly ensureSession: (threadId: ThreadId) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Roll back provider conversation state by a number of turns.\n   */\n  readonly rollbackConversation: (input: {\n    readonly threadId: ThreadId;\n    readonly numTurns: number;\n  }) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Canonical provider runtime event stream.\n   *\n   * Fan-out is owned by ProviderService (not by a standalone event-bus service).\n   */\n  readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;\n}\n\n/**\n * ProviderService - Service tag for provider orchestration.\n */\nexport class ProviderService extends Context.Service<ProviderService, ProviderServiceShape>()(\n  \"t3/provider/Services/ProviderService\",\n) {}\n","import type { PortProxyPort } from \"@t3tools/contracts\";\n\nconst ports = new Set<PortProxyPort>();\nconst methods = new Set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\"]);\nconst requestHeaders = new Set([\n  \"authorization\",\n  \"cookie\",\n  \"host\",\n  \"connection\",\n  \"upgrade\",\n  \"proxy-authorization\",\n  \"proxy-connection\",\n]);\nconst responseHeaders = new Set([\n  \"set-cookie\",\n  \"connection\",\n  \"upgrade\",\n  \"proxy-authenticate\",\n  \"transfer-encoding\",\n]);\n\nexport function listAuthorizedPorts(): PortProxyPort[] {\n  return [...ports].sort((a, b) => a - b);\n}\n\nexport function authorizePort(port: PortProxyPort): PortProxyPort[] {\n  ports.add(port);\n  return listAuthorizedPorts();\n}\n\nexport function revokePort(port: PortProxyPort): PortProxyPort[] {\n  ports.delete(port);\n  return listAuthorizedPorts();\n}\n\nexport function isPortAuthorized(port: number): boolean {\n  return ports.has(port as PortProxyPort);\n}\n\nexport function authorizedPortBaseUrl(port: number): string | null {\n  return isPortAuthorized(port) ? `http://127.0.0.1:${port}` : null;\n}\n\nexport function isPortProxyMethodAllowed(method: string): boolean {\n  return methods.has(method.toUpperCase());\n}\n\nexport function isPortProxyRequestHeaderAllowed(header: string): boolean {\n  return !requestHeaders.has(header.toLowerCase());\n}\n\nexport function isPortProxyResponseHeaderAllowed(header: string): boolean {\n  return !responseHeaders.has(header.toLowerCase());\n}\n\nexport function clearAuthorizedPorts(): void {\n  ports.clear();\n}\n","export type RankedSearchResult<T> = {\n  item: T;\n  score: number;\n  tieBreaker: string;\n};\n\nexport function normalizeSearchQuery(\n  input: string,\n  options?: {\n    trimLeadingPattern?: RegExp;\n  },\n): string {\n  const trimmed = input.trim();\n  if (!trimmed) {\n    return \"\";\n  }\n  return options?.trimLeadingPattern\n    ? trimmed.replace(options.trimLeadingPattern, \"\").toLowerCase()\n    : trimmed.toLowerCase();\n}\n\nexport function scoreSubsequenceMatch(value: string, query: string): number | null {\n  if (!query) return 0;\n\n  let queryIndex = 0;\n  let firstMatchIndex = -1;\n  let previousMatchIndex = -1;\n  let gapPenalty = 0;\n\n  for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {\n    if (value[valueIndex] !== query[queryIndex]) {\n      continue;\n    }\n\n    if (firstMatchIndex === -1) {\n      firstMatchIndex = valueIndex;\n    }\n    if (previousMatchIndex !== -1) {\n      gapPenalty += valueIndex - previousMatchIndex - 1;\n    }\n\n    previousMatchIndex = valueIndex;\n    queryIndex += 1;\n    if (queryIndex === query.length) {\n      const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;\n      const lengthPenalty = Math.min(64, value.length - query.length);\n      return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;\n    }\n  }\n\n  return null;\n}\n\nfunction lengthPenalty(value: string, query: string): number {\n  return Math.min(64, Math.max(0, value.length - query.length));\n}\n\nfunction findBoundaryMatchIndex(\n  value: string,\n  query: string,\n  boundaryMarkers: readonly string[],\n): number | null {\n  let bestIndex: number | null = null;\n\n  for (const marker of boundaryMarkers) {\n    const index = value.indexOf(`${marker}${query}`);\n    if (index === -1) {\n      continue;\n    }\n\n    const matchIndex = index + marker.length;\n    if (bestIndex === null || matchIndex < bestIndex) {\n      bestIndex = matchIndex;\n    }\n  }\n\n  return bestIndex;\n}\n\n/**\n * Scores how well `value` matches `query` using tiered match strategies.\n *\n * **Expects pre-normalized inputs**: both `value` and `query` must already be\n * trimmed and lowercased (e.g. via {@link normalizeSearchQuery}).\n */\nexport function scoreQueryMatch(input: {\n  value: string;\n  query: string;\n  exactBase: number;\n  prefixBase?: number;\n  boundaryBase?: number;\n  includesBase?: number;\n  fuzzyBase?: number;\n  boundaryMarkers?: readonly string[];\n}): number | null {\n  const { value, query } = input;\n\n  if (!value || !query) {\n    return null;\n  }\n\n  if (value === query) {\n    return input.exactBase;\n  }\n\n  if (input.prefixBase !== undefined && value.startsWith(query)) {\n    return input.prefixBase + lengthPenalty(value, query);\n  }\n\n  if (input.boundaryBase !== undefined) {\n    const boundaryIndex = findBoundaryMatchIndex(\n      value,\n      query,\n      input.boundaryMarkers ?? [\" \", \"-\", \"_\", \"/\"],\n    );\n    if (boundaryIndex !== null) {\n      return input.boundaryBase + boundaryIndex * 2 + lengthPenalty(value, query);\n    }\n  }\n\n  if (input.includesBase !== undefined) {\n    const includesIndex = value.indexOf(query);\n    if (includesIndex !== -1) {\n      return input.includesBase + includesIndex * 2 + lengthPenalty(value, query);\n    }\n  }\n\n  if (input.fuzzyBase !== undefined) {\n    const fuzzyScore = scoreSubsequenceMatch(value, query);\n    if (fuzzyScore !== null) {\n      return input.fuzzyBase + fuzzyScore;\n    }\n  }\n\n  return null;\n}\n\nexport function compareRankedSearchResults<T>(\n  left: RankedSearchResult<T>,\n  right: RankedSearchResult<T>,\n): number {\n  const scoreDelta = left.score - right.score;\n  if (scoreDelta !== 0) return scoreDelta;\n  return left.tieBreaker.localeCompare(right.tieBreaker);\n}\n\nfunction findInsertionIndex<T>(\n  rankedEntries: RankedSearchResult<T>[],\n  candidate: RankedSearchResult<T>,\n): number {\n  let low = 0;\n  let high = rankedEntries.length;\n\n  while (low < high) {\n    const middle = low + Math.floor((high - low) / 2);\n    const current = rankedEntries[middle];\n    if (!current) {\n      break;\n    }\n\n    if (compareRankedSearchResults(candidate, current) < 0) {\n      high = middle;\n    } else {\n      low = middle + 1;\n    }\n  }\n\n  return low;\n}\n\nexport function insertRankedSearchResult<T>(\n  rankedEntries: RankedSearchResult<T>[],\n  candidate: RankedSearchResult<T>,\n  limit: number,\n): void {\n  if (limit <= 0) {\n    return;\n  }\n\n  const insertionIndex = findInsertionIndex(rankedEntries, candidate);\n  if (rankedEntries.length < limit) {\n    rankedEntries.splice(insertionIndex, 0, candidate);\n    return;\n  }\n\n  if (insertionIndex >= limit) {\n    return;\n  }\n\n  rankedEntries.splice(insertionIndex, 0, candidate);\n  rankedEntries.pop();\n}\n","import {\n  type DirItem,\n  type DirSearchResult,\n  type FileItem,\n  FileFinder,\n  type GrepCursor,\n  type MixedItem,\n  type MixedSearchResult,\n  type Result,\n  type SearchResult,\n} from \"@ff-labs/fff-node\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as LayerMap from \"effect/LayerMap\";\nimport * as Schema from \"effect/Schema\";\n\nimport type {\n  ProjectEntry,\n  ProjectEntryKind,\n  ProjectListEntriesResult,\n  ProjectSearchContentsInput,\n  ProjectSearchContentsResult,\n  ProjectSearchEntriesResult,\n} from \"@t3tools/contracts\";\n\nconst WORKSPACE_INDEX_MAX_ENTRIES = 25_000;\nconst WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;\nconst WORKSPACE_INDEX_SCAN_TIMEOUT = \"15 seconds\";\nconst WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;\nconst WORKSPACE_INDEX_IDLE_TTL = \"15 minutes\";\nconst CONTENT_SEARCH_TIME_BUDGET_MS = 250;\nconst CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;\n\nexport class WorkspaceSearchIndexCreateFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexCreateFailed>()(\n  \"WorkspaceSearchIndexCreateFailed\",\n  {\n    cwd: Schema.String,\n    reason: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Failed to create the workspace search index for '${this.cwd}'.`;\n  }\n}\n\nexport class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedErrorClass<WorkspaceSearchIndexScanTimedOut>()(\n  \"WorkspaceSearchIndexScanTimedOut\",\n  {\n    cwd: Schema.String,\n    timeout: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;\n  }\n}\n\nexport class WorkspaceSearchIndexSearchFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexSearchFailed>()(\n  \"WorkspaceSearchIndexSearchFailed\",\n  {\n    cwd: Schema.String,\n    queryLength: Schema.Number,\n    pageSize: Schema.Number,\n    reason: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Workspace search failed for '${this.cwd}'.`;\n  }\n}\n\nexport class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexRefreshFailed>()(\n  \"WorkspaceSearchIndexRefreshFailed\",\n  {\n    cwd: Schema.String,\n    reason: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Failed to refresh the workspace search index for '${this.cwd}'.`;\n  }\n}\n\nexport class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(\n  \"WorkspaceSearchIndexDestroyFailed\",\n  {\n    cwd: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to destroy the workspace search index for '${this.cwd}'.`;\n  }\n}\n\nexport type WorkspaceSearchIndexError =\n  | WorkspaceSearchIndexCreateFailed\n  | WorkspaceSearchIndexScanTimedOut\n  | WorkspaceSearchIndexSearchFailed\n  | WorkspaceSearchIndexRefreshFailed;\n\nexport class WorkspaceSearchIndex extends Context.Service<\n  WorkspaceSearchIndex,\n  {\n    readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;\n    readonly search: (\n      query: string,\n      limit: number,\n      kind?: ProjectEntryKind,\n    ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;\n    readonly searchContents: (\n      input: Omit<ProjectSearchContentsInput, \"cwd\">,\n    ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;\n    readonly refresh: () => Effect.Effect<\n      void,\n      WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut\n    >;\n  }\n>()(\"t3/workspace/WorkspaceSearchIndex\") {}\n\nfunction toPosixPath(input: string): string {\n  return input.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction trimDirectorySeparator(input: string): string {\n  return input.endsWith(\"/\") ? input.slice(0, -1) : input;\n}\n\nfunction parentPathOf(input: string): string | undefined {\n  const separatorIndex = input.lastIndexOf(\"/\");\n  return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);\n}\n\nfunction toProjectEntry(item: MixedItem): ProjectEntry | null {\n  const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));\n  if (!normalizedPath) {\n    return null;\n  }\n\n  return {\n    path: normalizedPath,\n    kind: item.type,\n  };\n}\n\nfunction toFileEntry(item: FileItem): ProjectEntry | null {\n  const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));\n  return normalizedPath ? { path: normalizedPath, kind: \"file\" } : null;\n}\n\nfunction toDirectoryEntry(item: DirItem): ProjectEntry | null {\n  const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));\n  return normalizedPath ? { path: normalizedPath, kind: \"directory\" } : null;\n}\n\nfunction mapFileSearchResult(result: SearchResult, limit: number): ProjectSearchEntriesResult {\n  return {\n    entries: result.items\n      .flatMap((item) => {\n        const entry = toFileEntry(item);\n        return entry ? [entry] : [];\n      })\n      .slice(0, limit),\n    truncated: result.totalMatched > limit,\n  };\n}\n\nfunction mapDirectorySearchResult(\n  result: DirSearchResult,\n  limit: number,\n): ProjectSearchEntriesResult {\n  const entries = result.items.flatMap((item) => {\n    const entry = toDirectoryEntry(item);\n    return entry ? [entry] : [];\n  });\n  const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;\n  return {\n    entries: entries.slice(0, limit),\n    truncated: result.totalMatched - rootDirectoryCount > limit,\n  };\n}\n\nfunction mapMixedSearchResult(\n  result: MixedSearchResult,\n  limit: number,\n): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {\n  const entries: ProjectEntry[] = [];\n  for (const item of result.items) {\n    const entry = toProjectEntry(item);\n    if (entry) {\n      entries.push(entry);\n    }\n    if (entries.length >= limit) {\n      break;\n    }\n  }\n\n  const rootDirectoryCount = result.items.some(\n    (item) => item.type === \"directory\" && item.item.relativePath.length === 0,\n  )\n    ? 1\n    : 0;\n  return {\n    entries,\n    truncated: result.totalMatched - rootDirectoryCount > limit,\n  };\n}\n\nconst WORD_CHARACTER = /[\\p{Letter}\\p{Mark}\\p{Number}_]/u;\n\nfunction codePointAt(line: string, index: number): string | undefined {\n  const codePoint = line.codePointAt(index);\n  return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);\n}\n\nfunction codePointBefore(line: string, index: number): string | undefined {\n  if (index <= 0) return undefined;\n  const previousCodeUnit = line.charCodeAt(index - 1);\n  const previousIndex =\n    previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;\n  return codePointAt(line, previousIndex);\n}\n\nfunction buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, \"cwd\">): {\n  readonly searchQuery: string;\n  readonly regexMode: boolean;\n} {\n  if (input.caseSensitive) {\n    return { searchQuery: input.query, regexMode: input.useRegex };\n  }\n  // Plain mode relies on smart case: an all-lowercase needle matches\n  // case-insensitively. Regex mode needs an explicit inline flag instead.\n  return input.useRegex\n    ? { searchQuery: `(?i)${input.query}`, regexMode: true }\n    : { searchQuery: input.query.toLowerCase(), regexMode: false };\n}\n\nfunction mapContentMatchRanges(\n  line: string,\n  byteRanges: ReadonlyArray<readonly [number, number]>,\n): Array<{ readonly start: number; readonly end: number }> {\n  const lineBytes = Buffer.from(line);\n  const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;\n  return byteRanges.map(([startByte, endByte]) => ({\n    start: toStringIndex(startByte),\n    end: toStringIndex(endByte),\n  }));\n}\n\n/**\n * Whole-word filtering happens after the grep rather than by wrapping the\n * pattern in boundary regex: consuming boundaries such as `(?:^|\\W)` swallow\n * the separator between adjacent matches and widen the reported ranges, and\n * `\\b` cannot match punctuation-edged queries at all. Matching VS Code, a\n * match edge is a word boundary when it touches the line edge, the\n * neighbouring character is not a word character, or the match's own edge\n * character is not a word character.\n */\nfunction isWholeWordRange(\n  line: string,\n  range: { readonly start: number; readonly end: number },\n): boolean {\n  if (range.end <= range.start) return false;\n  const isWord = (character: string | undefined) =>\n    character !== undefined && WORD_CHARACTER.test(character);\n  const leftIsBoundary =\n    range.start === 0 ||\n    !isWord(codePointBefore(line, range.start)) ||\n    !isWord(codePointAt(line, range.start));\n  const rightIsBoundary =\n    range.end >= line.length ||\n    !isWord(codePointAt(line, range.end)) ||\n    !isWord(codePointBefore(line, range.end));\n  return leftIsBoundary && rightIsBoundary;\n}\n\nfunction withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {\n  const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));\n  for (const entry of entries) {\n    let parentPath = parentPathOf(entry.path);\n    while (parentPath) {\n      if (!entryByPath.has(parentPath)) {\n        entryByPath.set(parentPath, { path: parentPath, kind: \"directory\" });\n      }\n      parentPath = parentPathOf(parentPath);\n    }\n  }\n  return [...entryByPath.values()];\n}\n\nconst createFinder = Effect.fn(\"WorkspaceSearchIndex.createFinder\")(function* (\n  cwd: string,\n  variant: WorkspaceSearchIndexVariant,\n) {\n  const result = yield* Effect.try({\n    try: () =>\n      FileFinder.create({\n        basePath: cwd,\n        disableMmapCache: true,\n        // Content indexing costs scan CPU and memory, so only the on-demand\n        // content-search index pays for it; path-only consumers (file tree,\n        // composer path search, file picker) keep the lightweight index.\n        disableContentIndexing: variant !== \"content\",\n        aiMode: false,\n        enableFsRootScanning: true,\n        enableHomeDirScanning: true,\n      }),\n    catch: (cause) =>\n      new WorkspaceSearchIndexCreateFailed({\n        cwd,\n        reason: \"FileFinder.create threw unexpectedly.\",\n        cause,\n      }),\n  });\n  if (result.ok) return result.value;\n  return yield* new WorkspaceSearchIndexCreateFailed({\n    cwd,\n    reason: result.error,\n  });\n});\n\nconst waitForIndexReady = Effect.fn(\"WorkspaceSearchIndex.waitForIndexReady\")(function* <E>(\n  cwd: string,\n  finder: FileFinder,\n  onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,\n): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {\n  const result = yield* Effect.tryPromise({\n    try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),\n    catch: (cause) =>\n      onFailure({\n        reason: \"FileFinder.waitForIndexReady rejected unexpectedly.\",\n        cause,\n      }),\n  });\n  if (!result.ok) {\n    return yield* Effect.fail(onFailure({ reason: result.error }));\n  }\n  if (!result.value) {\n    return yield* new WorkspaceSearchIndexScanTimedOut({\n      cwd,\n      timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,\n    });\n  }\n});\n\nexport const make = Effect.fn(\"WorkspaceSearchIndex.make\")(function* (\n  cwd: string,\n  variant: WorkspaceSearchIndexVariant = \"paths\",\n) {\n  const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>\n    Effect.try({\n      try: () => finder.destroy(),\n      catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),\n    }).pipe(Effect.orDie),\n  );\n  yield* waitForIndexReady(\n    cwd,\n    finder,\n    ({ reason, cause }) =>\n      new WorkspaceSearchIndexCreateFailed({\n        cwd,\n        reason,\n        cause,\n      }),\n  );\n\n  const runSearch = Effect.fn(\"WorkspaceSearchIndex.runSearch\")(function* <A>(\n    query: string,\n    pageSize: number,\n    operation: \"directorySearch\" | \"fileSearch\" | \"grep\" | \"mixedSearch\",\n    execute: () => Result<A>,\n  ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {\n    const result = yield* Effect.try({\n      try: execute,\n      catch: (cause) =>\n        new WorkspaceSearchIndexSearchFailed({\n          cwd,\n          queryLength: query.length,\n          pageSize,\n          reason: `FileFinder.${operation} threw unexpectedly.`,\n          cause,\n        }),\n    });\n    if (!result.ok) {\n      return yield* new WorkspaceSearchIndexSearchFailed({\n        cwd,\n        queryLength: query.length,\n        pageSize,\n        reason: result.error,\n      });\n    }\n    return result.value;\n  });\n\n  const refresh: WorkspaceSearchIndex[\"Service\"][\"refresh\"] = Effect.fn(\n    \"WorkspaceSearchIndex.refresh\",\n  )(function* () {\n    const result = yield* Effect.try({\n      try: () => finder.scanFiles(),\n      catch: (cause) =>\n        new WorkspaceSearchIndexRefreshFailed({\n          cwd,\n          reason: \"FileFinder.scanFiles threw unexpectedly.\",\n          cause,\n        }),\n    });\n    if (!result.ok) {\n      return yield* new WorkspaceSearchIndexRefreshFailed({\n        cwd,\n        reason: result.error,\n      });\n    }\n    yield* waitForIndexReady(\n      cwd,\n      finder,\n      ({ reason, cause }) =>\n        new WorkspaceSearchIndexRefreshFailed({\n          cwd,\n          reason,\n          cause,\n        }),\n    );\n  });\n\n  const list: WorkspaceSearchIndex[\"Service\"][\"list\"] = Effect.fn(\"WorkspaceSearchIndex.list\")(\n    function* () {\n      const result = yield* runSearch(\"\", WORKSPACE_INDEX_PAGE_SIZE, \"mixedSearch\", () =>\n        finder.mixedSearch(\"\", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),\n      );\n      const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);\n      const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>\n        left.path.localeCompare(right.path),\n      );\n      const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);\n      return {\n        entries,\n        truncated: mapped.truncated || entries.length < sortedEntries.length,\n      };\n    },\n  );\n\n  const search: WorkspaceSearchIndex[\"Service\"][\"search\"] = Effect.fn(\n    \"WorkspaceSearchIndex.search\",\n  )(function* (query, limit, kind) {\n    const pageSize = Math.max(1, limit + 1);\n    if (kind === \"file\") {\n      const result = yield* runSearch(query, pageSize, \"fileSearch\", () =>\n        finder.fileSearch(query, { pageSize }),\n      );\n      return mapFileSearchResult(result, limit);\n    }\n    if (kind === \"directory\") {\n      const result = yield* runSearch(query, pageSize, \"directorySearch\", () =>\n        finder.directorySearch(query, { pageSize }),\n      );\n      return mapDirectorySearchResult(result, limit);\n    }\n    const result = yield* runSearch(query, pageSize, \"mixedSearch\", () =>\n      finder.mixedSearch(query, { pageSize }),\n    );\n    return mapMixedSearchResult(result, limit);\n  });\n\n  const searchContents: WorkspaceSearchIndex[\"Service\"][\"searchContents\"] = Effect.fn(\n    \"WorkspaceSearchIndex.searchContents\",\n  )(function* (input) {\n    const { searchQuery, regexMode } = buildContentSearchQuery(input);\n    const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;\n    // Grep cursors advance by file, so whole-word post-filtering needs enough\n    // raw candidates from the current file before moving to the next one.\n    const rawPageSize = input.wholeWord\n      ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)\n      : input.limit;\n    const matches: Array<ProjectSearchContentsResult[\"matches\"][number]> = [];\n    let nextCursor: GrepCursor | null = null;\n    let regexFallbackError: string | undefined;\n\n    do {\n      const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));\n      const result = yield* runSearch(input.query, input.limit, \"grep\", () =>\n        finder.grep(searchQuery, {\n          mode: regexMode ? \"regex\" : \"plain\",\n          smartCase: !input.caseSensitive && !regexMode,\n          // A single dense file must not consume the whole result page.\n          maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),\n          pageSize: rawPageSize,\n          cursor: nextCursor,\n          timeBudgetMs: remainingTimeBudgetMs,\n        }),\n      );\n\n      for (const match of result.items) {\n        const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(\n          (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),\n        );\n        if (matchRanges.length === 0) continue;\n        matches.push({\n          path: toPosixPath(match.relativePath),\n          lineNumber: match.lineNumber,\n          lineContent: match.lineContent,\n          matchRanges,\n        });\n      }\n      nextCursor = result.nextCursor;\n      regexFallbackError ??= result.regexFallbackError;\n    } while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);\n\n    return {\n      matches: matches.slice(0, input.limit),\n      truncated: matches.length > input.limit || nextCursor !== null,\n      ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),\n    };\n  });\n\n  return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });\n});\n\nexport const WORKSPACE_SEARCH_INDEX_VARIANTS = [\"paths\", \"content\"] as const;\nexport type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];\n\n/**\n * Composite LayerMap key so the lightweight path index and the on-demand\n * content-search index of the same workspace are separate resources with\n * independent lifecycles. \"\\n\" cannot appear in a filesystem path.\n */\nexport const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>\n  `${variant}\\n${cwd}`;\n\nfunction parseWorkspaceSearchIndexKey(key: string): {\n  readonly cwd: string;\n  readonly variant: WorkspaceSearchIndexVariant;\n} {\n  const separatorIndex = key.indexOf(\"\\n\");\n  return {\n    variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,\n    cwd: key.slice(separatorIndex + 1),\n  };\n}\n\n/**\n * A layer factory is required because every index is scoped to a concrete\n * workspace root and variant. WorkspaceSearchIndexMap owns memoization and\n * idle cleanup; using a default cwd here would mix resources from different\n * workspaces.\n */\nexport const layer = (key: string) => {\n  const { cwd, variant } = parseWorkspaceSearchIndexKey(key);\n  return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));\n};\n\nexport class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(\n  \"t3/workspace/WorkspaceSearchIndexMap\",\n  {\n    lookup: layer,\n    idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,\n  },\n) {}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFSP from \"node:fs/promises\";\nimport * as NodeOS from \"node:os\";\n\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as RcMap from \"effect/RcMap\";\nimport * as Schema from \"effect/Schema\";\n\nimport type {\n  FilesystemBrowseInput,\n  FilesystemBrowseResult,\n  ProjectListEntriesInput,\n  ProjectListEntriesResult,\n  ProjectSearchContentsInput,\n  ProjectSearchContentsResult,\n  ProjectSearchEntriesInput,\n  ProjectSearchEntriesResult,\n} from \"@t3tools/contracts\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { isExplicitRelativePath, isWindowsAbsolutePath } from \"@t3tools/shared/path\";\nimport { normalizeSearchQuery } from \"@t3tools/shared/searchRanking\";\n\nimport * as WorkspacePaths from \"./WorkspacePaths.ts\";\nimport * as WorkspaceSearchIndex from \"./WorkspaceSearchIndex.ts\";\n\nexport class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedErrorClass<WorkspaceEntriesWindowsPathUnsupportedError>()(\n  \"WorkspaceEntriesWindowsPathUnsupportedError\",\n  {\n    cwd: Schema.optional(Schema.String),\n    partialPath: Schema.String,\n    platform: Schema.String,\n  },\n) {\n  override get message(): string {\n    const cwd = this.cwd ? ` from '${this.cwd}'` : \"\";\n    return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;\n  }\n}\n\nexport class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedErrorClass<WorkspaceEntriesCurrentProjectRequiredError>()(\n  \"WorkspaceEntriesCurrentProjectRequiredError\",\n  {\n    partialPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `A current project is required to browse relative workspace path '${this.partialPath}'.`;\n  }\n}\n\nexport class WorkspaceEntriesReadDirectoryError extends Schema.TaggedErrorClass<WorkspaceEntriesReadDirectoryError>()(\n  \"WorkspaceEntriesReadDirectoryError\",\n  {\n    cwd: Schema.optional(Schema.String),\n    partialPath: Schema.String,\n    parentPath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const cwd = this.cwd ? ` from '${this.cwd}'` : \"\";\n    return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;\n  }\n}\n\nexport const WorkspaceEntriesBrowseError = Schema.Union([\n  WorkspaceEntriesWindowsPathUnsupportedError,\n  WorkspaceEntriesCurrentProjectRequiredError,\n  WorkspaceEntriesReadDirectoryError,\n]);\nexport type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;\n\nexport const WorkspaceEntriesError = Schema.Union([\n  WorkspacePaths.WorkspaceRootNotExistsError,\n  WorkspacePaths.WorkspaceRootCreateFailedError,\n  WorkspacePaths.WorkspaceRootStatFailedError,\n  WorkspacePaths.WorkspaceRootNotDirectoryError,\n  WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,\n  WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,\n  WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,\n]);\nexport type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;\n\nexport class WorkspaceEntries extends Context.Service<\n  WorkspaceEntries,\n  {\n    readonly browse: (\n      input: FilesystemBrowseInput,\n    ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;\n    readonly list: (\n      input: ProjectListEntriesInput,\n    ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;\n    readonly search: (\n      input: ProjectSearchEntriesInput,\n    ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;\n    readonly searchContents: (\n      input: ProjectSearchContentsInput,\n    ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;\n    readonly refresh: (cwd: string) => Effect.Effect<void>;\n  }\n>()(\"t3/workspace/WorkspaceEntries\") {}\n\nfunction expandHomePath(input: string, path: Path.Path): string {\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return path.join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n}\n\nconst resolveBrowseTarget = Effect.fn(\"WorkspaceEntries.resolveBrowseTarget\")(function* (\n  input: FilesystemBrowseInput,\n  path: Path.Path,\n): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {\n  const platform = yield* HostProcessPlatform;\n  if (platform !== \"win32\" && isWindowsAbsolutePath(input.partialPath)) {\n    return yield* new WorkspaceEntriesWindowsPathUnsupportedError({\n      cwd: input.cwd,\n      partialPath: input.partialPath,\n      platform,\n    });\n  }\n\n  if (!isExplicitRelativePath(input.partialPath)) {\n    return path.resolve(expandHomePath(input.partialPath, path));\n  }\n\n  if (!input.cwd) {\n    return yield* new WorkspaceEntriesCurrentProjectRequiredError({\n      partialPath: input.partialPath,\n    });\n  }\n  return path.resolve(expandHomePath(input.cwd, path), input.partialPath);\n});\n\nexport const make = Effect.gen(function* () {\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;\n\n  const normalizeWorkspaceRoot = Effect.fn(\"WorkspaceEntries.normalizeWorkspaceRoot\")(function* (\n    cwd: string,\n  ): Effect.fn.Return<string, WorkspaceEntriesError> {\n    return yield* workspacePaths.normalizeWorkspaceRoot(cwd);\n  });\n\n  const refresh: WorkspaceEntries[\"Service\"][\"refresh\"] = Effect.fn(\"WorkspaceEntries.refresh\")(\n    function* (cwd) {\n      const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(\n        Effect.orElseSucceed(() => cwd),\n      );\n      for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {\n        const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);\n        if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {\n          continue;\n        }\n        const recoverRefreshFailure = (\n          cause:\n            | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed\n            | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut\n            | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,\n        ) =>\n          Effect.gen(function* () {\n            yield* Effect.logWarning(\"Failed to refresh workspace search index\", {\n              cwd,\n              variant,\n              cause,\n            });\n            yield* workspaceSearchIndexes.invalidate(indexKey);\n          });\n        yield* Effect.gen(function* () {\n          const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n          yield* searchIndex.refresh();\n        }).pipe(\n          Effect.provide(workspaceSearchIndexes.get(indexKey)),\n          Effect.catchTags({\n            WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,\n            WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,\n            WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,\n          }),\n        );\n      }\n    },\n  );\n\n  const browse: WorkspaceEntries[\"Service\"][\"browse\"] = Effect.fn(\"WorkspaceEntries.browse\")(\n    function* (input) {\n      const resolvedInputPath = yield* resolveBrowseTarget(input, path);\n      const endsWithSeparator = /[\\\\/]$/.test(input.partialPath) || input.partialPath === \"~\";\n      const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);\n      const prefix = endsWithSeparator ? \"\" : path.basename(resolvedInputPath);\n\n      const dirents = yield* Effect.tryPromise({\n        try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),\n        catch: (cause) =>\n          new WorkspaceEntriesReadDirectoryError({\n            cwd: input.cwd,\n            partialPath: input.partialPath,\n            parentPath,\n            cause,\n          }),\n      }).pipe(\n        Effect.catchIf(\n          (error) => {\n            const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;\n            return code === \"EACCES\" || code === \"EPERM\";\n          },\n          () => Effect.succeed([]),\n        ),\n      );\n\n      const showHidden = endsWithSeparator || prefix.startsWith(\".\");\n      const lowerPrefix = prefix.toLowerCase();\n      const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];\n      for (const dirent of dirents) {\n        if (\n          dirent.isDirectory() &&\n          dirent.name.toLowerCase().startsWith(lowerPrefix) &&\n          (showHidden || !dirent.name.startsWith(\".\"))\n        ) {\n          entries.push({\n            name: dirent.name,\n            fullPath: path.join(parentPath, dirent.name),\n          });\n        }\n      }\n\n      return {\n        parentPath,\n        entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),\n      };\n    },\n  );\n\n  const search: WorkspaceEntries[\"Service\"][\"search\"] = Effect.fn(\"WorkspaceEntries.search\")(\n    function* (input) {\n      const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);\n      const normalizedQuery = normalizeSearchQuery(input.query, {\n        trimLeadingPattern: /^[@./]+/,\n      });\n      return yield* Effect.gen(function* () {\n        const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n        return yield* searchIndex.search(normalizedQuery, input.limit, input.kind);\n      }).pipe(\n        Effect.provide(\n          workspaceSearchIndexes.get(\n            WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, \"paths\"),\n          ),\n        ),\n      );\n    },\n  );\n\n  const searchContents: WorkspaceEntries[\"Service\"][\"searchContents\"] = Effect.fn(\n    \"WorkspaceEntries.searchContents\",\n  )(function* (input) {\n    const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);\n    return yield* Effect.gen(function* () {\n      const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n      return yield* searchIndex.searchContents(input);\n    }).pipe(\n      Effect.provide(\n        workspaceSearchIndexes.get(\n          WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, \"content\"),\n        ),\n      ),\n    );\n  });\n\n  const list: WorkspaceEntries[\"Service\"][\"list\"] = Effect.fn(\"WorkspaceEntries.list\")(\n    function* (input) {\n      const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);\n      return yield* Effect.gen(function* () {\n        const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n        return yield* searchIndex.list();\n      }).pipe(\n        Effect.provide(\n          workspaceSearchIndexes.get(\n            WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, \"paths\"),\n          ),\n        ),\n      );\n    },\n  );\n\n  return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });\n});\n\nexport const layer = Layer.effect(WorkspaceEntries, make).pipe(\n  Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),\n);\n","// @effect-diagnostics nodeBuiltinImport:off\n/**\n * WorkspaceFileSystem - Effect service contract for workspace file mutations.\n *\n * Owns workspace-root-relative file read/write operations and their associated\n * safety checks and cache invalidation hooks.\n *\n * @module WorkspaceFileSystem\n */\nimport * as NodeFSP from \"node:fs/promises\";\n\nimport type {\n  ProjectReadFileInput,\n  ProjectReadFileResult,\n  ProjectWriteFileInput,\n  ProjectWriteFileResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as WorkspaceEntries from \"./WorkspaceEntries.ts\";\nimport * as WorkspacePaths from \"./WorkspacePaths.ts\";\n\nconst PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;\n\nexport class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<WorkspaceFileSystemOperationError>()(\n  \"WorkspaceFileSystemOperationError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedPath: Schema.String,\n    operationPath: Schema.String,\n    operation: Schema.Literals([\n      \"realpath-workspace-root\",\n      \"realpath-target\",\n      \"open\",\n      \"stat\",\n      \"read\",\n      \"close\",\n      \"make-directory\",\n      \"write-file\",\n    ]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;\n  }\n}\n\nexport class WorkspaceFilePathEscapeError extends Schema.TaggedErrorClass<WorkspaceFilePathEscapeError>()(\n  \"WorkspaceFilePathEscapeError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedWorkspaceRoot: Schema.String,\n    resolvedPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;\n  }\n}\n\nexport class WorkspacePathNotFileError extends Schema.TaggedErrorClass<WorkspacePathNotFileError>()(\n  \"WorkspacePathNotFileError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;\n  }\n}\n\nexport class WorkspaceBinaryFileError extends Schema.TaggedErrorClass<WorkspaceBinaryFileError>()(\n  \"WorkspaceBinaryFileError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;\n  }\n}\n\nexport const WorkspaceFileSystemError = Schema.Union([\n  WorkspaceFileSystemOperationError,\n  WorkspaceFilePathEscapeError,\n  WorkspacePathNotFileError,\n  WorkspaceBinaryFileError,\n]);\nexport type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;\n\n/** Service tag for workspace file operations. */\nexport class WorkspaceFileSystem extends Context.Service<\n  WorkspaceFileSystem,\n  {\n    /** Read a UTF-8 text file relative to the workspace root. */\n    readonly readFile: (\n      input: ProjectReadFileInput,\n    ) => Effect.Effect<\n      ProjectReadFileResult,\n      WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError\n    >;\n    /**\n     * Write a file relative to the workspace root.\n     *\n     * Creates parent directories as needed and rejects paths that escape the\n     * workspace root.\n     */\n    readonly writeFile: (\n      input: ProjectWriteFileInput,\n    ) => Effect.Effect<\n      ProjectWriteFileResult,\n      WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError\n    >;\n  }\n>()(\"t3/workspace/WorkspaceFileSystem\") {}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;\n\n  const readFile: WorkspaceFileSystem[\"Service\"][\"readFile\"] = Effect.fn(\n    \"WorkspaceFileSystem.readFile\",\n  )(function* (input) {\n    const target = yield* workspacePaths.resolveRelativePathWithinRoot({\n      workspaceRoot: input.cwd,\n      relativePath: input.relativePath,\n    });\n\n    const realWorkspaceRoot = yield* Effect.tryPromise({\n      try: () => NodeFSP.realpath(input.cwd),\n      catch: (cause) =>\n        new WorkspaceFileSystemOperationError({\n          workspaceRoot: input.cwd,\n          relativePath: input.relativePath,\n          resolvedPath: target.absolutePath,\n          operationPath: input.cwd,\n          operation: \"realpath-workspace-root\",\n          cause,\n        }),\n    });\n    const realTargetPath = yield* Effect.tryPromise({\n      try: () => NodeFSP.realpath(target.absolutePath),\n      catch: (cause) =>\n        new WorkspaceFileSystemOperationError({\n          workspaceRoot: input.cwd,\n          relativePath: input.relativePath,\n          resolvedPath: target.absolutePath,\n          operationPath: target.absolutePath,\n          operation: \"realpath-target\",\n          cause,\n        }),\n    });\n    const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);\n    if (\n      relativeRealPath.startsWith(`..${path.sep}`) ||\n      relativeRealPath === \"..\" ||\n      path.isAbsolute(relativeRealPath)\n    ) {\n      return yield* new WorkspaceFilePathEscapeError({\n        workspaceRoot: input.cwd,\n        relativePath: input.relativePath,\n        resolvedWorkspaceRoot: realWorkspaceRoot,\n        resolvedPath: realTargetPath,\n      });\n    }\n\n    return yield* Effect.acquireUseRelease(\n      Effect.tryPromise({\n        try: () => NodeFSP.open(realTargetPath, \"r\"),\n        catch: (cause) =>\n          new WorkspaceFileSystemOperationError({\n            workspaceRoot: input.cwd,\n            relativePath: input.relativePath,\n            resolvedPath: realTargetPath,\n            operationPath: realTargetPath,\n            operation: \"open\",\n            cause,\n          }),\n      }),\n      (handle) =>\n        Effect.gen(function* () {\n          const stat = yield* Effect.tryPromise({\n            try: () => handle.stat(),\n            catch: (cause) =>\n              new WorkspaceFileSystemOperationError({\n                workspaceRoot: input.cwd,\n                relativePath: input.relativePath,\n                resolvedPath: realTargetPath,\n                operationPath: realTargetPath,\n                operation: \"stat\",\n                cause,\n              }),\n          });\n          if (!stat.isFile()) {\n            return yield* new WorkspacePathNotFileError({\n              workspaceRoot: input.cwd,\n              relativePath: input.relativePath,\n              resolvedPath: realTargetPath,\n            });\n          }\n\n          const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);\n          const buffer = Buffer.alloc(bytesToRead);\n          const { bytesRead } = yield* Effect.tryPromise({\n            try: () => handle.read(buffer, 0, bytesToRead, 0),\n            catch: (cause) =>\n              new WorkspaceFileSystemOperationError({\n                workspaceRoot: input.cwd,\n                relativePath: input.relativePath,\n                resolvedPath: realTargetPath,\n                operationPath: realTargetPath,\n                operation: \"read\",\n                cause,\n              }),\n          });\n          const fileBytes = buffer.subarray(0, bytesRead);\n          if (fileBytes.includes(0)) {\n            return yield* new WorkspaceBinaryFileError({\n              workspaceRoot: input.cwd,\n              relativePath: input.relativePath,\n              resolvedPath: realTargetPath,\n            });\n          }\n\n          return {\n            relativePath: target.relativePath,\n            contents: new TextDecoder(\"utf-8\").decode(fileBytes),\n            byteLength: stat.size,\n            truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,\n          };\n        }),\n      (handle) =>\n        Effect.tryPromise({\n          try: () => handle.close(),\n          catch: (cause) =>\n            new WorkspaceFileSystemOperationError({\n              workspaceRoot: input.cwd,\n              relativePath: input.relativePath,\n              resolvedPath: realTargetPath,\n              operationPath: realTargetPath,\n              operation: \"close\",\n              cause,\n            }),\n        }),\n    );\n  });\n\n  const writeFile: WorkspaceFileSystem[\"Service\"][\"writeFile\"] = Effect.fn(\n    \"WorkspaceFileSystem.writeFile\",\n  )(function* (input) {\n    const target = yield* workspacePaths.resolveRelativePathWithinRoot({\n      workspaceRoot: input.cwd,\n      relativePath: input.relativePath,\n    });\n\n    yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new WorkspaceFileSystemOperationError({\n            workspaceRoot: input.cwd,\n            relativePath: input.relativePath,\n            resolvedPath: target.absolutePath,\n            operationPath: path.dirname(target.absolutePath),\n            operation: \"make-directory\",\n            cause,\n          }),\n      ),\n    );\n    yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(\n      Effect.mapError(\n        (cause) =>\n          new WorkspaceFileSystemOperationError({\n            workspaceRoot: input.cwd,\n            relativePath: input.relativePath,\n            resolvedPath: target.absolutePath,\n            operationPath: target.absolutePath,\n            operation: \"write-file\",\n            cause,\n          }),\n      ),\n    );\n    yield* workspaceEntries.refresh(input.cwd);\n    return { relativePath: target.relativePath };\n  });\n\n  return WorkspaceFileSystem.of({ readFile, writeFile });\n});\n\nexport const layer = Layer.effect(WorkspaceFileSystem, make);\n","import {\n  GitCommandError,\n  type VcsListRefsInput,\n  type VcsListRefsResult,\n  type VcsRef,\n  type VcsStatusResult,\n  type VcsStatusStreamEvent,\n  type VcsSwitchRefInput,\n  type VcsSwitchRefResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\ninterface ParsedStatus {\n  readonly refName: string | null;\n  readonly hasUpstream: boolean;\n  readonly aheadCount: number;\n  readonly behindCount: number;\n  readonly files: ReadonlyArray<string>;\n}\n\nconst EMPTY_WORKING_TREE = { files: [], insertions: 0, deletions: 0 } as const;\n\nexport function parseGitStatus(output: string): ParsedStatus {\n  const records = output.split(\"\\0\").filter(Boolean);\n  const branchRecord = records[0]?.startsWith(\"## \") ? records.shift()!.slice(3) : \"\";\n  let refName: string | null = null;\n  if (branchRecord.startsWith(\"No commits yet on \")) {\n    refName = branchRecord.slice(\"No commits yet on \".length).trim() || null;\n  } else if (!branchRecord.startsWith(\"HEAD \")) {\n    refName = branchRecord.split(\"...\")[0]?.trim() || null;\n  }\n  const aheadCount = Number(/ahead (\\d+)/.exec(branchRecord)?.[1] ?? 0);\n  const behindCount = Number(/behind (\\d+)/.exec(branchRecord)?.[1] ?? 0);\n  const files: string[] = [];\n  for (let index = 0; index < records.length; index += 1) {\n    const record = records[index]!;\n    const path = record.length > 3 ? record.slice(3) : \"\";\n    if (path) files.push(path);\n    if (record[0] === \"R\" || record[1] === \"R\") index += 1;\n  }\n  return {\n    refName,\n    hasUpstream: branchRecord.includes(\"...\"),\n    aheadCount,\n    behindCount,\n    files,\n  };\n}\n\nexport function parseGitRefs(\n  output: string,\n  refKind: VcsListRefsInput[\"refKind\"],\n  query = \"\",\n  currentRef: string | null = null,\n): ReadonlyArray<VcsRef> {\n  const normalizedQuery = query.toLowerCase();\n  return output\n    .split(\"\\n\")\n    .filter(Boolean)\n    .flatMap<VcsRef>((line) => {\n      const [fullName = \"\", name = \"\", head = \"\", worktreePath = \"\"] = line.split(\"\\t\");\n      if (\n        !name ||\n        fullName.endsWith(\"/HEAD\") ||\n        !name.toLowerCase().includes(normalizedQuery)\n      ) {\n        return [];\n      }\n      const isRemote = fullName.startsWith(\"refs/remotes/\");\n      if (refKind === \"local\" && isRemote) return [];\n      if (refKind === \"remote\" && !isRemote) return [];\n      const firstSlash = name.indexOf(\"/\");\n      return [\n        {\n          name,\n          ...(isRemote ? { isRemote: true, remoteName: name.slice(0, firstSlash) } : {}),\n          current: head.trim() === \"*\" || name === currentRef,\n          isDefault: false,\n          worktreePath: worktreePath || null,\n        },\n      ];\n    });\n}\n\nexport class GitWorkspace extends Context.Service<\n  GitWorkspace,\n  {\n    readonly status: (cwd: string) => Effect.Effect<VcsStatusResult, GitCommandError>;\n    readonly statusStream: (cwd: string) => Stream.Stream<VcsStatusStreamEvent, GitCommandError>;\n    readonly listRefs: (\n      input: VcsListRefsInput,\n    ) => Effect.Effect<VcsListRefsResult, GitCommandError>;\n    readonly switchRef: (\n      input: VcsSwitchRefInput,\n    ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;\n  }\n>()(\"agentlink/workspace/GitWorkspace\") {}\n\nexport const make = Effect.gen(function* () {\n  const runner = yield* ProcessRunner.ProcessRunner;\n\n  const run = Effect.fn(\"GitWorkspace.run\")(function* (\n    cwd: string,\n    operation: string,\n    args: ReadonlyArray<string>,\n    allowFailure = false,\n  ) {\n    const result = yield* runner\n      .run({\n        command: \"git\",\n        args,\n        cwd,\n        timeout: \"15 seconds\",\n        maxOutputBytes: 2 * 1024 * 1024,\n        outputMode: \"truncate\",\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new GitCommandError({\n              operation,\n              command: \"git\",\n              cwd,\n              argumentCount: args.length,\n              detail: cause.message,\n              cause,\n            }),\n        ),\n      );\n    if (!allowFailure && result.code !== 0) {\n      return yield* new GitCommandError({\n        operation,\n        command: \"git\",\n        cwd,\n        argumentCount: args.length,\n        exitCode: result.code ?? undefined,\n        stdoutLength: result.stdout.length,\n        stderrLength: result.stderr.length,\n        outputLength: result.stdout.length + result.stderr.length,\n        detail: result.stderr.trim() || result.stdout.trim() || \"Git command failed.\",\n      });\n    }\n    return result;\n  });\n\n  const status: GitWorkspace[\"Service\"][\"status\"] = Effect.fn(\"GitWorkspace.status\")(\n    function* (cwd) {\n      const repository = yield* run(\n        cwd,\n        \"status.detect\",\n        [\"rev-parse\", \"--is-inside-work-tree\"],\n        true,\n      );\n      if (repository.code !== 0 || repository.stdout.trim() !== \"true\") {\n        return {\n          isRepo: false,\n          hasPrimaryRemote: false,\n          isDefaultRef: false,\n          refName: null,\n          hasWorkingTreeChanges: false,\n          workingTree: EMPTY_WORKING_TREE,\n          hasUpstream: false,\n          aheadCount: 0,\n          behindCount: 0,\n          aheadOfDefaultCount: 0,\n          pr: null,\n        };\n      }\n      const rawStatus = yield* run(cwd, \"status\", [\n        \"status\",\n        \"--porcelain=v1\",\n        \"-z\",\n        \"--branch\",\n        \"--untracked-files=normal\",\n      ]);\n      const parsed = parseGitStatus(rawStatus.stdout);\n      const [origin, defaultRef] = yield* Effect.all([\n        run(cwd, \"remote.origin\", [\"remote\", \"get-url\", \"origin\"], true),\n        run(cwd, \"remote.default\", [\"symbolic-ref\", \"refs/remotes/origin/HEAD\", \"--short\"], true),\n      ]);\n      return {\n        isRepo: true,\n        hasPrimaryRemote: origin.code === 0,\n        isDefaultRef:\n          defaultRef.code === 0 &&\n          defaultRef.stdout.trim().replace(/^origin\\//, \"\") === parsed.refName,\n        refName: parsed.refName,\n        hasWorkingTreeChanges: parsed.files.length > 0,\n        workingTree: {\n          files: parsed.files.map((path) => ({ path, insertions: 0, deletions: 0 })),\n          insertions: 0,\n          deletions: 0,\n        },\n        hasUpstream: parsed.hasUpstream,\n        aheadCount: parsed.aheadCount,\n        behindCount: parsed.behindCount,\n        aheadOfDefaultCount: 0,\n        pr: null,\n      };\n    },\n  );\n\n  const listRefs: GitWorkspace[\"Service\"][\"listRefs\"] = Effect.fn(\"GitWorkspace.listRefs\")(\n    function* (input) {\n      const currentStatus = yield* status(input.cwd);\n      if (!currentStatus.isRepo) {\n        return {\n          refs: [],\n          isRepo: false,\n          hasPrimaryRemote: false,\n          nextCursor: null,\n          totalCount: 0,\n        };\n      }\n      const result = yield* run(input.cwd, \"refs.list\", [\n        \"for-each-ref\",\n        \"--format=%(refname)\\t%(refname:short)\\t%(HEAD)\\t%(worktreepath)\",\n        \"refs/heads\",\n        \"refs/remotes\",\n      ]);\n      const refs = parseGitRefs(\n        result.stdout,\n        input.refKind,\n        input.query ?? \"\",\n        currentStatus.refName,\n      );\n      const cursor = input.cursor ?? 0;\n      const limit = input.limit ?? 100;\n      const page = refs.slice(cursor, cursor + limit);\n      return {\n        refs: page,\n        isRepo: true,\n        hasPrimaryRemote: currentStatus.hasPrimaryRemote,\n        nextCursor: cursor + page.length < refs.length ? cursor + page.length : null,\n        totalCount: refs.length,\n      };\n    },\n  );\n\n  const switchRef: GitWorkspace[\"Service\"][\"switchRef\"] = Effect.fn(\"GitWorkspace.switchRef\")(\n    function* (input) {\n      yield* run(input.cwd, \"refs.switch\", [\"switch\", input.refName]);\n      return { refName: (yield* status(input.cwd)).refName };\n    },\n  );\n\n  return GitWorkspace.of({\n    status,\n    statusStream: (cwd) =>\n      Stream.fromEffectSchedule(status(cwd), Schedule.spaced(\"3 seconds\")).pipe(\n        Stream.map(\n          (value): VcsStatusStreamEvent => ({\n            _tag: \"snapshot\",\n            local: {\n              isRepo: value.isRepo,\n              hasPrimaryRemote: value.hasPrimaryRemote,\n              isDefaultRef: value.isDefaultRef,\n              refName: value.refName,\n              hasWorkingTreeChanges: value.hasWorkingTreeChanges,\n              workingTree: value.workingTree,\n            },\n            remote: value.isRepo\n              ? {\n                  hasUpstream: value.hasUpstream,\n                  aheadCount: value.aheadCount,\n                  behindCount: value.behindCount,\n                  aheadOfDefaultCount: value.aheadOfDefaultCount,\n                  pr: value.pr,\n                }\n              : null,\n          }),\n        ),\n      ),\n    listRefs,\n    switchRef,\n  });\n});\n\nexport const layer = Layer.effect(GitWorkspace, make).pipe(Layer.provide(ProcessRunner.layer));\n","/**\n * PtyAdapter - Terminal PTY adapter service contract.\n *\n * Defines the process primitives required by terminal session management\n * without binding to a specific PTY implementation.\n *\n * @module PtyAdapter\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\n/**\n * PtySpawnError - Error type for PTY spawn failures.\n */\nexport class PtySpawnError extends Schema.TaggedErrorClass<PtySpawnError>()(\"PtySpawnError\", {\n  adapter: Schema.String,\n  shell: Schema.optional(Schema.String),\n  attemptedShells: Schema.optional(Schema.Array(Schema.String)),\n  cause: Schema.optional(Schema.Defect()),\n}) {\n  override get message(): string {\n    const shell = this.shell === undefined ? \"\" : ` '${this.shell}'`;\n    const attemptedShells =\n      this.attemptedShells === undefined || this.attemptedShells.length === 0\n        ? \"\"\n        : ` Tried shells: ${this.attemptedShells.join(\", \")}.`;\n    return `Failed to spawn PTY process${shell} with ${this.adapter}.${attemptedShells}`;\n  }\n}\n\nexport interface PtyExitEvent {\n  exitCode: number;\n  signal: number | null;\n}\n\nexport interface PtyProcess {\n  readonly pid: number;\n  write(data: string): void;\n  resize(cols: number, rows: number): void;\n  kill(signal?: string): void;\n  onData(callback: (data: string) => void): () => void;\n  onExit(callback: (event: PtyExitEvent) => void): () => void;\n}\n\nexport interface PtySpawnInput {\n  shell: string;\n  args?: string[];\n  cwd: string;\n  cols: number;\n  rows: number;\n  env: NodeJS.ProcessEnv;\n}\n\n/**\n * PtyAdapter - Service tag for PTY process integration.\n */\nexport class PtyAdapter extends Context.Service<\n  PtyAdapter,\n  {\n    /**\n     * Spawn a PTY process for a terminal session.\n     */\n    readonly spawn: (input: PtySpawnInput) => Effect.Effect<PtyProcess, PtySpawnError>;\n  }\n>()(\"t3/terminal/PtyAdapter\") {}\n","import * as NodeFs from \"node:fs/promises\";\n\nimport {\n  TerminalCwdNotDirectoryError,\n  TerminalCwdNotFoundError,\n  TerminalCwdStatError,\n  TerminalNotRunningError,\n  TerminalResizeError,\n  TerminalSessionLookupError,\n  TerminalWriteError,\n  type TerminalAttachInput,\n  type TerminalAttachStreamEvent,\n  type TerminalClearInput,\n  type TerminalCloseInput,\n  type TerminalError,\n  type TerminalEvent,\n  type TerminalMetadataStreamEvent,\n  type TerminalOpenInput,\n  type TerminalResizeInput,\n  type TerminalRestartInput,\n  type TerminalSessionSnapshot,\n  type TerminalSummary,\n  type TerminalWriteInput,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport * as PtyAdapter from \"./PtyAdapter.ts\";\n\nconst DEFAULT_COLS = 120;\nconst DEFAULT_ROWS = 30;\nconst MAX_HISTORY_CHARS = 512 * 1024;\n\nexport function terminalLocale(\n  environment: NodeJS.ProcessEnv,\n  platform: NodeJS.Platform,\n): string {\n  return (\n    environment.LC_ALL ??\n    environment.LC_CTYPE ??\n    environment.LANG ??\n    (platform === \"darwin\" ? \"en_US.UTF-8\" : \"C.UTF-8\")\n  );\n}\n\ninterface Session {\n  readonly threadId: string;\n  readonly terminalId: string;\n  cwd: string;\n  worktreePath: string | null;\n  status: TerminalSessionSnapshot[\"status\"];\n  process: PtyAdapter.PtyProcess | null;\n  history: string;\n  exitCode: number | null;\n  exitSignal: number | null;\n  updatedAt: string;\n  sequence: number;\n  cols: number;\n  rows: number;\n  env: Record<string, string> | undefined;\n  unsubscribeData: (() => void) | null;\n  unsubscribeExit: (() => void) | null;\n}\n\nexport class TerminalManager extends Context.Service<\n  TerminalManager,\n  {\n    readonly open: (\n      input: TerminalOpenInput,\n    ) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;\n    readonly attachStream: (\n      input: TerminalAttachInput,\n      listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,\n    ) => Effect.Effect<() => void, TerminalError>;\n    readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;\n    readonly resize: (input: TerminalResizeInput) => Effect.Effect<void, TerminalError>;\n    readonly clear: (input: TerminalClearInput) => Effect.Effect<void, TerminalError>;\n    readonly restart: (\n      input: TerminalRestartInput,\n    ) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;\n    readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;\n    readonly subscribe: (\n      listener: (event: TerminalEvent) => Effect.Effect<void>,\n    ) => Effect.Effect<() => void>;\n    readonly subscribeMetadata: (\n      listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,\n    ) => Effect.Effect<() => void>;\n  }\n>()(\"agentlink/terminal/TerminalManager\") {}\n\nfunction sessionKey(threadId: string, terminalId: string): string {\n  return `${threadId}\\0${terminalId}`;\n}\n\nfunction now(): string {\n  return new Date().toISOString();\n}\n\nfunction label(session: Session): string {\n  return session.status === \"running\" ? \"Terminal\" : \"Terminal (stopped)\";\n}\n\nfunction snapshot(session: Session): TerminalSessionSnapshot {\n  return {\n    threadId: session.threadId,\n    terminalId: session.terminalId,\n    cwd: session.cwd,\n    worktreePath: session.worktreePath,\n    status: session.status,\n    pid: session.process?.pid ?? null,\n    history: session.history,\n    exitCode: session.exitCode,\n    exitSignal: session.exitSignal,\n    label: label(session),\n    updatedAt: session.updatedAt,\n    sequence: session.sequence,\n  };\n}\n\nfunction summary(session: Session): TerminalSummary {\n  return {\n    threadId: session.threadId,\n    terminalId: session.terminalId,\n    cwd: session.cwd,\n    worktreePath: session.worktreePath,\n    status: session.status,\n    pid: session.process?.pid ?? null,\n    exitCode: session.exitCode,\n    exitSignal: session.exitSignal,\n    hasRunningSubprocess: false,\n    label: label(session),\n    updatedAt: session.updatedAt,\n  };\n}\n\nfunction validateCwd(cwd: string): Effect.Effect<void, TerminalError> {\n  return Effect.tryPromise({\n    try: () => NodeFs.stat(cwd),\n    catch: (cause) => {\n      const code = (cause as NodeJS.ErrnoException).code;\n      return code === \"ENOENT\"\n        ? new TerminalCwdNotFoundError({ cwd })\n        : new TerminalCwdStatError({ cwd, cause });\n    },\n  }).pipe(\n    Effect.flatMap((stat) =>\n      stat.isDirectory() ? Effect.void : new TerminalCwdNotDirectoryError({ cwd }),\n    ),\n  );\n}\n\nexport const make = Effect.gen(function* () {\n  const pty = yield* PtyAdapter.PtyAdapter;\n  const context = yield* Effect.context<never>();\n  const runFork = Effect.runForkWith(context);\n  const sessions = new Map<string, Session>();\n  const eventListeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();\n  const metadataListeners = new Set<(event: TerminalMetadataStreamEvent) => Effect.Effect<void>>();\n  const attachListeners = new Map<\n    string,\n    Set<(event: TerminalAttachStreamEvent) => Effect.Effect<void>>\n  >();\n\n  const publish = (event: TerminalEvent) => {\n    if (eventListeners.size > 0) {\n      runFork(Effect.forEach(eventListeners, (listener) => listener(event), { discard: true }));\n    }\n    if (event.type !== \"started\") {\n      const listeners = attachListeners.get(sessionKey(event.threadId, event.terminalId));\n      if (listeners && listeners.size > 0) {\n        runFork(Effect.forEach(listeners, (listener) => listener(event), { discard: true }));\n      }\n    }\n  };\n\n  const publishMetadata = (event: TerminalMetadataStreamEvent) => {\n    if (metadataListeners.size > 0) {\n      runFork(Effect.forEach(metadataListeners, (listener) => listener(event), { discard: true }));\n    }\n  };\n\n  const touch = (session: Session) => {\n    session.updatedAt = now();\n    session.sequence += 1;\n  };\n\n  const stop = (session: Session) => {\n    session.unsubscribeData?.();\n    session.unsubscribeExit?.();\n    session.unsubscribeData = null;\n    session.unsubscribeExit = null;\n    if (session.process) {\n      try {\n        session.process.kill();\n      } catch {\n        // Already exited.\n      }\n      session.process = null;\n    }\n  };\n\n  const spawn = Effect.fn(\"TerminalManager.spawn\")(function* (session: Session) {\n    session.status = \"starting\";\n    session.exitCode = null;\n    session.exitSignal = null;\n    touch(session);\n\n    const candidates = [\n      process.env.SHELL,\n      process.platform === \"win32\" ? process.env.ComSpec : undefined,\n      process.platform === \"win32\" ? \"powershell.exe\" : \"/bin/zsh\",\n      process.platform === \"win32\" ? \"cmd.exe\" : \"/bin/bash\",\n      process.platform === \"win32\" ? undefined : \"/bin/sh\",\n    ].filter((candidate): candidate is string => Boolean(candidate));\n    let lastError: unknown = null;\n    let child: PtyAdapter.PtyProcess | null = null;\n    for (const shell of [...new Set(candidates)]) {\n      const result = yield* Effect.result(\n        pty.spawn({\n          shell,\n          cwd: session.cwd,\n          cols: session.cols,\n          rows: session.rows,\n          env: {\n            ...process.env,\n            ...session.env,\n            TERM: \"xterm-256color\",\n            LANG: terminalLocale({ ...process.env, ...session.env }, process.platform),\n          },\n        }),\n      );\n      if (result._tag === \"Success\") {\n        child = result.success;\n        break;\n      }\n      lastError = result.failure;\n    }\n\n    if (!child) {\n      session.status = \"error\";\n      touch(session);\n      publish({\n        type: \"error\",\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        sequence: session.sequence,\n        message: lastError instanceof Error ? lastError.message : \"Could not start terminal.\",\n      });\n      publishMetadata({ type: \"upsert\", terminal: summary(session) });\n      return;\n    }\n\n    session.process = child;\n    session.status = \"running\";\n    touch(session);\n    const childPid = child.pid;\n    session.unsubscribeData = child.onData((data) => {\n      if (session.process?.pid !== childPid) return;\n      // ponytail: process-local bounded history; restore upstream persisted logs if users need\n      // terminal recovery across daemon restarts.\n      session.history = `${session.history}${data}`.slice(-MAX_HISTORY_CHARS);\n      touch(session);\n      publish({\n        type: \"output\",\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        sequence: session.sequence,\n        data,\n      });\n    });\n    session.unsubscribeExit = child.onExit((event) => {\n      if (session.process?.pid !== childPid) return;\n      session.unsubscribeData?.();\n      session.unsubscribeData = null;\n      session.unsubscribeExit = null;\n      session.process = null;\n      session.status = \"exited\";\n      session.exitCode = event.exitCode;\n      session.exitSignal = event.signal;\n      touch(session);\n      publish({\n        type: \"exited\",\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        sequence: session.sequence,\n        exitCode: event.exitCode,\n        exitSignal: event.signal,\n      });\n      publishMetadata({ type: \"upsert\", terminal: summary(session) });\n    });\n    publish({\n      type: \"started\",\n      threadId: session.threadId,\n      terminalId: session.terminalId,\n      sequence: session.sequence,\n      snapshot: snapshot(session),\n    });\n    publishMetadata({ type: \"upsert\", terminal: summary(session) });\n  });\n\n  const get = (threadId: string, terminalId: string) =>\n    sessions.get(sessionKey(threadId, terminalId));\n\n  const open: TerminalManager[\"Service\"][\"open\"] = Effect.fn(\"TerminalManager.open\")(\n    function* (input) {\n      const existing = get(input.threadId, input.terminalId);\n      if (existing) return snapshot(existing);\n      yield* validateCwd(input.cwd);\n      const session: Session = {\n        threadId: input.threadId,\n        terminalId: input.terminalId,\n        cwd: input.cwd,\n        worktreePath: input.worktreePath ?? null,\n        status: \"starting\",\n        process: null,\n        history: \"\",\n        exitCode: null,\n        exitSignal: null,\n        updatedAt: now(),\n        sequence: 0,\n        cols: input.cols ?? DEFAULT_COLS,\n        rows: input.rows ?? DEFAULT_ROWS,\n        env: input.env,\n        unsubscribeData: null,\n        unsubscribeExit: null,\n      };\n      sessions.set(sessionKey(input.threadId, input.terminalId), session);\n      yield* spawn(session);\n      return snapshot(session);\n    },\n  );\n\n  const restart: TerminalManager[\"Service\"][\"restart\"] = Effect.fn(\"TerminalManager.restart\")(\n    function* (input) {\n      yield* validateCwd(input.cwd);\n      const session = get(input.threadId, input.terminalId);\n      if (!session) {\n        return yield* new TerminalSessionLookupError({\n          threadId: input.threadId,\n          terminalId: input.terminalId,\n        });\n      }\n      stop(session);\n      session.cwd = input.cwd;\n      session.worktreePath = input.worktreePath ?? null;\n      session.cols = input.cols;\n      session.rows = input.rows;\n      session.env = input.env;\n      session.history = \"\";\n      yield* spawn(session);\n      publish({\n        type: \"restarted\",\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        sequence: session.sequence,\n        snapshot: snapshot(session),\n      });\n      return snapshot(session);\n    },\n  );\n\n  const attachStream: TerminalManager[\"Service\"][\"attachStream\"] = Effect.fn(\n    \"TerminalManager.attachStream\",\n  )(function* (input, listener) {\n    let session = get(input.threadId, input.terminalId);\n    if (!session && input.cwd) {\n      yield* open({\n        threadId: input.threadId,\n        terminalId: input.terminalId,\n        cwd: input.cwd,\n        worktreePath: input.worktreePath ?? null,\n        cols: input.cols,\n        rows: input.rows,\n        env: input.env,\n      });\n      session = get(input.threadId, input.terminalId);\n    }\n    if (!session) {\n      return yield* new TerminalSessionLookupError({\n        threadId: input.threadId,\n        terminalId: input.terminalId,\n      });\n    }\n    if (input.restartIfNotRunning && session.status !== \"running\" && input.cwd) {\n      yield* restart({\n        threadId: input.threadId,\n        terminalId: input.terminalId,\n        cwd: input.cwd,\n        worktreePath: input.worktreePath ?? null,\n        cols: input.cols ?? session.cols,\n        rows: input.rows ?? session.rows,\n        env: input.env,\n      });\n    }\n    yield* listener({ type: \"snapshot\", snapshot: snapshot(session) });\n    const key = sessionKey(input.threadId, input.terminalId);\n    const listeners = attachListeners.get(key) ?? new Set();\n    listeners.add(listener);\n    attachListeners.set(key, listeners);\n    return () => {\n      listeners.delete(listener);\n      if (listeners.size === 0) attachListeners.delete(key);\n    };\n  });\n\n  const write: TerminalManager[\"Service\"][\"write\"] = (input) =>\n    Effect.gen(function* () {\n      const session = get(input.threadId, input.terminalId);\n      if (!session) {\n        return yield* new TerminalSessionLookupError({\n          threadId: input.threadId,\n          terminalId: input.terminalId,\n        });\n      }\n      if (!session.process || session.status !== \"running\") {\n        return yield* new TerminalNotRunningError({\n          threadId: input.threadId,\n          terminalId: input.terminalId,\n        });\n      }\n      yield* Effect.try({\n        try: () => session.process!.write(input.data),\n        catch: (cause) =>\n          new TerminalWriteError({\n            threadId: input.threadId,\n            terminalId: input.terminalId,\n            terminalPid: session.process!.pid,\n            cause,\n          }),\n      });\n    });\n\n  const resize: TerminalManager[\"Service\"][\"resize\"] = (input) =>\n    Effect.gen(function* () {\n      const session = get(input.threadId, input.terminalId);\n      if (!session) {\n        return yield* new TerminalSessionLookupError({\n          threadId: input.threadId,\n          terminalId: input.terminalId,\n        });\n      }\n      if (!session.process || session.status !== \"running\") {\n        return yield* new TerminalNotRunningError({\n          threadId: input.threadId,\n          terminalId: input.terminalId,\n        });\n      }\n      yield* Effect.try({\n        try: () => session.process!.resize(input.cols, input.rows),\n        catch: (cause) =>\n          new TerminalResizeError({\n            threadId: input.threadId,\n            terminalId: input.terminalId,\n            terminalPid: session.process!.pid,\n            cols: input.cols,\n            rows: input.rows,\n            cause,\n          }),\n      });\n      session.cols = input.cols;\n      session.rows = input.rows;\n    });\n\n  const clear: TerminalManager[\"Service\"][\"clear\"] = (input) =>\n    Effect.gen(function* () {\n      const session = get(input.threadId, input.terminalId);\n      if (!session) {\n        return yield* new TerminalSessionLookupError({\n          threadId: input.threadId,\n          terminalId: input.terminalId,\n        });\n      }\n      session.history = \"\";\n      touch(session);\n      publish({\n        type: \"cleared\",\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        sequence: session.sequence,\n      });\n    });\n\n  const close: TerminalManager[\"Service\"][\"close\"] = (input) =>\n    Effect.sync(() => {\n      const targets = [...sessions.values()].filter(\n        (session) =>\n          session.threadId === input.threadId &&\n          (input.terminalId === undefined || session.terminalId === input.terminalId),\n      );\n      for (const session of targets) {\n        stop(session);\n        sessions.delete(sessionKey(session.threadId, session.terminalId));\n        attachListeners.delete(sessionKey(session.threadId, session.terminalId));\n        touch(session);\n        publish({\n          type: \"closed\",\n          threadId: session.threadId,\n          terminalId: session.terminalId,\n          sequence: session.sequence,\n        });\n        publishMetadata({\n          type: \"remove\",\n          threadId: session.threadId,\n          terminalId: session.terminalId,\n        });\n      }\n    });\n\n  return TerminalManager.of({\n    open,\n    attachStream,\n    write,\n    resize,\n    clear,\n    restart,\n    close,\n    subscribe: (listener) =>\n      Effect.sync(() => {\n        eventListeners.add(listener);\n        return () => eventListeners.delete(listener);\n      }),\n    subscribeMetadata: (listener) =>\n      Effect.gen(function* () {\n        yield* listener({ type: \"snapshot\", terminals: [...sessions.values()].map(summary) });\n        metadataListeners.add(listener);\n        return () => metadataListeners.delete(listener);\n      }),\n  });\n});\n\nexport const layer = Layer.effect(TerminalManager, make);\n","import {\n  AuthAccessReadScope,\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  AuthPortProxyOperateScope,\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n  AuthReviewWriteScope,\n  AuthTerminalOperateScope,\n  ORCHESTRATION_WS_METHODS,\n  type AuthEnvironmentScope,\n  WS_METHODS,\n  WsRpcGroup,\n} from \"@t3tools/contracts\";\nimport type * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\ntype WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>[\"_tag\"];\n\n/**\n * Keep authorization coverage coupled to the RPC group itself. Adding an RPC to\n * `WsRpcGroup` without choosing a scope is a type error instead of a production\n * runtime failure.\n */\nexport const RPC_REQUIRED_SCOPES = {\n  [ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,\n  [ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverProbe]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpdateServer]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpdateServerWithProgress]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpsertKeybinding]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverRemoveKeybinding]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverUpdateSettings]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverDiscoverSourceControl]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetTraceDiagnostics]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetProcessDiagnostics]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,\n  [WS_METHODS.portProxyList]: AuthOrchestrationOperateScope,\n  [WS_METHODS.portProxyAuthorize]: AuthOrchestrationOperateScope,\n  [WS_METHODS.portProxyRevoke]: AuthOrchestrationOperateScope,\n  [WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,\n  [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,\n  [WS_METHODS.voiceInputStart]: AuthOrchestrationOperateScope,\n  [WS_METHODS.voiceInputAppendAudio]: AuthOrchestrationOperateScope,\n  [WS_METHODS.voiceInputStop]: AuthOrchestrationOperateScope,\n  [WS_METHODS.subscribeVoiceInputTranscript]: AuthOrchestrationReadScope,\n  [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,\n  [WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,\n  [WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,\n  [WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,\n  [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,\n  [WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,\n  [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,\n  [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,\n  [WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,\n  [WS_METHODS.gitRunStackedAction]: AuthOrchestrationOperateScope,\n  [WS_METHODS.gitResolvePullRequest]: AuthOrchestrationOperateScope,\n  [WS_METHODS.gitPreparePullRequestThread]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,\n  [WS_METHODS.vcsCreateWorktree]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsRemoveWorktree]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsCreateRef]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,\n  [WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,\n  [WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,\n  [WS_METHODS.terminalOpen]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalAttach]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalWrite]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalResize]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalClear]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalRestart]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalClose]: AuthTerminalOperateScope,\n  [WS_METHODS.subscribeTerminalEvents]: AuthTerminalOperateScope,\n  [WS_METHODS.subscribeTerminalMetadata]: AuthTerminalOperateScope,\n  [WS_METHODS.previewOpen]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewNavigate]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewResize]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewRefresh]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewClose]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewList]: AuthOrchestrationReadScope,\n  [WS_METHODS.previewReportStatus]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewAutomationConnect]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewAutomationRespond]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewAutomationFocusHost]: AuthOrchestrationOperateScope,\n  [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope,\n  [WS_METHODS.subscribeBackgroundPolicy]: AuthOrchestrationReadScope,\n} as const satisfies Readonly<Record<WsRpcMethod, AuthEnvironmentScope>>;\n\nexport function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope {\n  if (!Object.hasOwn(RPC_REQUIRED_SCOPES, method)) {\n    throw new Error(`RPC method ${method} has no declared authorization scope.`);\n  }\n  const requiredScope = RPC_REQUIRED_SCOPES[method as WsRpcMethod];\n  if (requiredScope === undefined) {\n    throw new Error(`RPC method ${method} has no declared authorization scope.`);\n  }\n  return requiredScope;\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport {\n  AuthAccessStreamError,\n  type AuthAccessStreamEvent,\n  type AuthEnvironmentScope,\n  AuthSessionId,\n  CommandId,\n  type OrchestrationCommand,\n  OrchestrationDispatchCommandError,\n  type OrchestrationEvent,\n  type OrchestrationShellStreamEvent,\n  type OrchestrationShellStreamItem,\n  type OrchestrationThreadStreamItem,\n  OrchestrationGetSnapshotError,\n  OrchestrationSearchThreadsError,\n  ORCHESTRATION_WS_METHODS,\n  type ProjectId,\n  type ProjectEntriesFailure,\n  type ProjectFileFailure,\n  type ProjectFileOperation,\n  ProjectListEntriesError,\n  ProjectReadFileError,\n  ProjectSearchContentsError,\n  ProjectSearchEntriesError,\n  ProjectWriteFileError,\n  type FilesystemBrowseFailure,\n  FilesystemBrowseError,\n  AssetWorkspaceContextNotFoundError,\n  AssetWorkspaceContextResolutionError,\n  RpcClientId,\n  EnvironmentAuthorizationError,\n  ThreadId,\n  type ProviderRuntimeEvent,\n  VoiceInputUnavailableError,\n  type TerminalAttachStreamEvent,\n  type TerminalError,\n  type TerminalEvent,\n  type TerminalMetadataStreamEvent,\n  WS_METHODS,\n  WsRpcGroup,\n} from \"@t3tools/contracts\";\nimport { HttpRouter, HttpServerRequest, HttpServerRespondable } from \"effect/unstable/http\";\nimport { RpcSerialization, RpcServer } from \"effect/unstable/rpc\";\nimport * as Rpc from \"effect/unstable/rpc/Rpc\";\nimport * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\nimport * as ServerConfig from \"./config.ts\";\nimport * as Keybindings from \"./keybindings.ts\";\nimport * as ExternalLauncher from \"./process/externalLauncher.ts\";\nimport {\n  projectActivityEvent,\n  projectThreadDetailSnapshot,\n} from \"./orchestration/ActivityPayloadProjection.ts\";\nimport { normalizeDispatchCommand } from \"./orchestration/Normalizer.ts\";\nimport * as OrchestrationEngine from \"./orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"./orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport * as ProviderRuntimeIngestion from \"./orchestration/Services/ProviderRuntimeIngestion.ts\";\nimport {\n  observeRpcEffect as instrumentRpcEffect,\n  observeRpcStream as instrumentRpcStream,\n  observeRpcStreamEffect as instrumentRpcStreamEffect,\n} from \"./observability/RpcInstrumentation.ts\";\nimport * as ProviderRegistry from \"./provider/Services/ProviderRegistry.ts\";\nimport * as ProviderAdapterRegistry from \"./provider/Services/ProviderAdapterRegistry.ts\";\nimport * as ProviderSessionDirectory from \"./provider/Services/ProviderSessionDirectory.ts\";\nimport * as ProviderService from \"./provider/Services/ProviderService.ts\";\nimport * as ProviderMaintenanceRunner from \"./provider/providerMaintenanceRunner.ts\";\nimport * as ServerLifecycleEvents from \"./serverLifecycleEvents.ts\";\nimport * as ServerRuntimeStartup from \"./serverRuntimeStartup.ts\";\nimport * as ServerSettings from \"./serverSettings.ts\";\nimport * as PortProxy from \"./portProxy.ts\";\nimport { issueAssetUrl } from \"./assets/AssetAccess.ts\";\nimport * as WorkspaceEntries from \"./workspace/WorkspaceEntries.ts\";\nimport * as WorkspaceFileSystem from \"./workspace/WorkspaceFileSystem.ts\";\nimport * as WorkspacePaths from \"./workspace/WorkspacePaths.ts\";\nimport * as GitWorkspace from \"./workspace/GitWorkspace.ts\";\nimport * as TerminalManager from \"./terminal/Manager.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport * as BackgroundPolicy from \"./background/BackgroundPolicy.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport { requiredScopeForRpcMethod } from \"./auth/RpcAuthorization.ts\";\nimport * as PairingGrantStore from \"./auth/PairingGrantStore.ts\";\nimport * as SessionStore from \"./auth/SessionStore.ts\";\nimport { failEnvironmentAuthInvalid, failEnvironmentInternal } from \"./auth/http.ts\";\nconst isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\nconst EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);\n\nexport const resolveAvailableEditorsForConfig = <A, E, R>(\n  discovery: Effect.Effect<ReadonlyArray<A>, E, R>,\n) =>\n  discovery.pipe(\n    Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT),\n    Effect.map(Option.getOrElse(() => [])),\n  );\n\nfunction unexpectedCompatibilityError(error: never): never {\n  throw new Error(`Unhandled compatibility error: ${String(error)}`);\n}\n\nfunction projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {\n  readonly failure: ProjectEntriesFailure;\n  readonly normalizedCwd?: string;\n  readonly timeout?: string;\n  readonly detail?: string;\n} {\n  switch (error._tag) {\n    case \"WorkspaceRootNotExistsError\":\n      return {\n        failure: \"workspace_root_not_found\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n      };\n    case \"WorkspaceRootCreateFailedError\":\n      return {\n        failure: \"workspace_root_create_failed\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n      };\n    case \"WorkspaceRootStatFailedError\":\n      return {\n        failure: \"workspace_root_stat_failed\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n        detail: error.phase,\n      };\n    case \"WorkspaceRootNotDirectoryError\":\n      return {\n        failure: \"workspace_root_not_directory\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n      };\n    case \"WorkspaceSearchIndexCreateFailed\":\n      return {\n        failure: \"search_index_create_failed\",\n        normalizedCwd: error.cwd,\n        detail: error.reason,\n      };\n    case \"WorkspaceSearchIndexScanTimedOut\":\n      return {\n        failure: \"search_index_scan_timed_out\",\n        normalizedCwd: error.cwd,\n        timeout: error.timeout,\n      };\n    case \"WorkspaceSearchIndexSearchFailed\":\n      return {\n        failure: \"search_index_search_failed\",\n        normalizedCwd: error.cwd,\n        detail: error.reason,\n      };\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nfunction filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntriesBrowseError): {\n  readonly failure: FilesystemBrowseFailure;\n  readonly parentPath?: string;\n  readonly platform?: string;\n} {\n  switch (error._tag) {\n    case \"WorkspaceEntriesWindowsPathUnsupportedError\":\n      return { failure: \"windows_path_unsupported\", platform: error.platform };\n    case \"WorkspaceEntriesCurrentProjectRequiredError\":\n      return { failure: \"current_project_required\" };\n    case \"WorkspaceEntriesReadDirectoryError\":\n      return { failure: \"read_directory_failed\", parentPath: error.parentPath };\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nfunction projectFileFailureContext(\n  error:\n    | WorkspaceFileSystem.WorkspaceFileSystemError\n    | WorkspacePaths.WorkspacePathOutsideRootError,\n): {\n  readonly failure: ProjectFileFailure;\n  readonly resolvedPath?: string;\n  readonly resolvedWorkspaceRoot?: string;\n  readonly operation?: ProjectFileOperation;\n  readonly operationPath?: string;\n} {\n  switch (error._tag) {\n    case \"WorkspacePathOutsideRootError\":\n      return { failure: \"workspace_path_outside_root\" };\n    case \"WorkspaceFileSystemOperationError\":\n      return {\n        failure: \"operation_failed\",\n        resolvedPath: error.resolvedPath,\n        operation: error.operation,\n        operationPath: error.operationPath,\n      };\n    case \"WorkspaceFilePathEscapeError\":\n      return {\n        failure: \"resolved_path_outside_root\",\n        resolvedPath: error.resolvedPath,\n        resolvedWorkspaceRoot: error.resolvedWorkspaceRoot,\n      };\n    case \"WorkspacePathNotFileError\":\n      return { failure: \"path_not_file\", resolvedPath: error.resolvedPath };\n    case \"WorkspaceBinaryFileError\":\n      return { failure: \"binary_file\", resolvedPath: error.resolvedPath };\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nfunction isThreadDetailEvent(event: OrchestrationEvent): event is Extract<\n  OrchestrationEvent,\n  {\n    type:\n      | \"thread.message-sent\"\n      | \"thread.proposed-plan-upserted\"\n      | \"thread.activity-appended\"\n      | \"thread.turn-diff-completed\"\n      | \"thread.reverted\"\n      | \"thread.session-set\";\n  }\n> {\n  return (\n    event.type === \"thread.message-sent\" ||\n    event.type === \"thread.proposed-plan-upserted\" ||\n    event.type === \"thread.activity-appended\" ||\n    event.type === \"thread.turn-diff-completed\" ||\n    event.type === \"thread.reverted\" ||\n    event.type === \"thread.session-set\"\n  );\n}\n\nconst PROVIDER_STATUS_DEBOUNCE_MS = 200;\n\n// When a resuming client's cursor is more than this many events behind the\n// current head, skip the per-event catch-up replay and send a fresh shell\n// snapshot instead. Replaying each intervening event costs a shell refetch;\n// past this gap a single O(active-threads) snapshot is cheaper and bounded.\n// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).\nconst SHELL_RESUME_MAX_GAP = 1_000;\n\n// Same bound for thread resume. The replay reads the *global* event range and\n// filters per-thread afterwards, so a stale cursor far behind the head would\n// otherwise decode every intervening event's payload — reconnects with cursors\n// hundreds of thousands of events behind have OOM-killed servers on large\n// databases. Past this gap the client is reset with a fresh thread snapshot.\nconst THREAD_RESUME_MAX_GAP = 1_000;\n\nfunction toAuthAccessStreamEvent(\n  change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,\n  revision: number,\n  currentSessionId: AuthSessionId,\n): AuthAccessStreamEvent {\n  switch (change.type) {\n    case \"pairingLinkUpserted\":\n      return {\n        version: 1,\n        revision,\n        type: \"pairingLinkUpserted\",\n        payload: change.pairingLink,\n      };\n    case \"pairingLinkRemoved\":\n      return {\n        version: 1,\n        revision,\n        type: \"pairingLinkRemoved\",\n        payload: { id: change.id },\n      };\n    case \"clientUpserted\":\n      return {\n        version: 1,\n        revision,\n        type: \"clientUpserted\",\n        payload: {\n          ...change.clientSession,\n          current: change.clientSession.sessionId === currentSessionId,\n        },\n      };\n    case \"clientRemoved\":\n      return {\n        version: 1,\n        revision,\n        type: \"clientRemoved\",\n        payload: { sessionId: change.sessionId },\n      };\n  }\n}\n\n// agentlink fork: RPCs whose subsystem was cut from this build stay\n// registered so the WS group still satisfies `WsRpcGroup`, but every call\n// fails fast with a typed error instead of reaching missing services.\nclass UnsupportedRpcError extends Schema.TaggedErrorClass<UnsupportedRpcError>()(\n  \"UnsupportedRpcError\",\n  {\n    method: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `RPC method '${this.method}' is unsupported in this build.`;\n  }\n}\n\n// Streaming RPCs among the cut set; everything else returns a failing Effect.\nconst UNSUPPORTED_STREAM_METHODS = new Set<string>([\n  WS_METHODS.cloudInstallRelayClient,\n  WS_METHODS.gitRunStackedAction,\n  WS_METHODS.previewAutomationConnect,\n  WS_METHODS.serverUpdateServerWithProgress,\n  WS_METHODS.subscribeDiscoveredLocalServers,\n  WS_METHODS.subscribePreviewEvents,\n  WS_METHODS.subscribeResourceTelemetry,\n]);\n\ntype WsRpcs = typeof WsRpcGroup extends RpcGroup.RpcGroup<infer Rpcs> ? Rpcs : never;\n\n/**\n * Generic stub value: each usage below reads `unsupportedRpc<Tag>` with an\n * explicit tag type argument, which pins the value to that RPC's\n * `HandlerFrom` type. At runtime every invocation fails with a typed\n * `UnsupportedRpcError` — a failing `Stream` for streaming RPCs and a\n * failing `Effect` otherwise.\n */\nconst unsupportedRpc = ((<Tag extends WsRpcs[\"_tag\"]>(): RpcGroup.HandlerFrom<WsRpcs, Tag> =>\n  ((method: string) =>\n    UNSUPPORTED_STREAM_METHODS.has(method)\n      ? Stream.fail(new UnsupportedRpcError({ method }))\n      : new UnsupportedRpcError({ method })) as RpcGroup.HandlerFrom<WsRpcs, Tag>) as () => unknown)();\n\n// Exported for the hub tunnel bridge (tunnel/bridge.ts): a tunnel session\n// is the same RPC group over an envelope-decrypting socket instead of the\n// HTTP-upgraded one.\nexport const wsRpcServices = Effect.gen(function* () {\n  return {\n    crypto: yield* Crypto.Crypto,\n    projectionSnapshotQuery: yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery,\n    orchestrationEngine: yield* OrchestrationEngine.OrchestrationEngineService,\n    providerRuntimeIngestion:\n      yield* ProviderRuntimeIngestion.ProviderRuntimeIngestionService,\n    keybindings: yield* Keybindings.Keybindings,\n    externalLauncher: yield* ExternalLauncher.ExternalLauncher,\n    providerRegistry: yield* ProviderRegistry.ProviderRegistry,\n    providerAdapterRegistry: yield* ProviderAdapterRegistry.ProviderAdapterRegistry,\n    providerSessionDirectory: yield* ProviderSessionDirectory.ProviderSessionDirectory,\n    providerService: yield* ProviderService.ProviderService,\n    config: yield* ServerConfig.ServerConfig,\n    lifecycleEvents: yield* ServerLifecycleEvents.ServerLifecycleEvents,\n    serverSettings: yield* ServerSettings.ServerSettingsService,\n    startup: yield* ServerRuntimeStartup.ServerRuntimeStartup,\n    workspaceEntries: yield* WorkspaceEntries.WorkspaceEntries,\n    workspaceFileSystem: yield* WorkspaceFileSystem.WorkspaceFileSystem,\n    gitWorkspace: yield* GitWorkspace.GitWorkspace,\n    terminalManager: yield* TerminalManager.TerminalManager,\n    serverEnvironment: yield* ServerEnvironment.ServerEnvironment,\n    backgroundPolicy: yield* BackgroundPolicy.BackgroundPolicy,\n    serverAuth: yield* EnvironmentAuth.EnvironmentAuth,\n    bootstrapCredentials: yield* PairingGrantStore.PairingGrantStore,\n    sessions: yield* SessionStore.SessionStore,\n  };\n});\n\nexport const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>\n  WsRpcGroup.toLayer(\n    Effect.gen(function* () {\n      const currentSessionId = currentSession.sessionId;\n      const {\n        crypto,\n        projectionSnapshotQuery,\n        orchestrationEngine,\n        providerRuntimeIngestion,\n        keybindings,\n        externalLauncher,\n        providerRegistry,\n        providerAdapterRegistry,\n        providerSessionDirectory,\n        providerService,\n        config,\n        lifecycleEvents,\n        serverSettings,\n        startup,\n        workspaceEntries,\n        workspaceFileSystem,\n        gitWorkspace,\n        terminalManager,\n        serverEnvironment,\n        backgroundPolicy,\n        serverAuth,\n        bootstrapCredentials,\n        sessions,\n      } = yield* wsRpcServices;\n      const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;\n      const rpcClientIds = yield* Ref.make(new Set<RpcClientId>());\n      yield* Effect.addFinalizer(() =>\n        Ref.get(rpcClientIds).pipe(\n          Effect.flatMap((clientIds) =>\n            Effect.forEach(\n              clientIds,\n              (clientId) => backgroundPolicy.removeRpcClient(currentSessionId, clientId),\n              {\n                discard: true,\n              },\n            ),\n          ),\n          Effect.ignore,\n        ),\n      );\n      const authorizationError = (requiredScope: AuthEnvironmentScope) =>\n        new EnvironmentAuthorizationError({\n          message: `The authenticated token is missing required scope: ${requiredScope}.`,\n          requiredScope,\n        });\n      const voiceInputUnavailable = (message: string) => new VoiceInputUnavailableError({ message });\n      const resolveVoiceInput = (threadId: ThreadId) =>\n        providerSessionDirectory.getBinding(threadId).pipe(\n          Effect.mapError((cause) => voiceInputUnavailable(cause.message)),\n          Effect.flatMap((binding) =>\n            Option.match(binding, {\n              onNone: () =>\n                Effect.fail(voiceInputUnavailable(\"Start a Codex conversation before using voice input.\")),\n              onSome: (value) =>\n                value.provider !== \"codex\"\n                  ? Effect.fail(voiceInputUnavailable(\"Voice input is currently available for Codex only.\"))\n                  : providerAdapterRegistry.getByInstance(value.providerInstanceId!).pipe(\n                      Effect.mapError((cause) => voiceInputUnavailable(cause.message)),\n                    ),\n            }),\n          ),\n          Effect.flatMap((adapter) =>\n            adapter.capabilities.realtimeVoiceInput === true && adapter.realtimeVoiceInput\n              ? Effect.succeed(adapter.realtimeVoiceInput)\n              : Effect.fail(\n                  voiceInputUnavailable(\"Update this AgentLink daemon to use Codex voice input.\"),\n                ),\n          ),\n        );\n      const authorizeEffect = <A, E, R>(\n        requiredScope: AuthEnvironmentScope,\n        effect: Effect.Effect<A, E, R>,\n      ): Effect.Effect<A, E | EnvironmentAuthorizationError, R> =>\n        currentSession.scopes.includes(requiredScope)\n          ? effect\n          : Effect.fail(authorizationError(requiredScope));\n      const authorizeStream = <A, E, R>(\n        requiredScope: AuthEnvironmentScope,\n        stream: Stream.Stream<A, E, R>,\n      ): Stream.Stream<A, E | EnvironmentAuthorizationError, R> =>\n        currentSession.scopes.includes(requiredScope)\n          ? stream\n          : Stream.fail(authorizationError(requiredScope));\n      const observeRpcEffect = <A, E, R>(\n        method: string,\n        effect: Effect.Effect<A, E, R>,\n        traceAttributes?: Readonly<Record<string, unknown>>,\n      ) =>\n        instrumentRpcEffect(\n          method,\n          authorizeEffect(requiredScopeForRpcMethod(method), effect),\n          traceAttributes,\n        );\n      const observeRpcStream = <A, E, R>(\n        method: string,\n        stream: Stream.Stream<A, E, R>,\n        traceAttributes?: Readonly<Record<string, unknown>>,\n      ) =>\n        instrumentRpcStream(\n          method,\n          authorizeStream(requiredScopeForRpcMethod(method), stream),\n          traceAttributes,\n        );\n      const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(\n        method: string,\n        effect: Effect.Effect<\n          Stream.Stream<A, StreamError, StreamContext>,\n          EffectError,\n          EffectContext\n        >,\n        traceAttributes?: Readonly<Record<string, unknown>>,\n      ) =>\n        instrumentRpcStreamEffect(\n          method,\n          authorizeEffect(requiredScopeForRpcMethod(method), effect),\n          traceAttributes,\n        );\n      const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>\n        isOrchestrationDispatchCommandError(cause)\n          ? cause\n          : new OrchestrationDispatchCommandError({\n              message: cause instanceof Error ? cause.message : fallbackMessage,\n              cause,\n            });\n      const randomUUID = crypto.randomUUIDv4.pipe(\n        Effect.mapError((cause) =>\n          toDispatchCommandError(cause, \"Failed to generate orchestration command identifier.\"),\n        ),\n      );\n      const serverCommandId = (tag: string) =>\n        randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));\n\n      const loadAuthAccessSnapshot = () =>\n        Effect.all({\n          pairingLinks: serverAuth.listPairingLinks(),\n          clientSessions: serverAuth.listClientSessions(currentSessionId),\n        }).pipe(\n          Effect.mapError(\n            (error) =>\n              new AuthAccessStreamError({\n                message: error.message,\n              }),\n          ),\n        );\n\n      const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {\n        const error = Cause.squash(cause);\n        return isOrchestrationDispatchCommandError(error)\n          ? error\n          : new OrchestrationDispatchCommandError({\n              message:\n                error instanceof Error ? error.message : \"Failed to bootstrap thread turn start.\",\n              cause,\n            });\n      };\n\n      const toShellStreamEvent = (\n        event: OrchestrationEvent,\n      ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {\n        switch (event.type) {\n          case \"project.created\":\n          case \"project.meta-updated\":\n            return projectUpsertOrRemove(event.payload.projectId, event.sequence);\n          case \"project.deleted\":\n            return Effect.succeed(\n              Option.some({\n                kind: \"project-removed\" as const,\n                sequence: event.sequence,\n                projectId: event.payload.projectId,\n              }),\n            );\n          case \"thread.deleted\":\n          case \"thread.archived\":\n            return Effect.succeed(\n              Option.some({\n                kind: \"thread-removed\" as const,\n                sequence: event.sequence,\n                threadId: event.payload.threadId,\n              }),\n            );\n          case \"thread.unarchived\":\n            return threadUpsertOrRemove(event.payload.threadId, event.sequence);\n          default:\n            if (event.aggregateKind !== \"thread\") {\n              return Effect.succeed(Option.none());\n            }\n            return threadUpsertOrRemove(ThreadId.make(event.aggregateId), event.sequence);\n        }\n      };\n\n      // Coalescing makes each projection read represent every event for that\n      // aggregate in the current window. Retry a typed persistence failure once\n      // so a brief read failure cannot strand the shell at its previous state.\n      // If both attempts fail, log and drop the stream item; treating an error as\n      // a missing row would incorrectly remove a still-active aggregate.\n      const retryShellProjectionRead = <A, E>(\n        aggregateKind: \"project\" | \"thread\",\n        aggregateId: string,\n        read: Effect.Effect<A, E>,\n      ): Effect.Effect<Option.Option<A>, never, never> =>\n        read.pipe(\n          Effect.retry({ times: 1 }),\n          Effect.map(Option.some),\n          Effect.tapError((error) =>\n            Effect.logWarning(\"orchestration shell projection refetch failed\", {\n              aggregateKind,\n              aggregateId,\n              error,\n            }),\n          ),\n          Effect.orElseSucceed(() => Option.none()),\n        );\n\n      const projectUpsertOrRemove = (\n        projectId: ProjectId,\n        sequence: number,\n      ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>\n        retryShellProjectionRead(\n          \"project\",\n          projectId,\n          projectionSnapshotQuery.getProjectShellById(projectId),\n        ).pipe(\n          Effect.map(\n            Option.flatMap((project) =>\n              Option.match(project, {\n                onNone: () =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"project-removed\" as const,\n                    sequence,\n                    projectId,\n                  }),\n                onSome: (nextProject) =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"project-upserted\" as const,\n                    sequence,\n                    project: nextProject,\n                  }),\n              }),\n            ),\n          ),\n        );\n\n      // Refetch a thread's shell and emit an upsert if it is still active, or a\n      // `thread-removed` if the projection has no active row for it. Emitting a\n      // removal on a `none` (rather than dropping the event) is what keeps\n      // coalescing correct: when a burst collapses a `thread.deleted`/`archived`\n      // into a later refetchable event for the same thread, the refetch returns\n      // `none` for the now-inactive row and this still tells the sidebar to drop\n      // it. A `thread-removed` the client does not have is a harmless no-op. The\n      // projection commits in the same transaction before the event publishes,\n      // so a `none` reliably means the thread is deleted or archived, not\n      // not-yet-persisted.\n      const threadUpsertOrRemove = (\n        threadId: ThreadId,\n        sequence: number,\n      ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>\n        retryShellProjectionRead(\n          \"thread\",\n          threadId,\n          projectionSnapshotQuery.getThreadShellById(threadId),\n        ).pipe(\n          Effect.map(\n            Option.flatMap((thread) =>\n              Option.match(thread, {\n                onNone: () =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"thread-removed\" as const,\n                    sequence,\n                    threadId,\n                  }),\n                onSome: (nextThread) =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"thread-upserted\" as const,\n                    sequence,\n                    thread: nextThread,\n                  }),\n              }),\n            ),\n          ),\n        );\n\n      // Turn a batch of domain events into shell stream items, coalescing by\n      // aggregate first. `toShellStreamEvent` re-reads the *current* projected\n      // shell for an aggregate, so within a batch only the latest event per\n      // aggregate matters: a burst of streaming `thread.message-sent` deltas for\n      // one thread collapses into a single shell refetch, and an unrelated\n      // `thread.created` in the same batch is never stuck behind those DB reads.\n      //\n      // Input events arrive in ascending sequence; we keep the last (highest\n      // sequence) event per aggregate, then re-sort ascending before emitting so\n      // the client — which applies shell items strictly by increasing sequence\n      // and drops any `sequence <= snapshotSequence` — never skips a coalesced\n      // item. The refetch runs with bounded concurrency (order-preserving).\n      const SHELL_REFETCH_CONCURRENCY = 8;\n      const coalesceShellEvents = (\n        events: ReadonlyArray<OrchestrationEvent>,\n      ): Effect.Effect<ReadonlyArray<OrchestrationShellStreamEvent>, never, never> =>\n        Effect.gen(function* () {\n          if (events.length === 0) {\n            return [];\n          }\n          const latestByAggregate = new Map<string, OrchestrationEvent>();\n          for (const event of events) {\n            latestByAggregate.set(`${event.aggregateKind}:${event.aggregateId}`, event);\n          }\n          const survivors = Array.from(latestByAggregate.values()).sort(\n            (left, right) => left.sequence - right.sequence,\n          );\n          const shellEvents = yield* Effect.forEach(survivors, toShellStreamEvent, {\n            concurrency: SHELL_REFETCH_CONCURRENCY,\n          });\n          return shellEvents.flatMap((option) => (Option.isSome(option) ? [option.value] : []));\n        });\n\n      // Small time/size window over which to coalesce shell events. The window\n      // bounds the worst-case added latency for a brand-new thread to appear in\n      // the sidebar (imperceptible), while collapsing high-frequency streaming\n      // traffic so it can't serialize the shell stream behind per-event DB reads.\n      const SHELL_COALESCE_WINDOW = Duration.millis(50);\n      const SHELL_COALESCE_MAX_CHUNK = 512;\n      const coalesceShellStream = <E, R>(\n        stream: Stream.Stream<OrchestrationEvent, E, R>,\n      ): Stream.Stream<OrchestrationShellStreamEvent, E, R> =>\n        stream.pipe(\n          Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),\n          Stream.mapEffect(coalesceShellEvents),\n          Stream.flatMap((items) => Stream.fromIterable(items)),\n        );\n\n      type ShellLiveInput =\n        | { readonly kind: \"event\"; readonly event: OrchestrationEvent }\n        | { readonly kind: \"synchronized\" };\n\n      // A completion marker is queued alongside raw live events so it cannot\n      // overtake an event still waiting in the coalescing window. Split each\n      // batch at markers and coalesce only the event segments on either side.\n      const coalesceShellLiveInputs = (\n        inputs: ReadonlyArray<ShellLiveInput>,\n      ): Effect.Effect<ReadonlyArray<OrchestrationShellStreamItem>, never, never> =>\n        Effect.gen(function* () {\n          const output: Array<OrchestrationShellStreamItem> = [];\n          let pendingEvents: Array<OrchestrationEvent> = [];\n\n          for (const input of inputs) {\n            if (input.kind === \"event\") {\n              pendingEvents.push(input.event);\n              continue;\n            }\n\n            output.push(...(yield* coalesceShellEvents(pendingEvents)));\n            pendingEvents = [];\n            output.push({ kind: \"synchronized\" });\n          }\n\n          output.push(...(yield* coalesceShellEvents(pendingEvents)));\n          return output;\n        });\n\n      const coalesceShellLiveStream = <E, R>(\n        stream: Stream.Stream<ShellLiveInput, E, R>,\n      ): Stream.Stream<OrchestrationShellStreamItem, E, R> =>\n        stream.pipe(\n          Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),\n          Stream.mapEffect(coalesceShellLiveInputs),\n          Stream.flatMap((items) => Stream.fromIterable(items)),\n        );\n\n      // agentlink fork: worktree provisioning and setup-script execution were\n      // removed with the git/terminal subsystems. Bootstrap now only supports\n      // `createThread`; `prepareWorktree` / `runSetupScript` payloads are\n      // ignored.\n      const dispatchBootstrapTurnStart = (\n        command: Extract<OrchestrationCommand, { type: \"thread.turn.start\" }>,\n      ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>\n        Effect.gen(function* () {\n          const bootstrap = command.bootstrap;\n          const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;\n          let createdThread = false;\n\n          const bootstrapProgram = Effect.gen(function* () {\n            if (bootstrap?.createThread) {\n              yield* orchestrationEngine.dispatch({\n                type: \"thread.create\",\n                commandId: yield* serverCommandId(\"bootstrap-thread-create\"),\n                threadId: command.threadId,\n                projectId: bootstrap.createThread.projectId,\n                title: bootstrap.createThread.title,\n                modelSelection: bootstrap.createThread.modelSelection,\n                runtimeMode: bootstrap.createThread.runtimeMode,\n                interactionMode: bootstrap.createThread.interactionMode,\n                branch: bootstrap.createThread.branch,\n                worktreePath: bootstrap.createThread.worktreePath,\n                createdAt: bootstrap.createThread.createdAt,\n              });\n              createdThread = true;\n            }\n\n            return yield* orchestrationEngine.dispatch(finalTurnStartCommand);\n          });\n\n          return yield* bootstrapProgram.pipe(\n            Effect.catchCause((cause) => {\n              const dispatchError = toBootstrapDispatchCommandCauseError(cause);\n              if (Cause.hasInterruptsOnly(cause)) {\n                return Effect.fail(dispatchError);\n              }\n              return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));\n            }),\n          );\n\n          function cleanupCreatedThread() {\n            return createdThread\n              ? serverCommandId(\"bootstrap-thread-delete\").pipe(\n                  Effect.flatMap((commandId) =>\n                    orchestrationEngine.dispatch({\n                      type: \"thread.delete\",\n                      commandId,\n                      threadId: command.threadId,\n                    }),\n                  ),\n                  Effect.ignoreCause({ log: true }),\n                )\n              : Effect.void;\n          }\n        });\n\n      const dispatchNormalizedCommand = (\n        normalizedCommand: OrchestrationCommand,\n      ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {\n        const dispatchEffect =\n          normalizedCommand.type === \"thread.turn.start\" && normalizedCommand.bootstrap\n            ? dispatchBootstrapTurnStart(normalizedCommand)\n            : orchestrationEngine\n                .dispatch(normalizedCommand)\n                .pipe(\n                  Effect.mapError((cause) =>\n                    toDispatchCommandError(cause, \"Failed to dispatch orchestration command\"),\n                  ),\n                );\n\n        const guardedDispatchEffect =\n          normalizedCommand.type === \"thread.turn.start\" &&\n          normalizedCommand.bootstrap === undefined\n            ? providerRuntimeIngestion\n                .reconcileThread(normalizedCommand.threadId, { requireWritable: true })\n                .pipe(\n                  Effect.mapError((cause) =>\n                    toDispatchCommandError(cause, \"Failed to reconcile provider thread\"),\n                  ),\n                  Effect.andThen(dispatchEffect),\n                )\n            : dispatchEffect;\n\n        return startup\n          .enqueueCommand(guardedDispatchEffect)\n          .pipe(\n            Effect.mapError((cause) =>\n              toDispatchCommandError(cause, \"Failed to dispatch orchestration command\"),\n            ),\n          );\n      };\n\n      const loadServerConfig = Effect.gen(function* () {\n        const keybindingsConfig = yield* keybindings.loadConfigState;\n        const providers = yield* providerRegistry.getProviders;\n        const settings = ServerSettings.redactServerSettingsForClient(\n          yield* serverSettings.getSettings,\n        );\n        const environment = yield* serverEnvironment.getDescriptor;\n        const auth = yield* serverAuth.getDescriptor();\n\n        return {\n          environment,\n          auth,\n          cwd: config.cwd,\n          keybindingsConfigPath: config.keybindingsConfigPath,\n          keybindings: keybindingsConfig.keybindings,\n          issues: keybindingsConfig.issues,\n          providers,\n          availableEditors: yield* resolveAvailableEditorsForConfig(\n            externalLauncher.resolveAvailableEditors(),\n          ),\n          observability: {\n            logsDirectoryPath: config.logsDir,\n            localTracingEnabled: true,\n            ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),\n            otlpTracesEnabled: config.otlpTracesUrl !== undefined,\n            ...(config.otlpMetricsUrl !== undefined\n              ? { otlpMetricsUrl: config.otlpMetricsUrl }\n              : {}),\n            otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,\n          },\n          settings,\n          shellResumeCompletionMarker: true,\n          threadResumeCompletionMarker: true,\n        };\n      });\n\n      return WsRpcGroup.of({\n        [WS_METHODS.voiceInputStart]: ({ threadId }) =>\n          observeRpcEffect(\n            WS_METHODS.voiceInputStart,\n            resolveVoiceInput(threadId).pipe(\n              Effect.flatMap((voice) => voice.start(threadId)),\n              Effect.mapError((cause) =>\n                cause instanceof VoiceInputUnavailableError\n                  ? cause\n                  : voiceInputUnavailable(cause.message),\n              ),\n              Effect.as({}),\n            ),\n            { \"rpc.aggregate\": \"voice-input\" },\n          ),\n        [WS_METHODS.voiceInputAppendAudio]: ({\n          threadId,\n          data,\n          sampleRate,\n          numChannels,\n          samplesPerChannel,\n        }) =>\n          observeRpcEffect(\n            WS_METHODS.voiceInputAppendAudio,\n            resolveVoiceInput(threadId).pipe(\n              Effect.flatMap((voice) =>\n                voice.appendAudio(threadId, {\n                  data,\n                  sampleRate,\n                  numChannels,\n                  ...(samplesPerChannel !== undefined ? { samplesPerChannel } : {}),\n                }),\n              ),\n              Effect.mapError((cause) =>\n                cause instanceof VoiceInputUnavailableError\n                  ? cause\n                  : voiceInputUnavailable(cause.message),\n              ),\n              Effect.as({}),\n            ),\n            { \"rpc.aggregate\": \"voice-input\" },\n          ),\n        [WS_METHODS.voiceInputStop]: ({ threadId }) =>\n          observeRpcEffect(\n            WS_METHODS.voiceInputStop,\n            resolveVoiceInput(threadId).pipe(\n              Effect.flatMap((voice) => voice.stop(threadId)),\n              Effect.mapError((cause) =>\n                cause instanceof VoiceInputUnavailableError\n                  ? cause\n                  : voiceInputUnavailable(cause.message),\n              ),\n              Effect.as({}),\n            ),\n            { \"rpc.aggregate\": \"voice-input\" },\n          ),\n        [WS_METHODS.subscribeVoiceInputTranscript]: ({ threadId }) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeVoiceInputTranscript,\n            resolveVoiceInput(threadId).pipe(\n              Effect.as(\n                providerService.streamEvents.pipe(\n                  Stream.filter(\n                    (\n                      event,\n                    ): event is Extract<\n                      ProviderRuntimeEvent,\n                      {\n                        type:\n                          | \"thread.realtime.transcript.delta\"\n                          | \"thread.realtime.transcript.done\";\n                      }\n                    > =>\n                      event.threadId === threadId &&\n                      (event.type === \"thread.realtime.transcript.delta\" ||\n                        event.type === \"thread.realtime.transcript.done\"),\n                  ),\n                  Stream.map((event) => ({\n                    eventId: event.eventId,\n                    role: event.payload.role,\n                    text: event.type === \"thread.realtime.transcript.delta\"\n                      ? event.payload.delta\n                      : event.payload.text,\n                    final: event.type === \"thread.realtime.transcript.done\",\n                  })),\n                ),\n              ),\n            ),\n            { \"rpc.aggregate\": \"voice-input\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.dispatchCommand,\n            Effect.gen(function* () {\n              const normalizedCommand = yield* normalizeDispatchCommand(command);\n              const shouldStopSessionAfterArchive =\n                normalizedCommand.type === \"thread.archive\"\n                  ? yield* projectionSnapshotQuery\n                      .getThreadShellById(normalizedCommand.threadId)\n                      .pipe(\n                        Effect.map(\n                          Option.match({\n                            onNone: () => false,\n                            onSome: (thread) =>\n                              thread.session !== null && thread.session.status !== \"stopped\",\n                          }),\n                        ),\n                        Effect.orElseSucceed(() => false),\n                      )\n                  : false;\n              const result = yield* dispatchNormalizedCommand(normalizedCommand);\n              if (normalizedCommand.type === \"thread.archive\") {\n                if (shouldStopSessionAfterArchive) {\n                  yield* Effect.gen(function* () {\n                    const stopCommand = yield* normalizeDispatchCommand({\n                      type: \"thread.session.stop\",\n                      commandId: CommandId.make(\n                        `session-stop-for-archive:${normalizedCommand.commandId}`,\n                      ),\n                      threadId: normalizedCommand.threadId,\n                      createdAt: yield* nowIso,\n                    });\n\n                    yield* dispatchNormalizedCommand(stopCommand);\n                  }).pipe(\n                    Effect.catchCause((cause) =>\n                      Effect.logWarning(\"failed to stop provider session during archive\", {\n                        threadId: normalizedCommand.threadId,\n                        cause,\n                      }),\n                    ),\n                  );\n                }\n              }\n              return result;\n            }).pipe(\n              Effect.mapError((cause) =>\n                isOrchestrationDispatchCommandError(cause)\n                  ? cause\n                  : new OrchestrationDispatchCommandError({\n                      message: \"Failed to dispatch orchestration command\",\n                      cause,\n                    }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.searchThreads]: (input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.searchThreads,\n            projectionSnapshotQuery.searchThreads(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new OrchestrationSearchThreadsError({\n                    message: \"Failed to search threads\",\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.subscribeShell]: (input) =>\n          observeRpcStreamEffect(\n            ORCHESTRATION_WS_METHODS.subscribeShell,\n            Effect.gen(function* () {\n              // Coalesce the live shell stream per aggregate over a small window\n              // so bursts of high-frequency events (streaming message deltas,\n              // activity appends) collapse into a single shell refetch and never\n              // serialize a brand-new thread's `thread.created` behind hundreds\n              // of per-event DB reads. See coalesceShellStream.\n              // Attach live delivery into a scope-bound buffer BEFORE loading any\n              // snapshot or draining catch-up, otherwise an event published while\n              // the snapshot query is in flight is lost (it is past the snapshot's\n              // sequence but the live subscription is not attached yet). Every\n              // path below emits from this same buffered live tail. Overlapping\n              // events are deduped by sequence on the client.\n              const liveBuffer = yield* Queue.unbounded<ShellLiveInput>();\n              yield* Effect.forkScoped(\n                orchestrationEngine.streamDomainEvents.pipe(\n                  Stream.runForEach((event) =>\n                    Queue.offer(liveBuffer, { kind: \"event\" as const, event }),\n                  ),\n                ),\n                { startImmediately: true },\n              );\n              const bufferedLiveStream = coalesceShellLiveStream(Stream.fromQueue(liveBuffer));\n\n              const loadSnapshot = projectionSnapshotQuery.getShellSnapshot().pipe(\n                Effect.tapError((cause) =>\n                  Effect.logError(\"orchestration shell snapshot load failed\", { cause }),\n                ),\n                Effect.mapError(\n                  (cause) =>\n                    new OrchestrationGetSnapshotError({\n                      message: \"Failed to load orchestration shell snapshot\",\n                      cause,\n                    }),\n                ),\n              );\n\n              // Offer the completion marker into the same queue as live events.\n              // Anything buffered while snapshot/replay work was in flight is\n              // therefore delivered before the client is told it is synchronized.\n              const synchronizedThenLive =\n                input.requestCompletionMarker === true\n                  ? Stream.concat(\n                      Stream.fromEffect(\n                        Queue.offer(liveBuffer, { kind: \"synchronized\" as const }).pipe(\n                          Effect.andThen(Queue.takeAll(liveBuffer)),\n                          Effect.flatMap(coalesceShellLiveInputs),\n                        ),\n                      ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),\n                      bufferedLiveStream,\n                    )\n                  : bufferedLiveStream;\n\n              // When the client already holds a shell snapshot (cached, or loaded\n              // over HTTP) it passes that snapshot's sequence, and we resume by\n              // replaying shell events after it instead of re-sending the whole\n              // projects/threads list over the socket. If the client is too far\n              // behind, we fall back to a fresh snapshot instead of an unbounded\n              // replay (see below).\n              if (input.afterSequence !== undefined) {\n                const afterSequence = input.afterSequence;\n                const headSequence = yield* orchestrationEngine.latestSequence;\n                const replayGap = headSequence - afterSequence;\n                // Gap too large: replaying every intervening event (each a shell\n                // refetch) is far more expensive than a single O(active-threads)\n                // snapshot. A cursor ahead of this engine's authoritative state\n                // is also invalid, so reset it with a snapshot. Send the snapshot\n                // followed by the buffered live tail, exactly as the\n                // no-afterSequence path does.\n                if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) {\n                  const snapshot = yield* loadSnapshot;\n                  return Stream.concat(\n                    Stream.make({ kind: \"snapshot\" as const, snapshot }),\n                    synchronizedThenLive,\n                  );\n                }\n                const catchUpStream = coalesceShellStream(\n                  // Replay only through the head captured above. Newer events\n                  // are already covered by the live subscription, so this bound\n                  // cannot chase a moving event-store head or grow the live\n                  // buffer indefinitely while waiting for an empty page.\n                  orchestrationEngine.readEvents(afterSequence, replayGap),\n                ).pipe(\n                  Stream.mapError(\n                    (cause) =>\n                      new OrchestrationGetSnapshotError({\n                        message: \"Failed to replay orchestration shell events\",\n                        cause,\n                      }),\n                  ),\n                );\n                return Stream.concat(catchUpStream, synchronizedThenLive);\n              }\n\n              const snapshot = yield* loadSnapshot;\n              return Stream.concat(\n                Stream.make({\n                  kind: \"snapshot\" as const,\n                  snapshot,\n                }),\n                synchronizedThenLive,\n              );\n            }),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,\n            projectionSnapshotQuery.getArchivedShellSnapshot().pipe(\n              Effect.tapError((cause) =>\n                Effect.logError(\"orchestration archived shell snapshot load failed\", { cause }),\n              ),\n              Effect.mapError(\n                (cause) =>\n                  new OrchestrationGetSnapshotError({\n                    message: \"Failed to load archived orchestration shell snapshot\",\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>\n          observeRpcStreamEffect(\n            ORCHESTRATION_WS_METHODS.subscribeThread,\n            Effect.gen(function* () {\n              const isThisThreadDetailEvent = (event: OrchestrationEvent) =>\n                event.aggregateKind === \"thread\" &&\n                event.aggregateId === input.threadId &&\n                isThreadDetailEvent(event);\n\n              const liveStream = orchestrationEngine.streamDomainEvents.pipe(\n                Stream.filter(isThisThreadDetailEvent),\n                Stream.map((event) => ({\n                  kind: \"event\" as const,\n                  event: projectActivityEvent(event),\n                })),\n              );\n\n              // Attach live delivery before reading either replay or snapshot state.\n              // Otherwise an event published while the snapshot is loading is lost.\n              const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();\n              yield* Effect.forkScoped(\n                liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),\n              );\n              const bufferedLiveStream = Stream.fromQueue(liveBuffer);\n\n              yield* providerRuntimeIngestion.reconcileThread(input.threadId).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new OrchestrationGetSnapshotError({\n                      message: cause.message,\n                      cause,\n                    }),\n                ),\n              );\n\n              // When the client already loaded the snapshot over HTTP it passes\n              // that snapshot's sequence, and we resume the live subscription by\n              // replaying persisted events after it instead of re-sending the\n              // (potentially multi-KB) snapshot frame over the socket.\n              //\n              // The live PubSub subscription must be attached *before* draining\n              // the catch-up replay, otherwise events published during the replay\n              // window are dropped (they are past the persisted tail the replay\n              // read, but the live stream is not yet subscribed). So fork the\n              // live stream into a buffer bound to this stream's scope, then emit\n              // catch-up followed by the buffered/ongoing live events. Overlapping\n              // events are deduped by sequence on the client.\n              //\n              // The replay is bounded to the projection head captured below. The\n              // catch-up range is normally tiny (a fresh HTTP snapshot sequence),\n              // but a stale cached cursor can sit hundreds of thousands of global\n              // events behind — replaying that decodes every intervening event\n              // (including every other thread's tool payloads) only to discard\n              // almost all of them, which has OOM-killed servers on large\n              // databases. A truncated replay would silently drop this thread's\n              // events, so past the gap cap we reset the client with a fresh\n              // thread snapshot instead, exactly like subscribeShell above.\n              if (input.afterSequence !== undefined) {\n                const afterSequence = input.afterSequence;\n                const headSequence = yield* orchestrationEngine.latestSequence;\n                const replayGap = headSequence - afterSequence;\n                if (replayGap >= 0 && replayGap <= THREAD_RESUME_MAX_GAP) {\n                  const catchUpStream = orchestrationEngine\n                    .readEvents(afterSequence, replayGap)\n                    .pipe(\n                      Stream.filter(isThisThreadDetailEvent),\n                      Stream.map((event) => ({\n                        kind: \"event\" as const,\n                        event: projectActivityEvent(event),\n                      })),\n                      Stream.mapError(\n                        (cause) =>\n                          new OrchestrationGetSnapshotError({\n                            message: `Failed to replay thread ${input.threadId} events`,\n                            cause,\n                          }),\n                      ),\n                    );\n                  const afterCatchUp =\n                    input.requestCompletionMarker === true\n                      ? Stream.concat(\n                          Stream.fromEffect(\n                            Queue.offer(liveBuffer, { kind: \"synchronized\" as const }),\n                          ).pipe(Stream.drain),\n                          bufferedLiveStream,\n                        )\n                      : bufferedLiveStream;\n                  return Stream.concat(catchUpStream, afterCatchUp);\n                }\n                // Gap too large (or cursor ahead of authoritative state): fall\n                // through to the snapshot path so the client converges from a\n                // fresh thread detail instead of an unbounded replay.\n              }\n\n              const snapshot = yield* projectionSnapshotQuery\n                .getThreadDetailSnapshot(input.threadId)\n                .pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new OrchestrationGetSnapshotError({\n                        message: `Failed to load thread ${input.threadId}`,\n                        cause,\n                      }),\n                  ),\n                );\n\n              if (Option.isNone(snapshot)) {\n                return yield* new OrchestrationGetSnapshotError({\n                  message: `Thread ${input.threadId} was not found`,\n                  cause: input.threadId,\n                });\n              }\n\n              const afterSnapshot =\n                input.requestCompletionMarker === true\n                  ? Stream.concat(\n                      Stream.fromEffect(\n                        Queue.offer(liveBuffer, { kind: \"synchronized\" as const }),\n                      ).pipe(Stream.drain),\n                      bufferedLiveStream,\n                    )\n                  : bufferedLiveStream;\n              return Stream.concat(\n                Stream.make({\n                  kind: \"snapshot\" as const,\n                  snapshot: projectThreadDetailSnapshot(snapshot.value),\n                }),\n                afterSnapshot,\n              );\n            }),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [WS_METHODS.serverProbe]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverProbe, Effect.succeed({}), {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverGetConfig]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.portProxyList]: (_input) =>\n          observeRpcEffect(\n            WS_METHODS.portProxyList,\n            Effect.sync(() => ({ ports: PortProxy.listAuthorizedPorts() })),\n            { \"rpc.aggregate\": \"port-proxy\" },\n          ),\n        [WS_METHODS.portProxyAuthorize]: ({ port }) =>\n          observeRpcEffect(\n            WS_METHODS.portProxyAuthorize,\n            Effect.sync(() => ({ ports: PortProxy.authorizePort(port) })),\n            { \"rpc.aggregate\": \"port-proxy\" },\n          ),\n        [WS_METHODS.portProxyRevoke]: ({ port }) =>\n          observeRpcEffect(\n            WS_METHODS.portProxyRevoke,\n            Effect.sync(() => ({ ports: PortProxy.revokePort(port) })),\n            { \"rpc.aggregate\": \"port-proxy\" },\n          ),\n        [WS_METHODS.serverRefreshProviders]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverRefreshProviders,\n            (input.instanceId !== undefined\n              ? providerRegistry.refreshInstance(input.instanceId)\n              : providerRegistry.refresh()\n            ).pipe(Effect.map((providers) => ({ providers }))),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverUpdateProvider]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverUpdateProvider,\n            providerMaintenanceRunner.updateProvider(input),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverUpdateSettings]: ({ patch }) =>\n          observeRpcEffect(\n            WS_METHODS.serverUpdateSettings,\n            serverSettings\n              .updateSettings(patch)\n              .pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverUpsertKeybinding]: (rule) =>\n          observeRpcEffect(\n            WS_METHODS.serverUpsertKeybinding,\n            Effect.gen(function* () {\n              const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);\n              return { keybindings: keybindingsConfig, issues: [] };\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverRemoveKeybinding]: (rule) =>\n          observeRpcEffect(\n            WS_METHODS.serverRemoveKeybinding,\n            Effect.gen(function* () {\n              const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);\n              return { keybindings: keybindingsConfig, issues: [] };\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverGetSettings]: (_input) =>\n          observeRpcEffect(\n            WS_METHODS.serverGetSettings,\n            serverSettings.getSettings.pipe(\n              Effect.map(ServerSettings.redactServerSettingsForClient),\n            ),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverReportClientActivity]: (input, metadata) =>\n          Ref.update(rpcClientIds, (clientIds) => {\n            const next = new Set(clientIds);\n            next.add(RpcClientId.make(metadata.client.id));\n            return next;\n          }).pipe(\n            Effect.andThen(\n              observeRpcEffect(\n                WS_METHODS.serverReportClientActivity,\n                backgroundPolicy.reportClientActivity(\n                  currentSessionId,\n                  RpcClientId.make(metadata.client.id),\n                  input,\n                ),\n                { \"rpc.aggregate\": \"server\" },\n              ),\n            ),\n          ),\n        [WS_METHODS.serverReportHostPowerState]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverReportHostPowerState,\n            backgroundPolicy.reportHostPowerState(input),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverGetBackgroundPolicy]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverGetBackgroundPolicy, backgroundPolicy.snapshot, {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.projectsSearchEntries]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsSearchEntries,\n            workspaceEntries.search(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectSearchEntriesError({\n                    cwd: input.cwd,\n                    queryLength: input.query.length,\n                    limit: input.limit,\n                    ...projectEntriesFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsSearchContents]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsSearchContents,\n            workspaceEntries.searchContents(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectSearchContentsError({\n                    cwd: input.cwd,\n                    queryLength: input.query.length,\n                    limit: input.limit,\n                    ...projectEntriesFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsListEntries]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsListEntries,\n            workspaceEntries.list(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectListEntriesError({\n                    ...input,\n                    ...projectEntriesFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsReadFile]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsReadFile,\n            workspaceFileSystem.readFile(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectReadFileError({\n                    ...input,\n                    ...projectFileFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsWriteFile]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsWriteFile,\n            workspaceFileSystem.writeFile(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectWriteFileError({\n                    cwd: input.cwd,\n                    relativePath: input.relativePath,\n                    ...projectFileFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.shellOpenInEditor]: (input) =>\n          observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {\n            \"rpc.aggregate\": \"workspace\",\n          }),\n        [WS_METHODS.filesystemBrowse]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.filesystemBrowse,\n            workspaceEntries.browse(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new FilesystemBrowseError({\n                    ...input,\n                    ...filesystemBrowseFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.assetsCreateUrl]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.assetsCreateUrl,\n            Effect.gen(function* () {\n              if (input.resource._tag !== \"workspace-file\") {\n                return yield* issueAssetUrl({ resource: input.resource });\n              }\n              const thread = yield* projectionSnapshotQuery\n                .getThreadShellById(input.resource.threadId)\n                .pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new AssetWorkspaceContextResolutionError({\n                        resource: input.resource,\n                        cause,\n                      }),\n                  ),\n                );\n              if (Option.isNone(thread)) {\n                return yield* new AssetWorkspaceContextNotFoundError({\n                  resource: input.resource,\n                });\n              }\n              const project = yield* projectionSnapshotQuery\n                .getProjectShellById(thread.value.projectId)\n                .pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new AssetWorkspaceContextResolutionError({\n                        resource: input.resource,\n                        cause,\n                      }),\n                  ),\n                );\n              if (Option.isNone(project)) {\n                return yield* new AssetWorkspaceContextNotFoundError({\n                  resource: input.resource,\n                });\n              }\n              return yield* issueAssetUrl({\n                resource: input.resource,\n                workspaceRoot: thread.value.worktreePath ?? project.value.workspaceRoot,\n              });\n            }),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.subscribeServerConfig]: (_input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeServerConfig,\n            Effect.gen(function* () {\n              const keybindingsUpdates = keybindings.streamChanges.pipe(\n                Stream.map((event) => ({\n                  version: 1 as const,\n                  type: \"keybindingsUpdated\" as const,\n                  payload: {\n                    keybindings: event.keybindings,\n                    issues: event.issues,\n                  },\n                })),\n              );\n              const providerStatuses = providerRegistry.streamChanges.pipe(\n                Stream.map((providers) => ({\n                  version: 1 as const,\n                  type: \"providerStatuses\" as const,\n                  payload: { providers },\n                })),\n                Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),\n              );\n              const settingsUpdates = serverSettings.streamChanges.pipe(\n                Stream.map((settings) => ServerSettings.redactServerSettingsForClient(settings)),\n                Stream.map((settings) => ({\n                  version: 1 as const,\n                  type: \"settingsUpdated\" as const,\n                  payload: { settings },\n                })),\n              );\n\n              yield* providerRegistry\n                .refresh()\n                .pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);\n\n              const liveUpdates = Stream.merge(\n                keybindingsUpdates,\n                Stream.merge(providerStatuses, settingsUpdates),\n              );\n\n              return Stream.concat(\n                Stream.make({\n                  version: 1 as const,\n                  type: \"snapshot\" as const,\n                  config: yield* loadServerConfig,\n                }),\n                liveUpdates,\n              );\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.subscribeServerLifecycle]: (_input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeServerLifecycle,\n            Effect.gen(function* () {\n              const snapshot = yield* lifecycleEvents.snapshot;\n              const snapshotEvents = Array.from(snapshot.events).toSorted(\n                (left, right) => left.sequence - right.sequence,\n              );\n              const liveEvents = lifecycleEvents.stream.pipe(\n                Stream.filter((event) => event.sequence > snapshot.sequence),\n              );\n              return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.subscribeAuthAccess]: (_input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeAuthAccess,\n            Effect.gen(function* () {\n              const initialSnapshot = yield* loadAuthAccessSnapshot();\n              const revisionRef = yield* Ref.make(1);\n              const accessChanges: Stream.Stream<\n                PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange\n              > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);\n\n              const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(\n                Stream.mapEffect((change) =>\n                  Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(\n                    Effect.map((revision) =>\n                      toAuthAccessStreamEvent(change, revision, currentSessionId),\n                    ),\n                  ),\n                ),\n              );\n\n              return Stream.concat(\n                Stream.make({\n                  version: 1 as const,\n                  revision: 1,\n                  type: \"snapshot\" as const,\n                  payload: initialSnapshot,\n                }),\n                liveEvents,\n              );\n            }),\n            { \"rpc.aggregate\": \"auth\" },\n          ),\n        // agentlink fork: unsupported in this build (subsystem cut).\n        [WS_METHODS.cloudGetRelayClientStatus]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"cloud.getRelayClientStatus\" }>>),\n        [WS_METHODS.cloudInstallRelayClient]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"cloud.installRelayClient\" }>>),\n        [WS_METHODS.gitPreparePullRequestThread]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"git.preparePullRequestThread\" }>>),\n        [WS_METHODS.gitResolvePullRequest]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"git.resolvePullRequest\" }>>),\n        [WS_METHODS.gitRunStackedAction]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"git.runStackedAction\" }>>),\n        [WS_METHODS.previewAutomationConnect]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"previewAutomation.connect\" }>>),\n        [WS_METHODS.previewAutomationFocusHost]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"previewAutomation.focusHost\" }>>),\n        [WS_METHODS.previewAutomationRespond]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"previewAutomation.respond\" }>>),\n        [WS_METHODS.previewClose]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.close\" }>>),\n        [WS_METHODS.previewList]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.list\" }>>),\n        [WS_METHODS.previewNavigate]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.navigate\" }>>),\n        [WS_METHODS.previewOpen]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.open\" }>>),\n        [WS_METHODS.previewRefresh]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.refresh\" }>>),\n        [WS_METHODS.previewReportStatus]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.reportStatus\" }>>),\n        [WS_METHODS.previewResize]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"preview.resize\" }>>),\n        [WS_METHODS.reviewGetDiffFileContents]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"review.getDiffFileContents\" }>>),\n        [WS_METHODS.reviewGetDiffPreview]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"review.getDiffPreview\" }>>),\n        [WS_METHODS.serverDiscoverSourceControl]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.discoverSourceControl\" }>>),\n        [WS_METHODS.serverGetProcessDiagnostics]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.getProcessDiagnostics\" }>>),\n        [WS_METHODS.serverGetProcessResourceHistory]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.getProcessResourceHistory\" }>>),\n        [WS_METHODS.serverGetResourceTelemetryHistory]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.getResourceTelemetryHistory\" }>>),\n        [WS_METHODS.serverGetTraceDiagnostics]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.getTraceDiagnostics\" }>>),\n        [WS_METHODS.serverRetryResourceTelemetry]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.retryResourceTelemetry\" }>>),\n        [WS_METHODS.serverSignalProcess]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.signalProcess\" }>>),\n        [WS_METHODS.serverUpdateServer]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.updateServer\" }>>),\n        [WS_METHODS.serverUpdateServerWithProgress]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"server.updateServerWithProgress\" }>>),\n        [WS_METHODS.sourceControlCloneRepository]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"sourceControl.cloneRepository\" }>>),\n        [WS_METHODS.sourceControlLookupRepository]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"sourceControl.lookupRepository\" }>>),\n        [WS_METHODS.sourceControlPublishRepository]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"sourceControl.publishRepository\" }>>),\n        [WS_METHODS.subscribeDiscoveredLocalServers]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"subscribeDiscoveredLocalServers\" }>>),\n        [WS_METHODS.subscribePreviewEvents]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"subscribePreviewEvents\" }>>),\n        [WS_METHODS.subscribeResourceTelemetry]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"subscribeResourceTelemetry\" }>>),\n        [WS_METHODS.subscribeTerminalEvents]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeTerminalEvents,\n            Stream.callback<TerminalEvent>((queue) =>\n              Effect.acquireRelease(\n                terminalManager.subscribe((event) => Queue.offer(queue, event)),\n                (unsubscribe) => Effect.sync(unsubscribe),\n              ),\n            ),\n            { \"rpc.aggregate\": \"terminal\" },\n          ),\n        [WS_METHODS.subscribeTerminalMetadata]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeTerminalMetadata,\n            Stream.callback<TerminalMetadataStreamEvent>((queue) =>\n              Effect.acquireRelease(\n                terminalManager.subscribeMetadata((event) => Queue.offer(queue, event)),\n                (unsubscribe) => Effect.sync(unsubscribe),\n              ),\n            ),\n            { \"rpc.aggregate\": \"terminal\" },\n          ),\n        [WS_METHODS.subscribeVcsStatus]: (input) =>\n          observeRpcStream(WS_METHODS.subscribeVcsStatus, gitWorkspace.statusStream(input.cwd), {\n            \"rpc.aggregate\": \"vcs\",\n          }),\n        [WS_METHODS.terminalAttach]: (input) =>\n          observeRpcStream(\n            WS_METHODS.terminalAttach,\n            Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>\n              Effect.acquireRelease(\n                terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),\n                (unsubscribe) => Effect.sync(unsubscribe),\n              ),\n            ),\n            { \"rpc.aggregate\": \"terminal\" },\n          ),\n        [WS_METHODS.terminalClear]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalClose]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalOpen]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalResize]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalRestart]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalWrite]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.vcsCreateRef]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"vcs.createRef\" }>>),\n        [WS_METHODS.vcsCreateWorktree]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"vcs.createWorktree\" }>>),\n        [WS_METHODS.vcsInit]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"vcs.init\" }>>),\n        [WS_METHODS.vcsListRefs]: (input) =>\n          observeRpcEffect(WS_METHODS.vcsListRefs, gitWorkspace.listRefs(input), {\n            \"rpc.aggregate\": \"vcs\",\n          }),\n        [WS_METHODS.vcsPull]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"vcs.pull\" }>>),\n        [WS_METHODS.vcsRefreshStatus]: (input) =>\n          observeRpcEffect(WS_METHODS.vcsRefreshStatus, gitWorkspace.status(input.cwd), {\n            \"rpc.aggregate\": \"vcs\",\n          }),\n        [WS_METHODS.vcsRemoveWorktree]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"vcs.removeWorktree\" }>>),\n        [WS_METHODS.vcsSwitchRef]: (input) =>\n          observeRpcEffect(WS_METHODS.vcsSwitchRef, gitWorkspace.switchRef(input), {\n            \"rpc.aggregate\": \"vcs\",\n          }),\n        [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"orchestration.getFullThreadDiff\" }>>),\n        [ORCHESTRATION_WS_METHODS.getTurnDiff]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"orchestration.getTurnDiff\" }>>),\n        [ORCHESTRATION_WS_METHODS.getWorkflowScript]: (unsupportedRpc as Rpc.ToHandlerFn<Extract<WsRpcs, { readonly _tag: \"orchestration.getWorkflowScript\" }>>),\n        [WS_METHODS.subscribeBackgroundPolicy]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeBackgroundPolicy,\n            Stream.unwrap(\n              Effect.map(backgroundPolicy.subscribe, ({ latest, changes }) =>\n                Stream.concat(Stream.make(latest), changes),\n              ),\n            ),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n      });\n    }),\n  );\n\nexport const websocketRpcRouteLayer = Layer.unwrap(\n  Effect.gen(function* () {\n    return HttpRouter.add(\n      \"GET\",\n      \"/ws\",\n      Effect.gen(function* () {\n        const request = yield* HttpServerRequest.HttpServerRequest;\n        const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n        const sessions = yield* SessionStore.SessionStore;\n        const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"internal_error\", error),\n          ),\n        );\n        const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {\n          disableTracing: true,\n        }).pipe(\n          Effect.provide(\n            makeWsRpcLayer(session).pipe(\n              Layer.provideMerge(RpcSerialization.layerJson),\n              Layer.provide(ProviderMaintenanceRunner.layer),\n            ),\n          ),\n        );\n        return yield* Effect.acquireUseRelease(\n          sessions.markConnected(session.sessionId),\n          () => rpcWebSocketHttpEffect,\n          () => sessions.markDisconnected(session.sessionId),\n        );\n      }).pipe(\n        Effect.catchTags({\n          EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,\n          EnvironmentInternalError: HttpServerRespondable.toResponse,\n        }),\n      ),\n    );\n  }),\n);\n","// agentlink fork (t3-fork 步骤 6): node:crypto implementation of the\n// @agentlink/core E2EE envelope contract (packages/core/src/e2e.ts), which\n// the daemon cannot import directly — this package runs under\n// `node --experimental-strip-types` and core's noble imports are not in\n// daemon-t3's dependency closure. The wire contract is frozen, so the two\n// implementations are byte-for-byte interoperable (covered by\n// tunnel.test.ts against checked-in vectors):\n//\n//   - enckey: 32-byte master key, base64url (no padding) on the wire.\n//   - derive: HKDF-SHA256(ikm=enckey bytes, salt=utf8(\"agentlink\"),\n//     info=utf8(\"e2e-v1\"), length=32) → AES-256-GCM key.\n//   - per envelope: iv = 12 random bytes; ct = ciphertext || 16-byte GCM tag.\n//   - envelope: { e2e: 1, iv: base64url(iv), ct: base64url(ct) }.\n//   - plaintext: the raw utf8 bytes of one RPC frame (no JSON wrapping at\n//     this layer — bytesToEnvelope/envelopeToBytes in core).\n\nimport { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from \"node:crypto\";\n\nexport interface E2eEnvelope {\n  readonly e2e: 1;\n  readonly iv: string;\n  readonly ct: string;\n}\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nfunction deriveKey(enckey: string): Buffer {\n  if (!/^[A-Za-z0-9_-]{43}$/.test(enckey)) {\n    throw new Error(\"invalid enckey: expected unpadded base64url for 32 bytes\");\n  }\n  const ikm = Buffer.from(enckey, \"base64url\");\n  if (ikm.length !== 32) throw new Error(\"invalid enckey: expected 32 bytes\");\n  return Buffer.from(\n    hkdfSync(\"sha256\", ikm, textEncoder.encode(\"agentlink\"), textEncoder.encode(\"e2e-v1\"), 32),\n  );\n}\n\nexport function utf8ToEnvelope(enckey: string, plaintext: string): E2eEnvelope {\n  const key = deriveKey(enckey);\n  const iv = randomBytes(12);\n  const cipher = createCipheriv(\"aes-256-gcm\", key, iv);\n  const ct = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final(), cipher.getAuthTag()]);\n  return { e2e: 1, iv: iv.toString(\"base64url\"), ct: ct.toString(\"base64url\") };\n}\n\n// Wrong key / tampered ciphertext fails the GCM tag — createDecipheriv's\n// final() throws, the caller turns that into \"close this tunnel\".\nexport function envelopeToUtf8(enckey: string, envelope: E2eEnvelope): string {\n  const key = deriveKey(enckey);\n  const iv = Buffer.from(envelope.iv, \"base64url\");\n  const ct = Buffer.from(envelope.ct, \"base64url\");\n  if (ct.length < 16) throw new Error(\"invalid envelope: ciphertext shorter than the GCM tag\");\n  const decipher = createDecipheriv(\"aes-256-gcm\", key, iv);\n  decipher.setAuthTag(ct.subarray(ct.length - 16));\n  return textDecoder.decode(\n    Buffer.concat([decipher.update(ct.subarray(0, ct.length - 16)), decipher.final()]),\n  );\n}\n\nexport function isEnvelope(value: unknown): value is E2eEnvelope {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    (value as E2eEnvelope).e2e === 1 &&\n    typeof (value as E2eEnvelope).iv === \"string\" &&\n    typeof (value as E2eEnvelope).ct === \"string\"\n  );\n}\n\n// Keep encrypted WebSocket messages below Hub's 2 MiB maxPayload. The chunk\n// marker is encrypted like ordinary RPC/HTTP plaintext, so the Hub remains an\n// opaque relay and older small frames stay wire-compatible.\nconst AGENTLINK_FRAME_CHUNK_TAG = \"agentlink-frame-chunk-v1\";\nconst AGENTLINK_FRAME_CHUNK_BYTES = 512 * 1024;\nconst AGENTLINK_FRAME_MAX_CHUNKS = 64;\nconst AGENTLINK_FRAME_MAX_IN_FLIGHT = 8;\n\ntype AgentLinkFrameChunk = {\n  readonly __agentlink_chunk: typeof AGENTLINK_FRAME_CHUNK_TAG;\n  readonly id: string;\n  readonly index: number;\n  readonly total: number;\n  readonly data: string;\n};\n\nexport function chunkAgentLinkFrame(plaintext: string): readonly string[] {\n  const bytes = Buffer.from(plaintext, \"utf8\");\n  if (bytes.length <= AGENTLINK_FRAME_CHUNK_BYTES) return [plaintext];\n  const id = randomBytes(12).toString(\"base64url\");\n  const total = Math.ceil(bytes.length / AGENTLINK_FRAME_CHUNK_BYTES);\n  if (total > AGENTLINK_FRAME_MAX_CHUNKS) throw new Error(\"AgentLink frame is too large\");\n  const chunks: string[] = [];\n  for (let index = 0; index < total; index++) {\n    const start = index * AGENTLINK_FRAME_CHUNK_BYTES;\n    chunks.push(\n      JSON.stringify({\n        __agentlink_chunk: AGENTLINK_FRAME_CHUNK_TAG,\n        id,\n        index,\n        total,\n        data: bytes.subarray(start, start + AGENTLINK_FRAME_CHUNK_BYTES).toString(\"base64url\"),\n      } satisfies AgentLinkFrameChunk),\n    );\n  }\n  return chunks;\n}\n\nexport function makeAgentLinkFrameAssembler(): (plaintext: string) => string | null {\n  const inFlight = new Map<\n    string,\n    { readonly total: number; readonly parts: Array<Buffer | undefined>; bytes: number }\n  >();\n\n  return (plaintext) => {\n    if (!plaintext.startsWith(`{\"__agentlink_chunk\":\"${AGENTLINK_FRAME_CHUNK_TAG}\"`)) {\n      return plaintext;\n    }\n    let value: unknown;\n    try {\n      value = JSON.parse(plaintext);\n    } catch {\n      return plaintext;\n    }\n    if (\n      typeof value !== \"object\" ||\n      value === null ||\n      (value as { __agentlink_chunk?: unknown }).__agentlink_chunk !== AGENTLINK_FRAME_CHUNK_TAG\n    ) {\n      return plaintext;\n    }\n    const chunk = value as Partial<AgentLinkFrameChunk>;\n    if (\n      typeof chunk.id !== \"string\" ||\n      !Number.isInteger(chunk.index) ||\n      !Number.isInteger(chunk.total) ||\n      typeof chunk.data !== \"string\"\n    ) {\n      throw new Error(\"invalid AgentLink frame chunk\");\n    }\n    const id = chunk.id as string;\n    const index = chunk.index as number;\n    const total = chunk.total as number;\n    const data = chunk.data as string;\n    if (\n      total < 2 ||\n      total > AGENTLINK_FRAME_MAX_CHUNKS ||\n      index < 0 ||\n      index >= total\n    ) {\n      throw new Error(\"invalid AgentLink frame chunk\");\n    }\n    const part = Buffer.from(data, \"base64url\");\n    let current = inFlight.get(id);\n    if (!current) {\n      if (inFlight.size >= AGENTLINK_FRAME_MAX_IN_FLIGHT) {\n        throw new Error(\"too many AgentLink frame chunks in flight\");\n      }\n      current = {\n        total,\n        parts: Array.from({ length: total }, () => undefined),\n        bytes: 0,\n      };\n      inFlight.set(id, current);\n    }\n    const state = current!;\n    if (state.total !== total) throw new Error(\"inconsistent AgentLink frame chunk\");\n    const previous = state.parts[index];\n    if (previous) {\n      if (!previous.equals(part)) throw new Error(\"duplicate AgentLink frame chunk differs\");\n      return null;\n    }\n    state.parts[index] = part;\n    state.bytes += part.length;\n    if (state.bytes > AGENTLINK_FRAME_CHUNK_BYTES * AGENTLINK_FRAME_MAX_CHUNKS) {\n      throw new Error(\"AgentLink frame is too large\");\n    }\n    if (!state.parts.every((item) => item !== undefined)) return null;\n    if (state.parts.some((item) => item === undefined)) {\n      throw new Error(\"incomplete AgentLink frame chunk\");\n    }\n    const assembled = Buffer.concat(state.parts as Buffer[]);\n    inFlight.delete(id);\n    return assembled.toString(\"utf8\");\n  };\n}\n","// agentlink fork (t3-fork-design §9, 步骤 6): the daemon-side hub tunnel\n// bridge. With `hubTunnel` configured (--hub/--machine-token/--enckey or\n// T3CODE_HUB_* env), the daemon dials OUT to the hub's /daemon-tunnel\n// endpoint and holds the socket. For every browser the hub pairs up\n// ({\"type\":\"tunnel_attach\", tunnelId}), the bridge spins one in-process\n// Effect RPC session — the same WsRpcGroup + layerJson as the local /ws\n// route — over a decrypting socket adapter, so RPC frames cross the hub\n// only as E2EE envelopes:\n//\n//   browser ──hub──▶ daemon:  \"<tunnelId> <envelope JSON>\"  (text frame)\n//   daemon ──hub──▶ browser:  \"<tunnelId> <envelope JSON>\"  (text frame)\n//   hub ──▶ daemon control:   {\"type\":\"tunnel_attach\"} / ack \"tunnel_open\"\n//\n// The envelope plaintext is one whole RPC frame (RpcSerialization.layerJson\n// is one JSON value per WS text frame — verified against effect\n// 4.0.0-beta.103; see docs/t3-fork-design.md §9). The hub never sees\n// plaintext and stores nothing; an undeliverable frame closes the tunnel\n// rather than applying backpressure (matching the hub's own policy).\n//\n// Auth inside the tunnel: each tunnel session is minted via\n// EnvironmentAuth.issueSession with the tunnel scope set, so the daemon's\n// scope model (RpcAuthorization) stays the second gate behind the E2EE\n// key, exactly as §5 prescribes.\n\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as FiberSet from \"effect/FiberSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Scope from \"effect/Scope\";\nimport * as Socket from \"effect/unstable/socket/Socket\";\nimport * as NodeSocket from \"@effect/platform-node/NodeSocket\";\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { FromClientEncoded, FromServerEncoded } from \"effect/unstable/rpc/RpcMessage\";\nimport { RpcSerialization, RpcServer } from \"effect/unstable/rpc\";\nimport {\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  AuthPortProxyOperateScope,\n  AuthTerminalOperateScope,\n  WsRpcGroup,\n  type AuthEnvironmentScope,\n} from \"@t3tools/contracts\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\nimport * as SessionStore from \"../auth/SessionStore.ts\";\nimport * as ProviderMaintenanceRunner from \"../provider/providerMaintenanceRunner.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { makeWsRpcLayer, wsRpcServices } from \"../ws.ts\";\nimport {\n  chunkAgentLinkFrame,\n  envelopeToUtf8,\n  isEnvelope,\n  makeAgentLinkFrameAssembler,\n  utf8ToEnvelope,\n} from \"./e2e.ts\";\nimport {\n  HttpBody,\n  HttpClient,\n  HttpClientRequest,\n  HttpClientResponse,\n  HttpMethod,\n} from \"effect/unstable/http\";\nimport {\n  authorizedPortBaseUrl,\n  isPortProxyMethodAllowed,\n  isPortProxyRequestHeaderAllowed,\n  isPortProxyResponseHeaderAllowed,\n} from \"../portProxy.ts\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nexport interface HubTunnelConfig {\n  readonly hubUrl: string; // ws(s)://host[:port]\n  readonly machineToken: string; // al1 auth half, or the single-mode token\n  readonly enckey: string; // base64url 32-byte master key — never on the wire\n}\n\nexport const TUNNEL_SCOPES: ReadonlyArray<AuthEnvironmentScope> = [\n  AuthOrchestrationReadScope,\n  AuthOrchestrationOperateScope,\n  AuthTerminalOperateScope,\n  AuthPortProxyOperateScope,\n];\n\nexport function machineIdFromToken(token: string): string | null {\n  const parts = token.split(\".\");\n  if (parts.length !== 3 || parts[0] !== \"al1\" || !parts[1]) return null;\n  try {\n    const payload = JSON.parse(Buffer.from(parts[1], \"base64url\").toString(\"utf8\")) as {\n      mid?: unknown;\n    };\n    return typeof payload.mid === \"string\" && payload.mid.length > 0 ? payload.mid : null;\n  } catch {\n    return null;\n  }\n}\n\nexport function hubHttpUrl(hub: string): string {\n  const url = new URL(hub);\n  url.protocol = url.protocol === \"wss:\" ? \"https:\" : \"http:\";\n  url.pathname = \"\";\n  url.search = \"\";\n  url.hash = \"\";\n  return url.toString().replace(/\\/$/, \"\");\n}\n\nexport function hubRegistration(cliVersion: string | undefined) {\n  return cliVersion ? { type: \"register\" as const, daemonVersion: cliVersion } : null;\n}\n\nexport function writeHubConnectionStatus(\n  config: Pick<HubTunnelConfig, \"hubUrl\" | \"machineToken\">,\n  connected: boolean,\n  stateDir = process.env.AGENTLINK_STATE_DIR || join(homedir(), \".agentlink\"),\n): void {\n  try {\n    mkdirSync(stateDir, { recursive: true });\n    const statusPath = join(stateDir, \"status.json\");\n    let current: Record<string, unknown> = {};\n    try {\n      current = JSON.parse(readFileSync(statusPath, \"utf8\")) as Record<string, unknown>;\n    } catch {\n      // First write, or an invalid stale status file: replace it.\n    }\n    writeFileSync(\n      statusPath,\n      JSON.stringify({\n        ...current,\n        pid: process.pid,\n        state: connected ? \"connected\" : \"reconnecting\",\n        hub: config.hubUrl,\n        hubConnected: connected,\n        ...(process.env.AGENTLINK_CLI_VERSION\n          ? { daemonVersion: process.env.AGENTLINK_CLI_VERSION }\n          : {}),\n        machineId: machineIdFromToken(config.machineToken) ?? undefined,\n        startedAt: typeof current.startedAt === \"number\" ? current.startedAt : Date.now(),\n        ts: Date.now(),\n      }),\n    );\n  } catch {\n    // Best effort: CLI status must never affect the tunnel.\n  }\n}\n\nconst uploadHubEnckey = (config: HubTunnelConfig) =>\n  Effect.gen(function* () {\n    const machineId = machineIdFromToken(config.machineToken);\n    if (!machineId) {\n      return yield* Effect.fail(new Error(\"machine id is missing from the machine token\"));\n    }\n    const httpClient = yield* HttpClient.HttpClient;\n    const request = yield* HttpClientRequest.post(\n      `${hubHttpUrl(config.hubUrl)}/api/machines/${encodeURIComponent(machineId)}/enckey`,\n    ).pipe(\n      HttpClientRequest.setHeaders({\n        authorization: `Bearer ${config.machineToken}`,\n        \"content-type\": \"application/json\",\n        \"x-requested-with\": \"agentlink\",\n      }),\n      HttpClientRequest.bodyJson({ enckey: config.enckey }),\n    );\n    const response = yield* httpClient.execute(request);\n    yield* HttpClientResponse.filterStatusOk(response);\n    return machineId;\n  });\n\n// Frames relayed by the hub carry UTF-8 bytes; the ws transport may deliver\n// them as a Buffer/Uint8Array rather than a string, so decode defensively.\nconst hubFrameDecoder = new TextDecoder();\n\n// ---------------------------------------------------------------------\n// Port of effect's internal makeSocketProtocol (effect/unstable/rpc\n// RpcServer.js, 4.0.0-beta.103) minus the HTTP upgrade wrapper: the hub\n// tunnel needs protocol.onSocket over a SYNTHETIC socket (the decrypting\n// adapter), a seam the package does not export. The port is byte-faithful\n// so the two paths can never drift in framing semantics. `onSocket` keeps\n// the headers parameter for parity (unused — no HTTP headers exist inside\n// a tunnel).\n\nconst ResponseDefectEncoded = (cause: unknown) => ({\n  _tag: \"Defect\" as const,\n  defect: cause instanceof Error ? { message: cause.message, stack: cause.stack } : String(cause),\n});\n\nconst makeTunnelSocketProtocol = Effect.gen(function* () {\n  const serialization = yield* RpcSerialization.RpcSerialization;\n  const disconnects = yield* Queue.make<number>();\n  let clientId = 0;\n  const clients = new Map<\n    number,\n    { write: (response: FromServerEncoded) => Effect.Effect<void> }\n  >();\n  const clientIds = new Set<number>();\n  let writeRequest: (clientId: number, data: FromClientEncoded) => Effect.Effect<void>;\n\n  const onSocket = Effect.fnUntraced(function* (socket: Socket.Socket) {\n    const scope = yield* Effect.scope;\n    const parser = serialization.makeUnsafe();\n    const id = clientId++;\n    yield* Scope.addFinalizerExit(scope, () => {\n      clients.delete(id);\n      clientIds.delete(id);\n      return Queue.offer(disconnects, id).pipe(Effect.asVoid);\n    });\n    const writeRaw = yield* socket.writer;\n    const write = (response: FromServerEncoded) => {\n      try {\n        const encoded = parser.encode(response);\n        if (encoded === undefined) return Effect.void;\n        return Effect.orDie(writeRaw(encoded));\n      } catch (cause) {\n        const defect = parser.encode(ResponseDefectEncoded(cause) as FromServerEncoded);\n        return defect === undefined ? Effect.void : Effect.orDie(writeRaw(defect));\n      }\n    };\n    clients.set(id, { write });\n    clientIds.add(id);\n    yield* socket\n      .runRaw((data) => {\n        try {\n          const decoded = parser.decode(data);\n          if (decoded.length === 0) return Effect.void;\n          let i = 0;\n          return Effect.whileLoop({\n            while: () => i < decoded.length,\n            body: () => writeRequest(id, decoded[i++] as FromClientEncoded),\n            step: () => undefined,\n          });\n        } catch (cause) {\n          if (Predicate.isTagged(cause, \"MaxBufferSizeExceeded\")) {\n            return Effect.orDie(writeRaw(new Socket.CloseEvent(1009, String(cause))));\n          }\n          const defect = parser.encode(ResponseDefectEncoded(cause) as FromServerEncoded);\n          return defect === undefined ? Effect.void : Effect.orDie(writeRaw(defect));\n        }\n      })\n      .pipe(\n        Effect.catchReason(\"SocketError\", \"SocketCloseError\", () => Effect.void),\n        Effect.orDie,\n      );\n  });\n\n  const protocol = yield* RpcServer.Protocol.make((writeRequest_) => {\n    writeRequest = writeRequest_;\n    return Effect.succeed({\n      disconnects,\n      send: (clientId: number, response: FromServerEncoded) => {\n        const client = clients.get(clientId);\n        if (!client) return Effect.void;\n        return Effect.orDie(client.write(response));\n      },\n      end: (_clientId: number) => Effect.void,\n      clientIds: Effect.sync(() => clientIds),\n      initialMessage: Effect.succeedNone,\n      supportsAck: true,\n      supportsTransferables: false,\n      supportsSpanPropagation: true,\n    });\n  });\n\n  return { protocol, onSocket };\n});\n\n// ---------------------------------------------------------------------\n// Hub frame plumbing.\n\n// Control JSON (no id prefix) vs a tunnel frame \"<tunnelId> <rest>\".\nexport const splitHubFrame = (text: string): { tunnelId: string; rest: string } | null => {\n  if (text.startsWith(\"{\")) return null;\n  const spaceAt = text.indexOf(\" \");\n  if (spaceAt <= 0) return null;\n  return { tunnelId: text.slice(0, spaceAt), rest: text.slice(spaceAt + 1) };\n};\n\ninterface LiveTunnel {\n  readonly closed: Deferred.Deferred<void>;\n  readonly pendingFrames: Array<string>;\n  readonly purpose: \"rpc\" | \"http\";\n  onDecryptedFrame: ((frame: string) => void) | null;\n  readonly assembleFrame: (frame: string) => string | null;\n}\n\n// ---------------------------------------------------------------------\n// HTTP-over-tunnel frame contract (AgentLink fork §9 extension).\n//\n// A second tunnel purpose carries T3 environment HTTP requests/responses\n// through the same E2EE envelope as RPC frames. The hub stays opaque;\n// daemon decrypts, proxies to the local HTTP server, and encrypts the\n// response back.\n\ntype HttpTunnelRequestFrame = {\n  readonly _tag: \"HttpRequest\";\n  readonly id: string;\n  readonly method: string;\n  readonly path: string;\n  readonly headers: ReadonlyArray<[string, string]>;\n  readonly body: string | null; // base64-encoded body, null if empty\n  readonly targetPort?: number;\n};\n\ntype HttpTunnelResponseFrame = {\n  readonly _tag: \"HttpResponse\";\n  readonly id: string;\n  readonly status: number;\n  readonly statusText: string;\n  readonly headers: ReadonlyArray<[string, string]>;\n  readonly body: string | null; // base64-encoded body, null if empty\n};\n\nfunction isHttpTunnelRequestFrame(value: unknown): value is HttpTunnelRequestFrame {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    (value as { _tag?: unknown })._tag === \"HttpRequest\" &&\n    typeof (value as { id?: unknown }).id === \"string\" &&\n    typeof (value as { method?: unknown }).method === \"string\" &&\n    typeof (value as { path?: unknown }).path === \"string\" &&\n    Array.isArray((value as { headers?: unknown }).headers) &&\n    ((value as { body?: unknown }).body === null || typeof (value as { body?: unknown }).body === \"string\") &&\n    ((value as { targetPort?: unknown }).targetPort === undefined ||\n      (Number.isInteger((value as { targetPort?: unknown }).targetPort) &&\n        Number((value as { targetPort?: unknown }).targetPort) >= 1 &&\n        Number((value as { targetPort?: unknown }).targetPort) <= 65535))\n  );\n}\n\nfunction encodeHttpTunnelResponseFrame(frame: HttpTunnelResponseFrame): string {\n  return JSON.stringify(frame);\n}\n\n// The decrypting socket adapter between one tunnel and the RPC protocol:\n// runRaw hands DECRYPTED frames up, the writer encrypts on the way out.\nconst makeTunnelSocket = (input: {\n  readonly tunnel: LiveTunnel;\n  readonly enckey: string;\n  readonly sendEncrypted: (envelopeJson: string) => void;\n}): Socket.Socket => {\n  const runRaw: Socket.Socket[\"runRaw\"] = <A, E, R>(\n    handler: (frame: string | Uint8Array) => Effect.Effect<A, E, R> | void,\n    options?: { readonly onOpen?: Effect.Effect<void> | undefined },\n  ) =>\n    Effect.scopedWith((scope) =>\n      Effect.gen(function* () {\n        const fiberSet = yield* FiberSet.make<unknown, E>().pipe(Scope.provide(scope));\n        const runFork = yield* FiberSet.runtime(fiberSet)<R>();\n        const deliver = (frame: string) => {\n          const handled = handler(frame);\n          if (Effect.isEffect(handled)) {\n            void runFork(handled);\n          }\n        };\n        input.tunnel.onDecryptedFrame = deliver;\n        for (const frame of input.tunnel.pendingFrames.splice(0)) deliver(frame);\n        if (options?.onOpen) yield* options.onOpen;\n        // Block until the tunnel dies; returning ends the protocol's read\n        // loop for this client and runs the scope finalizers.\n        yield* Deferred.await(input.tunnel.closed).pipe(Effect.raceFirst(FiberSet.join(fiberSet)));\n      }),\n    );\n\n  return Socket.make({\n    runRaw,\n    writer: Effect.sync(\n      () => (chunk) =>\n        Effect.sync(() => {\n          if (typeof chunk === \"string\") {\n            for (const part of chunkAgentLinkFrame(chunk)) {\n              input.sendEncrypted(JSON.stringify(utf8ToEnvelope(input.enckey, part)));\n            }\n          }\n          // CloseEvent/bytes never occur with layerJson; tunnel teardown is\n          // Deferred-driven, nothing else to write.\n        }),\n    ),\n  });\n};\n\n// ---------------------------------------------------------------------\n// The worker: connect, multiplex tunnels, retry forever.\n\nexport const runHubTunnel = (config: HubTunnelConfig) =>\n  Effect.gen(function* () {\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const sessionsStore = yield* SessionStore.SessionStore;\n    const serverConfig = yield* ServerConfig.ServerConfig;\n    const httpClient = yield* HttpClient.HttpClient;\n    yield* wsRpcServices.pipe(Effect.asVoid);\n    yield* ChildProcessSpawner.ChildProcessSpawner;\n\n    // One hub connection attempt: scope-bound, so a drop tears down every\n    // tunnel and the writer with it, and the retry loop reconnects.\n    const connection = Effect.gen(function* () {\n      yield* Effect.sync(() => writeHubConnectionStatus(config, false));\n      yield* Effect.logInfo(\"hub tunnel: connection effect entered\");\n      const url = `${config.hubUrl.replace(/\\/+$/, \"\")}/daemon-tunnel?token=${encodeURIComponent(config.machineToken)}&v=1`;\n      yield* Effect.logInfo(\"hub tunnel: connecting\", { hubUrl: config.hubUrl });\n      const socket = yield* Socket.makeWebSocket(url).pipe(\n        Effect.provide(NodeSocket.layerWebSocketConstructor),\n      );\n      const upload = Effect.gen(function* () {\n        const machineId = machineIdFromToken(config.machineToken);\n        if (!machineId) {\n          yield* Effect.logWarning(\"[daemon] enckey upload skipped: machine id missing from token\");\n          return;\n        }\n        yield* Effect.logInfo(`[daemon] uploading enckey for machine ${machineId}...`);\n        yield* uploadHubEnckey(config);\n        yield* Effect.logInfo(\"[daemon] enckey uploaded to hub for cross-device recovery\");\n      }).pipe(\n        Effect.provideService(HttpClient.HttpClient, httpClient),\n        Effect.catch((error) =>\n          Effect.logError(`[daemon] enckey upload failed: ${String(error)}`),\n        ),\n        Effect.asVoid,\n      );\n      yield* Effect.addFinalizer((exit) =>\n        Effect.logInfo(\"hub tunnel: connection scope closing\", { exit: String(exit) }),\n      );\n\n      const tunnels = new Map<string, LiveTunnel>();\n      const dropTunnel = (tunnelId: string) => {\n        const t = tunnels.get(tunnelId);\n        if (!t) return;\n        tunnels.delete(tunnelId);\n        void Effect.runFork(Deferred.succeed(t.closed, undefined));\n      };\n      yield* Effect.addFinalizer(() =>\n        Effect.sync(() => {\n          for (const tunnelId of [...tunnels.keys()]) dropTunnel(tunnelId);\n        }),\n      );\n\n      // Outbound frames are serialized through a queue: with several live\n      // tunnels, concurrent socket.writer acquisitions could otherwise\n      // interleave hub frames.\n      const outbox = yield* Queue.bounded<string>(256);\n      const writeHub = (line: string) => Queue.offerUnsafe(outbox, line);\n      yield* Effect.forkScoped(\n        Effect.gen(function* () {\n          const writeRaw = yield* socket.writer;\n          yield* Effect.forever(Queue.take(outbox).pipe(Effect.flatMap(writeRaw)));\n        }),\n      );\n\n      const attachRpcTunnel = (tunnelId: string, live: LiveTunnel) =>\n        Effect.gen(function* () {\n          yield* Effect.addFinalizer(() =>\n            Effect.sync(() => {\n              if (tunnels.get(tunnelId) !== live) return;\n              tunnels.delete(tunnelId);\n              writeHub(\n                JSON.stringify({\n                  type: \"tunnel_close\",\n                  tunnelId,\n                  code: 1011,\n                  reason: \"daemon tunnel ended\",\n                }),\n              );\n            }),\n          );\n          // A tunnel session is a first-class session (visible/revocable in\n          // the access list), minted with the tunnel scope set.\n          const issued = yield* serverAuth.issueSession({\n            subject: \"hub-tunnel\",\n            label: \"AgentLink hub tunnel\",\n            scopes: [...TUNNEL_SCOPES],\n          });\n          yield* Effect.addFinalizer(() =>\n            sessionsStore\n              .markDisconnected(issued.sessionId)\n              .pipe(Effect.andThen(serverAuth.revokeSession(issued.sessionId)), Effect.ignore),\n          );\n          yield* sessionsStore.markConnected(issued.sessionId);\n\n          const socketAdapter = makeTunnelSocket({\n            tunnel: live,\n            enckey: config.enckey,\n            sendEncrypted: (envelopeJson) => {\n              if (!writeHub(`${tunnelId} ${envelopeJson}`)) dropTunnel(tunnelId);\n            },\n          });\n\n          // The RPC server half — same group + serialization + handler\n          // layer as the local /ws route, driven over the decrypting\n          // adapter through the ported socket protocol.\n          const { protocol, onSocket } = yield* makeTunnelSocketProtocol.pipe(\n            Effect.provide(RpcSerialization.layerJson),\n          );\n          const rpcServer = Effect.gen(function* () {\n            // `Effect.provide` replaces the context while it builds a layer.\n            // Build the handler layer explicitly from the tunnel fiber's\n            // current server context so ProviderRegistry and its siblings are\n            // available without recreating the daemon runtime layers.\n            const currentContext = yield* Effect.context();\n            const rpcContext = yield* Layer.build(\n              makeWsRpcLayer({\n                sessionId: issued.sessionId,\n                subject: \"hub-tunnel\",\n                method: \"bearer-access-token\",\n                scopes: [...TUNNEL_SCOPES],\n              }).pipe(\n                Layer.provideMerge(RpcSerialization.layerJson),\n                Layer.provide(ProviderMaintenanceRunner.layer),\n              ),\n            ).pipe(Effect.provideContext(currentContext));\n\n            yield* RpcServer.make(WsRpcGroup, { disableTracing: true }).pipe(\n              Effect.provideService(RpcServer.Protocol, protocol),\n              Effect.provideContext(rpcContext),\n            );\n          }).pipe(\n            Effect.tapCause((cause) =>\n              Effect.logError(\"hub tunnel: RPC server failed\", { cause: String(cause) }),\n            ),\n          );\n          yield* Effect.forkScoped(rpcServer);\n          yield* Effect.forkScoped(onSocket(socketAdapter));\n\n          // Acknowledge to the hub so its close handler tracks this tunnel.\n          if (!writeHub(JSON.stringify({ type: \"tunnel_open\", tunnelId }))) {\n            dropTunnel(tunnelId);\n          }\n          yield* Effect.logInfo(\"hub tunnel: attached\", { tunnelId, purpose: live.purpose });\n          yield* Deferred.await(live.closed);\n        }).pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"hub tunnel: attach failed\", { tunnelId, error }),\n          ),\n        );\n\n      const attachHttpTunnel = (tunnelId: string, live: LiveTunnel) =>\n        Effect.gen(function* () {\n          yield* Effect.addFinalizer(() =>\n            Effect.sync(() => {\n              if (tunnels.get(tunnelId) !== live) return;\n              tunnels.delete(tunnelId);\n              writeHub(\n                JSON.stringify({\n                  type: \"tunnel_close\",\n                  tunnelId,\n                  code: 1011,\n                  reason: \"daemon http tunnel ended\",\n                }),\n              );\n            }),\n          );\n\n          // Mint a session so we can authorize proxied requests to the\n          // local HTTP server. The browser does not hold a session cookie\n          // inside the tunnel, so we inject the Bearer token ourselves.\n          const issued = yield* serverAuth.issueSession({\n            subject: \"hub-tunnel-http\",\n            label: \"AgentLink hub tunnel HTTP proxy\",\n            scopes: [...TUNNEL_SCOPES],\n          });\n          yield* Effect.addFinalizer(() =>\n            sessionsStore\n              .markDisconnected(issued.sessionId)\n              .pipe(Effect.andThen(serverAuth.revokeSession(issued.sessionId)), Effect.ignore),\n          );\n          yield* sessionsStore.markConnected(issued.sessionId);\n\n          const daemonBaseUrl = `http://127.0.0.1:${serverConfig.port}`;\n\n          const sendEncrypted = (frame: HttpTunnelResponseFrame) => {\n            try {\n              for (const part of chunkAgentLinkFrame(encodeHttpTunnelResponseFrame(frame))) {\n                const envelope = utf8ToEnvelope(config.enckey, part);\n                if (!writeHub(`${tunnelId} ${JSON.stringify(envelope)}`)) {\n                  dropTunnel(tunnelId);\n                  return;\n                }\n              }\n            } catch {\n              dropTunnel(tunnelId);\n            }\n          };\n\n          live.onDecryptedFrame = (frame) => {\n            let requestFrame: HttpTunnelRequestFrame;\n            try {\n              const parsed = JSON.parse(frame);\n              if (!isHttpTunnelRequestFrame(parsed)) {\n                sendEncrypted({\n                  _tag: \"HttpResponse\",\n                  id: typeof parsed?.id === \"string\" ? parsed.id : \"unknown\",\n                  status: 400,\n                  statusText: \"Bad Request\",\n                  headers: [[\"content-type\", \"text/plain\"]],\n                  body: Buffer.from(\"Invalid HTTP tunnel request frame\").toString(\"base64\"),\n                });\n                return;\n              }\n              requestFrame = parsed;\n            } catch {\n              sendEncrypted({\n                _tag: \"HttpResponse\",\n                id: \"unknown\",\n                status: 400,\n                statusText: \"Bad Request\",\n                headers: [[\"content-type\", \"text/plain\"]],\n                body: Buffer.from(\"Malformed HTTP tunnel request frame\").toString(\"base64\"),\n              });\n              return;\n            }\n\n            const portProxyBaseUrl = requestFrame.targetPort === undefined\n              ? undefined\n              : authorizedPortBaseUrl(requestFrame.targetPort);\n            if (portProxyBaseUrl === null) {\n              sendEncrypted({\n                _tag: \"HttpResponse\",\n                id: requestFrame.id,\n                status: 403,\n                statusText: \"Forbidden\",\n                headers: [[\"content-type\", \"text/plain; charset=utf-8\"]],\n                body: Buffer.from(\"This port has not been authorized in AgentLink settings.\").toString(\"base64\"),\n              });\n              return;\n            }\n            if (portProxyBaseUrl !== undefined && !isPortProxyMethodAllowed(requestFrame.method)) {\n              sendEncrypted({\n                _tag: \"HttpResponse\",\n                id: requestFrame.id,\n                status: 405,\n                statusText: \"Method Not Allowed\",\n                headers: [[\"content-type\", \"text/plain; charset=utf-8\"]],\n                body: Buffer.from(\"Unsupported port proxy method.\").toString(\"base64\"),\n              });\n              return;\n            }\n\n            const effect = Effect.gen(function* () {\n              const localBaseUrl = portProxyBaseUrl ?? daemonBaseUrl;\n              const targetUrl = `${localBaseUrl}${requestFrame.path}`;\n              const headers: Record<string, string> = requestFrame.targetPort === undefined\n                ? { authorization: `Bearer ${issued.token}` }\n                : {};\n              for (const [key, value] of requestFrame.headers) {\n                const lower = key.toLowerCase();\n                if (\n                  requestFrame.targetPort === undefined\n                    ? lower === \"authorization\" || lower === \"cookie\"\n                    : !isPortProxyRequestHeaderAllowed(lower)\n                ) continue;\n                headers[lower] = value;\n              }\n\n              let request = HttpClientRequest.make(requestFrame.method as HttpMethod.HttpMethod)(\n                targetUrl,\n              ).pipe(HttpClientRequest.setHeaders(headers));\n              if (requestFrame.body !== null) {\n                const bodyBytes = Buffer.from(requestFrame.body, \"base64\");\n                request = HttpClientRequest.setBody(HttpBody.uint8Array(bodyBytes))(request);\n              }\n\n              const response = yield* httpClient.execute(request);\n              const responseBody = yield* response.arrayBuffer;\n              const responseHeaders: Array<[string, string]> = [];\n              for (const [key, value] of Object.entries(response.headers)) {\n                if (\n                  typeof value === \"string\" &&\n                  (requestFrame.targetPort === undefined || isPortProxyResponseHeaderAllowed(key))\n                ) {\n                  responseHeaders.push([key, value]);\n                }\n              }\n\n              return {\n                _tag: \"HttpResponse\" as const,\n                id: requestFrame.id,\n                status: response.status,\n                statusText: \"\",\n                headers: responseHeaders,\n                body: Buffer.from(responseBody).toString(\"base64\"),\n              };\n            }).pipe(\n              Effect.match({\n                onFailure: (cause): HttpTunnelResponseFrame => ({\n                  _tag: \"HttpResponse\",\n                  id: requestFrame.id,\n                  status: 502,\n                  statusText: \"Bad Gateway\",\n                  headers: [[\"content-type\", \"text/plain\"]],\n                  body: Buffer.from(\n                    cause instanceof Error ? cause.message : String(cause),\n                  ).toString(\"base64\"),\n                }),\n                onSuccess: (response) => response,\n              }),\n              Effect.tap((frame) => Effect.sync(() => sendEncrypted(frame))),\n            );\n\n            void Effect.runFork(effect);\n          };\n\n          // Acknowledge to the hub so its close handler tracks this tunnel.\n          if (!writeHub(JSON.stringify({ type: \"tunnel_open\", tunnelId }))) {\n            dropTunnel(tunnelId);\n          }\n          yield* Effect.logInfo(\"hub tunnel: attached\", { tunnelId, purpose: live.purpose });\n          yield* Deferred.await(live.closed);\n      }).pipe(\n        Effect.provideService(HttpClient.HttpClient, httpClient),\n        Effect.catch((error) =>\n            Effect.logWarning(\"hub tunnel: attach failed\", { tunnelId, error }),\n          ),\n        );\n\n      // Read loop for the hub socket: control JSON, tunnel frames, or\n      // connection end. Keep it interruptible so daemon shutdown closes the\n      // scoped WebSocket instead of stranding the worker.\n      yield* socket\n        .runRaw(\n          (rawData) => {\n            // The hub relays browser frames verbatim. Depending on the ws\n            // binaryType and how the browser's socket writes, a frame may\n            // arrive as a string OR as a Buffer/Uint8Array holding the same\n            // UTF-8 bytes. Decode both to text — dropping non-string frames\n            // silently used to swallow every RPC subscribe frame (provider\n            // status, config) whenever the transport delivered bytes, which\n            // manifested as \"attached but no RPC\" with providers stuck in\n            // Checking. CloseEvents are not expected on this contract.\n            const data =\n              typeof rawData === \"string\"\n                ? rawData\n                : rawData instanceof Uint8Array\n                  ? hubFrameDecoder.decode(rawData)\n                  : null;\n            if (data === null) return;\n            if (data.startsWith(\"{\")) {\n              let control: { type?: unknown; tunnelId?: unknown; purpose?: unknown };\n              try {\n                control = JSON.parse(data);\n              } catch {\n                return; // not ours — drop silently\n              }\n              if (control.type === \"tunnel_attach\" && typeof control.tunnelId === \"string\") {\n                const tunnelId = control.tunnelId;\n                if (tunnels.has(tunnelId)) return;\n                return Effect.gen(function* () {\n                  const closed = yield* Deferred.make<void>();\n                  const purpose = control.purpose === \"http\" ? \"http\" : \"rpc\";\n                  const live: LiveTunnel = {\n                    closed,\n                    pendingFrames: [],\n                    purpose,\n                    onDecryptedFrame: null,\n                    assembleFrame: makeAgentLinkFrameAssembler(),\n                  };\n                  // Register before forking setup: WebSocket ordering then\n                  // guarantees an immediate first RPC frame lands in the\n                  // bounded pendingFrames buffer instead of being dropped.\n                  tunnels.set(tunnelId, live);\n                  if (purpose === \"http\") {\n                    yield* Effect.forkScoped(Effect.scoped(attachHttpTunnel(tunnelId, live)));\n                  } else {\n                    yield* Effect.forkScoped(Effect.scoped(attachRpcTunnel(tunnelId, live)));\n                  }\n                });\n              }\n              if (control.type === \"tunnel_close\" && typeof control.tunnelId === \"string\") {\n                dropTunnel(control.tunnelId);\n              }\n              if (control.type === \"enckey_upload_request\") {\n                return Effect.sync(() => void Effect.runFork(upload));\n              }\n              return;\n            }\n            const framed = splitHubFrame(data);\n            if (framed) {\n              const live = tunnels.get(framed.tunnelId);\n              if (!live) return; // unknown/closed tunnel — drop silently (hub policy)\n              let envelope: unknown;\n              try {\n                envelope = JSON.parse(framed.rest);\n              } catch {\n                return dropTunnel(framed.tunnelId);\n              }\n              if (!isEnvelope(envelope)) return dropTunnel(framed.tunnelId);\n              let frame: string;\n              try {\n                frame = envelopeToUtf8(config.enckey, envelope);\n              } catch {\n                // Wrong key or tampered ciphertext — the tunnel is garbage.\n                return dropTunnel(framed.tunnelId);\n              }\n              let complete: string | null;\n              try {\n                complete = live.assembleFrame(frame);\n              } catch {\n                return dropTunnel(framed.tunnelId);\n              }\n              if (complete === null) return;\n              if (live.onDecryptedFrame) {\n                live.onDecryptedFrame(complete);\n              } else if (live.pendingFrames.length < 16) {\n                // ponytail: bounded setup-race buffer; add an attach-ready\n                // handshake only if clients can exceed 16 frames before setup.\n                live.pendingFrames.push(complete);\n              } else {\n                dropTunnel(framed.tunnelId);\n              }\n              return;\n            }\n          },\n          {\n            onOpen: Effect.logInfo(\"hub tunnel: connected to hub\").pipe(\n              Effect.tap(() =>\n                Effect.sync(() => {\n                  const registration = hubRegistration(process.env.AGENTLINK_CLI_VERSION);\n                  if (registration) writeHub(JSON.stringify(registration));\n                }),\n              ),\n              Effect.tap(() => Effect.sync(() => writeHubConnectionStatus(config, true))),\n              Effect.tap(() => Effect.sync(() => void Effect.runFork(upload))),\n            ),\n          },\n        )\n        .pipe(\n          Effect.ensuring(Effect.sync(() => writeHubConnectionStatus(config, false))),\n          Effect.tapDefect((cause) =>\n            Effect.logWarning(\"hub tunnel: hub socket defect\", { cause: String(cause) }),\n          ),\n        );\n\n      // runRaw returned: the hub socket closed. Every tunnel on it dies\n      // with it (finalizer above), and the retry loop reconnects.\n      yield* Effect.logWarning(\"hub tunnel: hub connection closed\");\n      return yield* Effect.fail(new Error(\"hub tunnel closed\"));\n    }).pipe(\n      Effect.scoped,\n      Effect.tapError((error) => Effect.logWarning(\"hub tunnel: connection error\", { error })),\n    );\n\n    // The hub going away is normal life for a long-running daemon (hub\n    // redeploys, laptop roams). Retry forever; the hub already failed the\n    // pending browser tunnels.\n    yield* Effect.retry(connection, {\n      schedule: Schedule.spaced(\"500 millis\"),\n      while: (error) =>\n        !(\n          Socket.SocketError.is(error) &&\n          error.reason._tag === \"SocketCloseError\" &&\n          (error.reason.code === 4401 || error.reason.code === 4403)\n        ),\n    });\n  }).pipe(\n    // The retry loop must NEVER die silently — a defect here would orphan\n    // the tunnel with no log at all.\n    Effect.tapDefect((cause) =>\n      Effect.logError(\"hub tunnel: worker defect\", { cause: String(cause) }),\n    ),\n    Effect.catchCause((cause) =>\n      Effect.logError(\"hub tunnel: worker failed\", { cause: String(cause) }),\n    ),\n  );\n\nexport const layer = (config: HubTunnelConfig) =>\n  Layer.effectDiscard(Effect.forkScoped(runHubTunnel(config)));\n","import type {\n  EnvironmentId,\n  OrchestrationProjectShell,\n  OrchestrationThreadShell,\n  ThreadId,\n} from \"@t3tools/contracts\";\n\nexport type AgentAwarenessPhase =\n  | \"starting\"\n  | \"running\"\n  | \"waiting_for_approval\"\n  | \"waiting_for_input\"\n  | \"completed\"\n  | \"failed\"\n  | \"stale\";\n\nexport interface AgentAwarenessState {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n  readonly projectTitle: string;\n  readonly threadTitle: string;\n  readonly phase: AgentAwarenessPhase;\n  readonly headline: string;\n  readonly detail?: string;\n  readonly modelTitle: string;\n  readonly updatedAt: string;\n  readonly deepLink: string;\n}\n\nexport interface ProjectThreadAwarenessInput {\n  readonly environmentId: EnvironmentId;\n  readonly project: Pick<OrchestrationProjectShell, \"title\">;\n  readonly thread: Pick<\n    OrchestrationThreadShell,\n    | \"id\"\n    | \"title\"\n    | \"modelSelection\"\n    | \"session\"\n    | \"latestTurn\"\n    | \"updatedAt\"\n    | \"hasPendingApprovals\"\n    | \"hasPendingUserInput\"\n  >;\n}\n\nexport function buildAgentAwarenessDeepLink(input: {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n}): string {\n  return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;\n}\n\nexport function projectThreadAwareness(\n  input: ProjectThreadAwarenessInput,\n): AgentAwarenessState | null {\n  const { environmentId, project, thread } = input;\n  const phase = resolveThreadAwarenessPhase(thread);\n  if (!phase) {\n    return null;\n  }\n\n  const detail = detailForPhase(phase, thread);\n  return {\n    environmentId,\n    threadId: thread.id,\n    projectTitle: project.title,\n    threadTitle: thread.title,\n    phase,\n    headline: headlineForPhase(phase),\n    ...(detail === undefined ? {} : { detail }),\n    modelTitle: thread.modelSelection.model,\n    updatedAt: thread.updatedAt,\n    deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),\n  };\n}\n\nfunction resolveThreadAwarenessPhase(\n  thread: ProjectThreadAwarenessInput[\"thread\"],\n): AgentAwarenessPhase | null {\n  if (thread.hasPendingApprovals) {\n    return \"waiting_for_approval\";\n  }\n  if (thread.hasPendingUserInput) {\n    return \"waiting_for_input\";\n  }\n  if (thread.session?.status === \"error\" || thread.latestTurn?.state === \"error\") {\n    return \"failed\";\n  }\n  if (thread.session?.status === \"starting\") {\n    return \"starting\";\n  }\n  if (thread.session?.status === \"running\" || thread.latestTurn?.state === \"running\") {\n    return \"running\";\n  }\n  if (thread.latestTurn?.state === \"completed\") {\n    return \"completed\";\n  }\n  // A turn that finished can still read as \"interrupted\" here: session\n  // teardown settles still-running turns by session status, and that write\n  // can race the turn.completed one. completedAt survives the race — a turn\n  // that has a completion timestamp finished, whatever the state column says.\n  // Without this, quick finish-then-teardown threads resolve to null\n  // persistently and get tombstoned instead of published as completed.\n  if (thread.latestTurn?.state === \"interrupted\" && thread.latestTurn.completedAt !== null) {\n    return \"completed\";\n  }\n  // Threads whose turns never produce a checkpoint (no code changes) have no\n  // materialized latestTurn in the shell at all, and the session-set\n  // projection clears latest_turn_id the moment the session settles. The\n  // session status is then the only surviving completion signal: a live\n  // session at \"ready\"/\"idle\" with nothing pending and nothing running means\n  // the agent finished and is waiting for the next prompt — Done.\n  if (thread.session?.status === \"ready\" || thread.session?.status === \"idle\") {\n    return \"completed\";\n  }\n  return null;\n}\n\nfunction headlineForPhase(phase: AgentAwarenessPhase): string {\n  switch (phase) {\n    case \"starting\":\n      return \"Starting agent\";\n    case \"running\":\n      return \"Agent is working\";\n    case \"waiting_for_approval\":\n      return \"Approval needed\";\n    case \"waiting_for_input\":\n      return \"Waiting for input\";\n    case \"completed\":\n      return \"Agent finished\";\n    case \"failed\":\n      return \"Agent failed\";\n    case \"stale\":\n      return \"Update delayed\";\n  }\n}\n\nfunction detailForPhase(\n  phase: AgentAwarenessPhase,\n  thread: ProjectThreadAwarenessInput[\"thread\"],\n): string | undefined {\n  if (phase === \"failed\") {\n    return thread.session?.lastError ?? undefined;\n  }\n  if (phase === \"completed\") {\n    return \"Review the completed task.\";\n  }\n  if (phase === \"running\" && thread.session?.providerName) {\n    return `${thread.session.providerName} is active.`;\n  }\n  return undefined;\n}\n","/**\n * DrainableWorker - A queue-based worker that exposes a `drain()` effect.\n *\n * Wraps the common `Queue.unbounded` + `Effect.forever` pattern and adds\n * a signal that resolves when the queue is empty **and** the current item\n * has finished processing. This lets tests replace timing-sensitive\n * `Effect.sleep` calls with deterministic `drain()`.\n *\n * @module DrainableWorker\n */\nimport * as Scope from \"effect/Scope\";\nimport * as Effect from \"effect/Effect\";\nimport * as TxQueue from \"effect/TxQueue\";\nimport * as TxRef from \"effect/TxRef\";\n\nexport interface DrainableWorker<A> {\n  /**\n   * Enqueue a work item and track it for `drain()`.\n   *\n   * This wraps `Queue.offer` so drain state is updated atomically with the\n   * enqueue path instead of inferring it from queue internals.\n   */\n  readonly enqueue: (item: A) => Effect.Effect<void>;\n\n  /**\n   * Resolves when the queue is empty and the worker is idle (not processing).\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * Create a drainable worker that processes items from an unbounded queue.\n *\n * The worker is forked into the current scope and will be interrupted when\n * the scope closes. A finalizer shuts down the queue.\n *\n * @param process - The effect to run for each queued item.\n * @returns A `DrainableWorker` with `queue` and `drain`.\n */\nexport const makeDrainableWorker = <A, E, R>(\n  process: (item: A) => Effect.Effect<void, E, R>,\n): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>\n  Effect.gen(function* () {\n    const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), TxQueue.shutdown);\n    const outstanding = yield* TxRef.make(0);\n\n    yield* TxQueue.take(queue).pipe(\n      Effect.tap((a) =>\n        Effect.ensuring(\n          process(a),\n          TxRef.update(outstanding, (n) => n - 1),\n        ),\n      ),\n      Effect.forever,\n      Effect.forkScoped,\n    );\n\n    const drain: DrainableWorker<A>[\"drain\"] = TxRef.get(outstanding).pipe(\n      Effect.tap((n) => (n > 0 ? Effect.txRetry : Effect.void)),\n      Effect.tx,\n    );\n\n    const enqueue = (element: A): Effect.Effect<boolean, never, never> =>\n      TxQueue.offer(queue, element).pipe(\n        Effect.tap(() => TxRef.update(outstanding, (n) => n + 1)),\n        Effect.tx,\n      );\n\n    return { enqueue, drain } satisfies DrainableWorker<A>;\n  });\n","import type { OrchestrationEvent, ThreadId } from \"@t3tools/contracts\";\nimport { projectThreadAwareness } from \"@t3tools/shared/agentAwareness\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\n\nimport type { HubTunnelConfig } from \"../config.ts\";\nimport * as ServerEnvironment from \"../environment/ServerEnvironment.ts\";\nimport * as OrchestrationEngine from \"../orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport { hubHttpUrl } from \"./bridge.ts\";\n\nexport class AgentAwarenessHub extends Context.Service<\n  AgentAwarenessHub,\n  { readonly start: () => Effect.Effect<void, never> }\n>()(\"agentlink/AgentAwarenessHub\") {}\n\nexport function eventThreadId(event: OrchestrationEvent): ThreadId | null {\n  const payload = event.payload as { readonly threadId?: unknown };\n  if (typeof payload.threadId === \"string\") return payload.threadId as ThreadId;\n  return event.aggregateKind === \"thread\" && typeof event.aggregateId === \"string\"\n    ? (event.aggregateId as ThreadId)\n    : null;\n}\n\nexport function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {\n  if (event.type === \"thread.message-sent\" || event.type === \"thread.turn-start-requested\") return false;\n  if (event.type !== \"thread.activity-appended\") return true;\n  return [\n    \"approval.requested\",\n    \"approval.resolved\",\n    \"user-input.requested\",\n    \"user-input.resolved\",\n    \"runtime.error\",\n  ].includes(event.payload.activity.kind);\n}\n\nconst make = (config: HubTunnelConfig) =>\n  Effect.gen(function* () {\n    const environment = yield* ServerEnvironment.ServerEnvironment;\n    const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n    const engine = yield* OrchestrationEngine.OrchestrationEngineService;\n    const published = yield* Ref.make(new Map<ThreadId, string>());\n\n    const publishThread = Effect.fn(\"AgentAwarenessHub.publishThread\")(function* (threadId: ThreadId) {\n      const thread = yield* snapshots.getThreadShellById(threadId);\n      if (Option.isNone(thread)) return;\n      const project = yield* snapshots.getProjectShellById(thread.value.projectId);\n      if (Option.isNone(project)) return;\n      const environmentId = yield* environment.getEnvironmentId;\n      const state = projectThreadAwareness({\n        environmentId,\n        project: project.value,\n        thread: thread.value,\n      });\n      if (\n        !state ||\n        ![\"waiting_for_approval\", \"waiting_for_input\", \"completed\", \"failed\"].includes(state.phase)\n      ) {\n        yield* Ref.update(published, (current) => {\n          const next = new Map(current);\n          next.delete(threadId);\n          return next;\n        });\n        return;\n      }\n\n      const { updatedAt: _updatedAt, detail: _detail, ...safeState } = state;\n      const identity = JSON.stringify(safeState);\n      const previous = (yield* Ref.get(published)).get(threadId);\n      if (previous === identity) return;\n\n      const response = yield* Effect.tryPromise({\n        try: () =>\n          fetch(`${hubHttpUrl(config.hubUrl)}/api/push/activity`, {\n            method: \"POST\",\n            headers: {\n              authorization: `Bearer ${config.machineToken}`,\n              \"content-type\": \"application/json\",\n              \"x-requested-with\": \"agentlink\",\n            },\n            body: JSON.stringify({ state: safeState }),\n          }),\n        catch: (cause) => cause,\n      });\n      if (!response.ok) return yield* Effect.fail(new Error(`Hub push publish failed: ${response.status}`));\n      yield* Ref.update(published, (current) => new Map(current).set(threadId, identity));\n    });\n\n    const worker = yield* makeDrainableWorker((threadId: ThreadId) =>\n      publishThread(threadId).pipe(\n        Effect.catchCause((cause) =>\n          Effect.logWarning(\"Agent awareness Hub publish failed\", { threadId, cause }),\n        ),\n      ),\n    );\n\n    return AgentAwarenessHub.of({\n      start: () =>\n        Stream.runForEach(engine.streamDomainEvents, (event) => {\n          const threadId = eventThreadId(event);\n          return threadId && shouldPublishAgentAwarenessEvent(event)\n            ? worker.enqueue(threadId)\n            : Effect.void;\n        }).pipe(Effect.catchCause(() => Effect.void)),\n    });\n  });\n\nexport const layer = (config: HubTunnelConfig) =>\n  Layer.effectDiscard(\n    Effect.gen(function* () {\n      const service = yield* make(config);\n      yield* Effect.forkScoped(service.start());\n    }),\n  );\n","import * as Arr from \"effect/Array\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport {\n  IsoDateTime,\n  ProviderInstanceId,\n  ProviderSessionRuntimeStatus,\n  RuntimeMode,\n  ThreadId,\n} from \"@t3tools/contracts\";\n\nimport {\n  PersistenceDecodeError,\n  type PersistenceErrorCorrelation,\n  PersistenceSqlError,\n  type ProviderSessionRuntimeRepositoryError,\n} from \"./Errors.ts\";\n\n/**\n * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.\n *\n * Owns persistence operations for provider runtime metadata and resume cursors.\n *\n * @module ProviderSessionRuntimeRepository\n */\n\nexport const ProviderSessionRuntime = Schema.Struct({\n  threadId: ThreadId,\n  providerName: Schema.String,\n  /**\n   * User-defined routing key for the configured provider instance that\n   * owns this session. Nullable only at the storage/migration boundary:\n   * rows persisted before the driver/instance split carry only\n   * `providerName`. Repository consumers must materialize a concrete\n   * instance id before routing.\n   */\n  providerInstanceId: Schema.NullOr(ProviderInstanceId),\n  adapterKey: Schema.String,\n  runtimeMode: RuntimeMode,\n  status: ProviderSessionRuntimeStatus,\n  lastSeenAt: IsoDateTime,\n  resumeCursor: Schema.NullOr(Schema.Unknown),\n  runtimePayload: Schema.NullOr(Schema.Unknown),\n});\nexport type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;\n\nexport const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });\nexport type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;\n\nexport const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });\nexport type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;\n\n/**\n * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.\n */\nexport class ProviderSessionRuntimeRepository extends Context.Service<\n  ProviderSessionRuntimeRepository,\n  {\n    /**\n     * Insert or replace a provider runtime row.\n     *\n     * Upserts by canonical `threadId`, including JSON payload/cursor fields.\n     */\n    readonly upsert: (\n      runtime: ProviderSessionRuntime,\n    ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;\n\n    /**\n     * Read provider runtime state by canonical thread id.\n     */\n    readonly getByThreadId: (\n      input: GetProviderSessionRuntimeInput,\n    ) => Effect.Effect<\n      Option.Option<ProviderSessionRuntime>,\n      ProviderSessionRuntimeRepositoryError\n    >;\n\n    /**\n     * List all provider runtime rows.\n     *\n     * Returned in ascending last-seen order.\n     */\n    readonly list: () => Effect.Effect<\n      ReadonlyArray<ProviderSessionRuntime>,\n      ProviderSessionRuntimeRepositoryError\n    >;\n\n    /**\n     * Delete provider runtime state by canonical thread id.\n     */\n    readonly deleteByThreadId: (\n      input: DeleteProviderSessionRuntimeInput,\n    ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;\n  }\n>()(\"t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository\") {}\n\nconst ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(\n  Struct.assign({\n    resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),\n    runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),\n  }),\n);\n\nconst ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({\n  threadId: Schema.String,\n  providerName: Schema.Unknown,\n  providerInstanceId: Schema.Unknown,\n  adapterKey: Schema.Unknown,\n  runtimeMode: Schema.Unknown,\n  status: Schema.Unknown,\n  lastSeenAt: Schema.Unknown,\n  resumeCursor: Schema.Unknown,\n  runtimePayload: Schema.Unknown,\n});\n\nconst decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);\n\nconst GetRuntimeRequestSchema = Schema.Struct({\n  threadId: ThreadId,\n});\n\nconst DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;\n\nfunction toPersistenceSqlOrDecodeError(\n  sqlOperation: string,\n  decodeOperation: string,\n  correlation?: PersistenceErrorCorrelation,\n) {\n  return (cause: unknown): ProviderSessionRuntimeRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)\n      : new PersistenceSqlError({\n          operation: sqlOperation,\n          ...(correlation === undefined ? {} : { correlation }),\n          cause,\n        });\n}\n\nexport const make = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertRuntimeRow = SqlSchema.void({\n    Request: ProviderSessionRuntimeDbRowSchema,\n    execute: (runtime) =>\n      sql`\n        INSERT INTO provider_session_runtime (\n          thread_id,\n          provider_name,\n          provider_instance_id,\n          adapter_key,\n          runtime_mode,\n          status,\n          last_seen_at,\n          resume_cursor_json,\n          runtime_payload_json\n        )\n        VALUES (\n          ${runtime.threadId},\n          ${runtime.providerName},\n          ${runtime.providerInstanceId},\n          ${runtime.adapterKey},\n          ${runtime.runtimeMode},\n          ${runtime.status},\n          ${runtime.lastSeenAt},\n          ${runtime.resumeCursor},\n          ${runtime.runtimePayload}\n        )\n        ON CONFLICT (thread_id)\n        DO UPDATE SET\n          provider_name = excluded.provider_name,\n          provider_instance_id = excluded.provider_instance_id,\n          adapter_key = excluded.adapter_key,\n          runtime_mode = excluded.runtime_mode,\n          status = excluded.status,\n          last_seen_at = excluded.last_seen_at,\n          resume_cursor_json = excluded.resume_cursor_json,\n          runtime_payload_json = excluded.runtime_payload_json\n      `,\n  });\n\n  const getRuntimeRowByThreadId = SqlSchema.findOneOption({\n    Request: GetRuntimeRequestSchema,\n    Result: ProviderSessionRuntimeRawDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          adapter_key AS \"adapterKey\",\n          runtime_mode AS \"runtimeMode\",\n          status,\n          last_seen_at AS \"lastSeenAt\",\n          resume_cursor_json AS \"resumeCursor\",\n          runtime_payload_json AS \"runtimePayload\"\n        FROM provider_session_runtime\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const listRuntimeRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProviderSessionRuntimeRawDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          adapter_key AS \"adapterKey\",\n          runtime_mode AS \"runtimeMode\",\n          status,\n          last_seen_at AS \"lastSeenAt\",\n          resume_cursor_json AS \"resumeCursor\",\n          runtime_payload_json AS \"runtimePayload\"\n        FROM provider_session_runtime\n        ORDER BY last_seen_at ASC, thread_id ASC\n      `,\n  });\n\n  const deleteRuntimeByThreadId = SqlSchema.void({\n    Request: DeleteRuntimeRequestSchema,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM provider_session_runtime\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProviderSessionRuntimeRepository[\"Service\"][\"upsert\"] = (runtime) =>\n    upsertRuntimeRow(runtime).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProviderSessionRuntimeRepository.upsert:query\",\n          \"ProviderSessionRuntimeRepository.upsert:encodeRequest\",\n          { threadId: runtime.threadId },\n        ),\n      ),\n    );\n\n  const getByThreadId: ProviderSessionRuntimeRepository[\"Service\"][\"getByThreadId\"] = (input) =>\n    getRuntimeRowByThreadId(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProviderSessionRuntimeRepository.getByThreadId:query\",\n          \"ProviderSessionRuntimeRepository.getByThreadId:decodeRow\",\n          { threadId: input.threadId },\n        ),\n      ),\n      Effect.flatMap((runtimeRowOption) =>\n        Option.match(runtimeRowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeRuntimeRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"ProviderSessionRuntimeRepository.getByThreadId:decodeRow\",\n                  cause,\n                  { threadId: input.threadId },\n                ),\n              ),\n              Effect.map((runtime) => Option.some(runtime)),\n            ),\n        }),\n      ),\n    );\n\n  const list: ProviderSessionRuntimeRepository[\"Service\"][\"list\"] = () =>\n    listRuntimeRows(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProviderSessionRuntimeRepository.list:query\",\n          \"ProviderSessionRuntimeRepository.list:decodeRows\",\n        ),\n      ),\n      Effect.flatMap((rows) =>\n        // Skip rows that no longer decode (e.g. written by an older build)\n        // instead of failing the whole list — one stale row must not disable\n        // every consumer that enumerates sessions, such as the reaper.\n        Effect.forEach(rows, (row) =>\n          decodeRuntimeRow(row).pipe(\n            Effect.map(Option.some),\n            Effect.catch((cause) =>\n              Effect.logWarning(\"provider.session.runtime.row-skipped\", {\n                threadId: row.threadId,\n                error: PersistenceDecodeError.fromSchemaError(\n                  \"ProviderSessionRuntimeRepository.list:decodeRows\",\n                  cause,\n                  { threadId: row.threadId },\n                ).message,\n              }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),\n            ),\n          ),\n        ),\n      ),\n      Effect.map((decoded) =>\n        Arr.filterMap(decoded, (row) =>\n          Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,\n        ),\n      ),\n    );\n\n  const deleteByThreadId: ProviderSessionRuntimeRepository[\"Service\"][\"deleteByThreadId\"] = (\n    input,\n  ) =>\n    deleteRuntimeByThreadId(input).pipe(\n      Effect.mapError(\n        (cause) =>\n          new PersistenceSqlError({\n            operation: \"ProviderSessionRuntimeRepository.deleteByThreadId:query\",\n            correlation: { threadId: input.threadId },\n            cause,\n          }),\n      ),\n    );\n\n  return {\n    upsert,\n    getByThreadId,\n    list,\n    deleteByThreadId,\n  } satisfies ProviderSessionRuntimeRepository[\"Service\"];\n});\n\nexport const layer = Layer.effect(ProviderSessionRuntimeRepository, make);\n","import * as Schema from \"effect/Schema\";\n\n/**\n * ProviderAdapterValidationError - Invalid adapter API input.\n */\nexport class ProviderAdapterValidationError extends Schema.TaggedErrorClass<ProviderAdapterValidationError>()(\n  \"ProviderAdapterValidationError\",\n  {\n    provider: Schema.String,\n    operation: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider adapter validation failed (${this.provider}) in ${this.operation}: ${this.issue}`;\n  }\n}\n\n/**\n * ProviderAdapterSessionNotFoundError - Adapter-owned session id is unknown.\n */\nexport class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass<ProviderAdapterSessionNotFoundError>()(\n  \"ProviderAdapterSessionNotFoundError\",\n  {\n    provider: Schema.String,\n    threadId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Unknown ${this.provider} adapter thread: ${this.threadId}`;\n  }\n}\n\n/**\n * ProviderAdapterSessionClosedError - Adapter session exists but is closed.\n */\nexport class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass<ProviderAdapterSessionClosedError>()(\n  \"ProviderAdapterSessionClosedError\",\n  {\n    provider: Schema.String,\n    threadId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `${this.provider} adapter thread is closed: ${this.threadId}`;\n  }\n}\n\n/**\n * ProviderAdapterRequestError - Provider protocol request failed or timed out.\n */\nexport class ProviderAdapterRequestError extends Schema.TaggedErrorClass<ProviderAdapterRequestError>()(\n  \"ProviderAdapterRequestError\",\n  {\n    provider: Schema.String,\n    method: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`;\n  }\n}\n\n/**\n * ProviderAdapterProcessError - Provider process lifecycle failure.\n */\nexport class ProviderAdapterProcessError extends Schema.TaggedErrorClass<ProviderAdapterProcessError>()(\n  \"ProviderAdapterProcessError\",\n  {\n    provider: Schema.String,\n    threadId: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;\n  }\n}\n\n/**\n * ProviderValidationError - Invalid provider API input.\n */\nexport class ProviderValidationError extends Schema.TaggedErrorClass<ProviderValidationError>()(\n  \"ProviderValidationError\",\n  {\n    operation: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider validation failed in ${this.operation}: ${this.issue}`;\n  }\n}\n\n/**\n * ProviderUnsupportedError - Requested provider is not implemented.\n */\nexport class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUnsupportedError>()(\n  \"ProviderUnsupportedError\",\n  {\n    provider: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider '${this.provider}' is not implemented`;\n  }\n}\n\n/**\n * ProviderInstanceNotFoundError - Lookup against the instance registry failed.\n *\n * Distinct from `ProviderUnsupportedError`: the driver is registered, but no\n * instance with the requested id has been bootstrapped — typically because\n * the persisted instance id refers to an instance the user removed from\n * settings, or because routing is asked for an instance before the registry\n * has finished its first reload.\n */\nexport class ProviderInstanceNotFoundError extends Schema.TaggedErrorClass<ProviderInstanceNotFoundError>()(\n  \"ProviderInstanceNotFoundError\",\n  {\n    instanceId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `No provider instance bound to id '${this.instanceId}'`;\n  }\n}\n\n/**\n * ProviderDriverError - A driver `create` call failed before producing an\n * instance. Surfaced to the registry, which marks the offending entry as\n * an \"unavailable\" shadow snapshot rather than crashing the server.\n */\nexport class ProviderDriverError extends Schema.TaggedErrorClass<ProviderDriverError>()(\n  \"ProviderDriverError\",\n  {\n    driver: Schema.String,\n    instanceId: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}`;\n  }\n}\n\n/**\n * ProviderSessionNotFoundError - Provider-facing session not found.\n */\nexport class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<ProviderSessionNotFoundError>()(\n  \"ProviderSessionNotFoundError\",\n  {\n    threadId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Unknown provider thread: ${this.threadId}`;\n  }\n}\n\n/**\n * ProviderSessionDirectoryPersistenceError - Session directory persistence failure.\n */\nexport class ProviderSessionDirectoryPersistenceError extends Schema.TaggedErrorClass<ProviderSessionDirectoryPersistenceError>()(\n  \"ProviderSessionDirectoryPersistenceError\",\n  {\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider session directory persistence error in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport type ProviderAdapterError =\n  | ProviderAdapterValidationError\n  | ProviderAdapterSessionNotFoundError\n  | ProviderAdapterSessionClosedError\n  | ProviderAdapterRequestError\n  | ProviderAdapterProcessError;\n\nexport type ProviderServiceError =\n  | ProviderValidationError\n  | ProviderUnsupportedError\n  | ProviderInstanceNotFoundError\n  | ProviderSessionNotFoundError\n  | ProviderSessionDirectoryPersistenceError\n  | ProviderAdapterError;\n","import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProviderSessionRuntime from \"../../persistence/ProviderSessionRuntime.ts\";\nimport { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from \"../Errors.ts\";\nimport {\n  ProviderSessionDirectory,\n  type ProviderRuntimeBinding,\n  type ProviderRuntimeBindingWithMetadata,\n  type ProviderSessionDirectoryShape,\n} from \"../Services/ProviderSessionDirectory.ts\";\nconst decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);\n\nfunction toPersistenceError(operation: string) {\n  return (cause: unknown) =>\n    new ProviderSessionDirectoryPersistenceError({\n      operation,\n      detail: `Failed to execute ${operation}.`,\n      cause,\n    });\n}\n\nfunction decodeProviderDriverKind(\n  providerName: string,\n  operation: string,\n): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {\n  return decodeProviderDriverKindValue(providerName).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ProviderSessionDirectoryPersistenceError({\n          operation,\n          detail: `Unknown persisted provider '${providerName}'.`,\n          cause,\n        }),\n    ),\n  );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction mergeRuntimePayload(\n  existing: unknown | null,\n  next: unknown | null | undefined,\n): unknown | null {\n  if (next === undefined) {\n    return existing ?? null;\n  }\n  if (isRecord(existing) && isRecord(next)) {\n    return { ...existing, ...next };\n  }\n  return next;\n}\n\nfunction toRuntimeBinding(\n  runtime: ProviderSessionRuntime.ProviderSessionRuntime,\n  operation: string,\n): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {\n  return decodeProviderDriverKind(runtime.providerName, operation).pipe(\n    Effect.map(\n      (provider) =>\n        ({\n          threadId: runtime.threadId,\n          provider,\n          // Migration boundary only: rows written before the instance split\n          // have a null provider_instance_id. Promote them as they leave\n          // persistence so hot routing code never has to infer an instance\n          // from a driver kind.\n          providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),\n          adapterKey: runtime.adapterKey,\n          runtimeMode: runtime.runtimeMode,\n          status: runtime.status,\n          resumeCursor: runtime.resumeCursor,\n          runtimePayload: runtime.runtimePayload,\n          lastSeenAt: runtime.lastSeenAt,\n        }) satisfies ProviderRuntimeBindingWithMetadata,\n    ),\n  );\n}\n\nconst makeProviderSessionDirectory = Effect.gen(function* () {\n  const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;\n\n  const getBinding = (threadId: ThreadId) =>\n    repository.getByThreadId({ threadId }).pipe(\n      Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.getBinding:getByThreadId\")),\n      Effect.flatMap((runtime) =>\n        Option.match(runtime, {\n          onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),\n          onSome: (value) =>\n            toRuntimeBinding(value, \"ProviderSessionDirectory.getBinding\").pipe(\n              Effect.map((binding) => Option.some(binding)),\n            ),\n        }),\n      ),\n    );\n\n  const upsert: ProviderSessionDirectoryShape[\"upsert\"] = Effect.fn(function* (binding) {\n    const existing = yield* repository\n      .getByThreadId({ threadId: binding.threadId })\n      .pipe(Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.upsert:getByThreadId\")));\n\n    const existingRuntime = Option.getOrUndefined(existing);\n    const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;\n    if (!resolvedThreadId) {\n      return yield* new ProviderValidationError({\n        operation: \"ProviderSessionDirectory.upsert\",\n        issue: \"threadId must be a non-empty string.\",\n      });\n    }\n\n    const now = DateTime.formatIso(yield* DateTime.now);\n    const providerChanged =\n      existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;\n    const providerInstanceId =\n      binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);\n    if (providerInstanceId === null || providerInstanceId === undefined) {\n      return yield* new ProviderValidationError({\n        operation: \"ProviderSessionDirectory.upsert\",\n        issue: \"providerInstanceId is required for provider session runtime bindings.\",\n      });\n    }\n    yield* repository\n      .upsert({\n        threadId: resolvedThreadId,\n        providerName: binding.provider,\n        providerInstanceId,\n        adapterKey:\n          binding.adapterKey ??\n          (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),\n        runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? \"full-access\",\n        status: binding.status ?? existingRuntime?.status ?? \"running\",\n        lastSeenAt: now,\n        resumeCursor:\n          binding.resumeCursor !== undefined\n            ? binding.resumeCursor\n            : (existingRuntime?.resumeCursor ?? null),\n        runtimePayload: mergeRuntimePayload(\n          existingRuntime?.runtimePayload ?? null,\n          binding.runtimePayload,\n        ),\n      })\n      .pipe(Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.upsert:upsert\")));\n  });\n\n  const getProvider: ProviderSessionDirectoryShape[\"getProvider\"] = (threadId) =>\n    getBinding(threadId).pipe(\n      Effect.flatMap((binding) =>\n        Option.match(binding, {\n          onSome: (value) => Effect.succeed(value.provider),\n          onNone: () =>\n            Effect.fail(\n              new ProviderSessionDirectoryPersistenceError({\n                operation: \"ProviderSessionDirectory.getProvider\",\n                detail: `No persisted provider binding found for thread '${threadId}'.`,\n              }),\n            ),\n        }),\n      ),\n    );\n\n  const listThreadIds: ProviderSessionDirectoryShape[\"listThreadIds\"] = () =>\n    repository.list().pipe(\n      Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.listThreadIds:list\")),\n      Effect.map((rows) => rows.map((row) => row.threadId)),\n    );\n\n  const listBindings: ProviderSessionDirectoryShape[\"listBindings\"] = () =>\n    repository.list().pipe(\n      Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.listBindings:list\")),\n      Effect.flatMap((rows) =>\n        Effect.forEach(\n          rows,\n          (row) => toRuntimeBinding(row, \"ProviderSessionDirectory.listBindings\"),\n          { concurrency: \"unbounded\" },\n        ),\n      ),\n    );\n\n  return {\n    upsert,\n    getProvider,\n    getBinding,\n    listThreadIds,\n    listBindings,\n  } satisfies ProviderSessionDirectoryShape;\n});\n\nexport const ProviderSessionDirectoryLive = Layer.effect(\n  ProviderSessionDirectory,\n  makeProviderSessionDirectory,\n);\n\nexport function makeProviderSessionDirectoryLive() {\n  return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);\n}\n","/**\n * ProviderInstanceRegistry — the single Effect service in the new model.\n *\n * Owns a `Map<ProviderInstanceId, ProviderInstance>` produced by running\n * registered driver factories against `ServerSettings.providerInstances`.\n * The registry watches settings; when an instance's config changes (or\n * the entry disappears), the registry tears down the affected instance's\n * scope and rebuilds — that's the entire hot-reload story.\n *\n * What rest-of-server reads from here:\n *   - `getInstance(instanceId)` — for routing turn/session calls.\n *   - `listInstances` — for snapshot aggregation in `ProviderRegistry`.\n *   - `listUnavailable` — `ServerProvider` shadows for instances whose\n *     driver is not registered in this build (rollback / fork tolerance).\n *   - `streamChanges` — coalesced \"registry mutated\" pings so consumers\n *     can re-pull lists or re-broadcast.\n *\n * @module provider/Services/ProviderInstanceRegistry\n */\nimport type { ProviderInstanceId, ServerProvider } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { ProviderInstance } from \"../ProviderDriver.ts\";\n\nexport interface ProviderInstanceRegistryShape {\n  /**\n   * Look up one instance by id. Returns `undefined` (not Option) when the\n   * id is unknown — callers branch on falsy and emit\n   * `ProviderInstanceNotFoundError`.\n   */\n  readonly getInstance: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderInstance | undefined>;\n  /**\n   * Every available (driver-registered, successfully created) instance,\n   * in stable settings-author order.\n   */\n  readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;\n  /**\n   * Wire-shape shadow snapshots for instances whose driver is unknown to\n   * this build (or whose config failed to decode). Suitable for merging\n   * directly into `ProviderRegistry` output.\n   */\n  readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;\n  /**\n   * Push notification stream emitted whenever the registry's contents\n   * change — instance added, removed, or rebuilt. The payload is `void`\n   * because consumers always want to re-pull `listInstances` /\n   * `listUnavailable` together.\n   *\n   * NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the\n   * stream starts running, forking a consumer via\n   * `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next\n   * publish — the forked fiber may not have subscribed yet when the\n   * publish lands. Hot-reload consumers that must not miss a publish\n   * should use `subscribeChanges` below instead, which acquires the\n   * subscription synchronously in the caller's fiber before the consumer\n   * loop is forked.\n   */\n  readonly streamChanges: Stream.Stream<void>;\n  /**\n   * Acquire a subscription to the registry's change channel synchronously\n   * in the caller's fiber. Returns a `PubSub.Subscription<void>` whose\n   * lifetime is scoped to the provided `Scope` (the subscription is\n   * released when the scope closes). Consumers typically `yield*` this\n   * in the same fiber that forks their consumer loop, then drain with\n   * `PubSub.take(subscription)` inside `Effect.forever`. Because the\n   * subscription is registered with the PubSub before this `yield*`\n   * returns, no subsequent publish can land in a gap.\n   *\n   * This exists because the `ProviderInstanceRegistry` publishes on a\n   * PubSub and `Stream.fromPubSub` defers subscription until the stream\n   * starts executing — a consumer that `forkScoped`s the stream\n   * consumption can miss a publish that lands in the narrow window\n   * between \"fiber scheduled\" and \"fiber starts running\".\n   */\n  readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;\n}\n\nexport class ProviderInstanceRegistry extends Context.Service<\n  ProviderInstanceRegistry,\n  ProviderInstanceRegistryShape\n>()(\"t3/provider/Services/ProviderInstanceRegistry\") {}\n","/**\n * ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.\n *\n * `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one\n * adapter via the four `<X>AdapterLive` singleton Layers. The per-instance\n * refactor moved adapter construction inside each `ProviderDriver.create()`:\n * adapters are now bundled on the `ProviderInstance` that the\n * `ProviderInstanceRegistry` owns.\n *\n * This facade fulfills the `ProviderAdapterRegistryShape` contract by doing\n * dynamic look-ups against `ProviderInstanceRegistry` on every call. That\n * means settings-driven hot-reload shows up here automatically — adding a\n * new instance via settings makes `getByInstance` resolve immediately\n * without rebuilding the facade.\n *\n * @module ProviderAdapterRegistryLive\n */\nimport {\n  defaultInstanceIdForDriver,\n  ProviderInstanceId,\n  type ProviderDriverKind,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { ProviderUnsupportedError } from \"../Errors.ts\";\nimport { ProviderInstanceRegistry } from \"../Services/ProviderInstanceRegistry.ts\";\nimport {\n  ProviderAdapterRegistry,\n  type ProviderAdapterRegistryShape,\n} from \"../Services/ProviderAdapterRegistry.ts\";\n\nconst makeProviderAdapterRegistry = Effect.fn(\"makeProviderAdapterRegistry\")(function* () {\n  const registry = yield* ProviderInstanceRegistry;\n\n  const getByInstance: ProviderAdapterRegistryShape[\"getByInstance\"] = (instanceId) =>\n    registry.getInstance(instanceId).pipe(\n      Effect.flatMap((instance) =>\n        instance === undefined\n          ? Effect.fail(\n              new ProviderUnsupportedError({\n                provider: instanceId,\n              }),\n            )\n          : Effect.succeed(instance.adapter),\n      ),\n    );\n\n  const getInstanceInfo: ProviderAdapterRegistryShape[\"getInstanceInfo\"] = (instanceId) =>\n    registry.getInstance(instanceId).pipe(\n      Effect.flatMap((instance) =>\n        instance === undefined\n          ? Effect.fail(\n              new ProviderUnsupportedError({\n                provider: instanceId,\n              }),\n            )\n          : Effect.succeed({\n              instanceId: instance.instanceId,\n              driverKind: instance.driverKind,\n              displayName: instance.displayName,\n              accentColor: instance.accentColor,\n              enabled: instance.enabled,\n              continuationIdentity: instance.continuationIdentity,\n            }),\n      ),\n    );\n\n  const listInstances: ProviderAdapterRegistryShape[\"listInstances\"] = () =>\n    registry.listInstances.pipe(\n      Effect.map((instances) => instances.map((instance) => instance.instanceId)),\n    );\n\n  const listProviders: ProviderAdapterRegistryShape[\"listProviders\"] = () =>\n    registry.listInstances.pipe(\n      Effect.map((instances) => {\n        const kinds = new Set<ProviderDriverKind>();\n        for (const instance of instances) {\n          const defaultId = defaultInstanceIdForDriver(instance.driverKind);\n          if (instance.instanceId === defaultId) {\n            // Only the default-instance rows show up through the legacy\n            // shim — custom instances like `codex_personal` have no\n            // `ProviderDriverKind` equivalent.\n            kinds.add(instance.driverKind);\n          }\n        }\n        return Array.from(kinds);\n      }),\n    );\n\n  return {\n    getByInstance,\n    getInstanceInfo,\n    listInstances,\n    listProviders,\n    // Proxy directly — the facade has no state of its own; the instance\n    // registry already coalesces adds/removes/rebuilds into one emission.\n    streamChanges: registry.streamChanges,\n    subscribeChanges: registry.subscribeChanges,\n  } satisfies ProviderAdapterRegistryShape;\n});\n\nexport const ProviderAdapterRegistryLive = Layer.effect(\n  ProviderAdapterRegistry,\n  makeProviderAdapterRegistry(),\n);\n\n// Exposed for tests that want to build a facade over a pre-assembled\n// `ProviderInstanceRegistry` without pulling in the whole boot graph.\nexport { makeProviderAdapterRegistry };\n\n// Re-export for consumers that need the accessor shape. The service tag\n// itself lives in `Services/ProviderAdapterRegistry.ts`.\nexport { ProviderAdapterRegistry } from \"../Services/ProviderAdapterRegistry.ts\";\n// Re-export for consumers (including tests) that construct a\n// `ProviderInstanceId` before calling `getByInstance`.\nexport { ProviderInstanceId };\n","// @effect-diagnostics nodeBuiltinImport:off\n/**\n * Best-effort provider event logging with one shared writer per thread.\n *\n * Native and canonical views share batching, rotation, and retention state so\n * they cannot race while appending to the same thread-scoped file.\n */\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\n\nimport type { ThreadId } from \"@t3tools/contracts\";\nimport { RotatingFileSink } from \"@t3tools/shared/logging\";\nimport { errorTag } from \"@t3tools/shared/observability\";\nimport * as Clock from \"effect/Clock\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { toSafeThreadAttachmentSegment } from \"../../attachmentStore.ts\";\nimport type { ResourceAttribution } from \"../../resourceTelemetry/ResourceAttribution.ts\";\n\nconst MEBIBYTE = 1024 * 1024;\nconst DAY_MS = 24 * 60 * 60 * 1_000;\nconst DEFAULT_MAX_BYTES = 10 * MEBIBYTE;\nconst DEFAULT_MAX_FILES = 10;\nconst DEFAULT_BATCH_WINDOW_MS = 1_000;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;\nconst DEFAULT_MAX_AGE_MS = 14 * DAY_MS;\nconst DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;\nconst DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;\nconst DEFAULT_MAX_BUFFERED_RECORDS = 512;\nconst GLOBAL_THREAD_SEGMENT = \"_global\";\nconst LOG_SCOPE = \"provider-observability\";\nconst encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst transientCanonicalEventTypes = new Set([\n  \"content.delta\",\n  \"hook.progress\",\n  \"item.updated\",\n  \"task.progress\",\n  \"thread.realtime.audio.delta\",\n  \"tool.progress\",\n  \"turn.proposed.delta\",\n]);\n\nexport type EventNdjsonStream = \"native\" | \"canonical\" | \"orchestration\";\n\nexport interface EventNdjsonLogger {\n  readonly filePath: string;\n  readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;\n  readonly close: () => Effect.Effect<void>;\n}\n\nexport interface EventNdjsonLogStore {\n  readonly filePath: string;\n  readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;\n  readonly close: () => Effect.Effect<void>;\n}\n\nexport interface EventNdjsonLogStoreOptions {\n  readonly maxBytes?: number;\n  readonly maxFiles?: number;\n  readonly batchWindowMs?: number;\n  readonly maxTotalBytes?: number;\n  readonly maxAgeMs?: number;\n  readonly retentionCheckIntervalMs?: number;\n  readonly maxBufferedBytes?: number;\n  readonly maxBufferedRecords?: number;\n  readonly attribution?: ResourceAttribution[\"Service\"];\n}\n\nexport interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {\n  readonly stream: EventNdjsonStream;\n}\n\nexport class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(\n  \"EventNdjsonLogConfigurationError\",\n  {\n    filePath: Schema.String,\n    option: Schema.String,\n    value: Schema.Number,\n    minimum: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;\n  }\n}\n\nexport class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(\n  \"EventNdjsonLogDirectoryError\",\n  {\n    directory: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to create provider event log directory '${this.directory}'`;\n  }\n}\n\nexport type EventNdjsonLogStoreError =\n  | EventNdjsonLogConfigurationError\n  | EventNdjsonLogDirectoryError;\n\ninterface ResolvedOptions {\n  readonly maxBytes: number;\n  readonly maxFiles: number;\n  readonly batchWindowMs: number;\n  readonly maxTotalBytes: number;\n  readonly maxAgeMs: number;\n  readonly retentionCheckIntervalMs: number;\n  readonly maxBufferedBytes: number;\n  readonly maxBufferedRecords: number;\n  readonly attribution: ResourceAttribution[\"Service\"] | undefined;\n}\n\nexport interface PendingRecord {\n  readonly stream: EventNdjsonStream;\n  readonly threadSegment: string;\n  readonly line: string;\n  readonly bytes: number;\n}\n\ninterface StoreState {\n  readonly pending: ReadonlyArray<PendingRecord>;\n  readonly pendingBytes: number;\n  readonly sinks: ReadonlyMap<string, RotatingFileSink>;\n  readonly flushScheduled: boolean;\n  readonly closed: boolean;\n  readonly lastRetentionAt: number;\n}\n\ninterface AttributionSummary {\n  readonly stream: EventNdjsonStream;\n  readonly count: number;\n  readonly logicalWriteBytes: number;\n}\n\ninterface FileOperationFailure {\n  readonly filePath: string;\n  readonly cause: unknown;\n}\n\ninterface RetentionResult {\n  readonly failures: ReadonlyArray<FileOperationFailure>;\n}\n\ninterface DrainResult {\n  readonly attributions: ReadonlyArray<AttributionSummary>;\n  readonly failures: ReadonlyArray<FileOperationFailure>;\n}\n\nfunction logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {\n  return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));\n}\n\nfunction resolveThreadSegment(raw: string | null | undefined): string {\n  const normalized = typeof raw === \"string\" ? toSafeThreadAttachmentSegment(raw) : null;\n  return normalized ?? GLOBAL_THREAD_SEGMENT;\n}\n\nfunction resolveStreamLabel(stream: EventNdjsonStream): string {\n  return stream === \"native\" ? \"NTIVE\" : stream === \"orchestration\" ? \"ORCH\" : \"CANON\";\n}\n\nfunction providerLogPrefix(filePath: string): string {\n  const basename = NodePath.basename(filePath);\n  const extension = NodePath.extname(basename);\n  return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;\n}\n\nfunction providerLogPath(directory: string, prefix: string, threadSegment: string): string {\n  return NodePath.join(directory, `${prefix}${threadSegment}.log`);\n}\n\nfunction shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {\n  if (stream !== \"canonical\" || typeof event !== \"object\" || event === null) {\n    return true;\n  }\n  try {\n    const type = Reflect.get(event, \"type\");\n    return typeof type !== \"string\" || !transientCanonicalEventTypes.has(type);\n  } catch {\n    return true;\n  }\n}\n\nexport function writeBatchedMessages(\n  sink: Pick<RotatingFileSink, \"write\">,\n  records: ReadonlyArray<PendingRecord>,\n  maxBytes: number,\n  onWritten: (records: ReadonlyArray<PendingRecord>) => void,\n): void {\n  let pendingRecords: Array<PendingRecord> = [];\n  let pendingBytes = 0;\n\n  const flush = () => {\n    if (pendingRecords.length === 0) return;\n    const writtenRecords = pendingRecords;\n    sink.write(writtenRecords.map((record) => record.line).join(\"\"));\n    onWritten(writtenRecords);\n    pendingRecords = [];\n    pendingBytes = 0;\n  };\n\n  for (const record of records) {\n    if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {\n      flush();\n    }\n    pendingRecords.push(record);\n    pendingBytes += record.bytes;\n    if (pendingBytes >= maxBytes) {\n      flush();\n    }\n  }\n  flush();\n}\n\nfunction isProviderLogFile(filePath: string, fileName: string, filePrefix: string): boolean {\n  if (!/\\.log(?:\\.\\d+)?$/u.test(fileName)) return false;\n  if (fileName.startsWith(filePrefix)) return true;\n\n  const descriptor = NodeFS.openSync(filePath, \"r\");\n  try {\n    const header = Buffer.alloc(256);\n    const bytesRead = NodeFS.readSync(descriptor, header, 0, header.byteLength, 0);\n    return /^\\[[^\\]\\r\\n]+\\] (?:NTIVE|CANON|ORCH): /u.test(header.toString(\"utf8\", 0, bytesRead));\n  } finally {\n    NodeFS.closeSync(descriptor);\n  }\n}\n\nfunction enforceRetention(input: {\n  readonly directory: string;\n  readonly maxTotalBytes: number;\n  readonly maxAgeMs: number;\n  readonly activeFilePaths: ReadonlySet<string>;\n  readonly filePrefix: string;\n  readonly now: number;\n}): RetentionResult {\n  const failures: Array<FileOperationFailure> = [];\n  const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];\n\n  let entries: ReadonlyArray<NodeFS.Dirent>;\n  try {\n    entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });\n  } catch (cause) {\n    return { failures: [{ filePath: input.directory, cause }] };\n  }\n\n  for (const entry of entries) {\n    if (!entry.isFile()) continue;\n    const filePath = NodePath.join(input.directory, entry.name);\n    try {\n      if (!isProviderLogFile(filePath, entry.name, input.filePrefix)) continue;\n      const stat = NodeFS.statSync(filePath);\n      files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });\n    } catch (cause) {\n      failures.push({ filePath, cause });\n    }\n  }\n\n  let totalBytes = files.reduce((total, file) => total + file.size, 0);\n  const remove = (file: (typeof files)[number]) => {\n    if (input.activeFilePaths.has(file.filePath)) return false;\n    try {\n      NodeFS.rmSync(file.filePath, { force: true });\n      totalBytes -= file.size;\n      return true;\n    } catch (cause) {\n      failures.push({ filePath: file.filePath, cause });\n      return false;\n    }\n  };\n\n  const retained = files.filter((file) => {\n    if (input.now - file.mtimeMs <= input.maxAgeMs) return true;\n    return !remove(file);\n  });\n\n  for (const file of retained.toSorted(\n    (left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),\n  )) {\n    if (totalBytes <= input.maxTotalBytes) break;\n    remove(file);\n  }\n\n  return { failures };\n}\n\nfunction validateOption(input: {\n  readonly filePath: string;\n  readonly option: string;\n  readonly value: number;\n  readonly minimum: number;\n}): EventNdjsonLogConfigurationError | undefined {\n  if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;\n  return new EventNdjsonLogConfigurationError(input);\n}\n\nfunction resolveOptions(\n  filePath: string,\n  options: EventNdjsonLogStoreOptions,\n): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {\n  const resolved = {\n    maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n    maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,\n    batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,\n    maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n    maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,\n    retentionCheckIntervalMs:\n      options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,\n    maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,\n    maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,\n    attribution: options.attribution,\n  } satisfies ResolvedOptions;\n\n  const validations = [\n    [\"maxBytes\", resolved.maxBytes, 1],\n    [\"maxFiles\", resolved.maxFiles, 1],\n    [\"batchWindowMs\", resolved.batchWindowMs, 0],\n    [\"maxTotalBytes\", resolved.maxTotalBytes, 1],\n    [\"maxAgeMs\", resolved.maxAgeMs, 1],\n    [\"retentionCheckIntervalMs\", resolved.retentionCheckIntervalMs, 1],\n    [\"maxBufferedBytes\", resolved.maxBufferedBytes, 1],\n    [\"maxBufferedRecords\", resolved.maxBufferedRecords, 1],\n  ] as const;\n\n  for (const [option, value, minimum] of validations) {\n    const error = validateOption({ filePath, option, value, minimum });\n    if (error) return Effect.fail(error);\n  }\n  return Effect.succeed(resolved);\n}\n\nfunction drainPending(input: {\n  readonly directory: string;\n  readonly options: ResolvedOptions;\n  readonly state: StoreState;\n  readonly filePrefix: string;\n  readonly now: number;\n  readonly timerFired: boolean;\n  readonly close: boolean;\n}): readonly [DrainResult, StoreState] {\n  if (input.state.closed) {\n    return [{ attributions: [], failures: [] }, input.state];\n  }\n\n  const sinks = new Map(input.state.sinks);\n  const failures: Array<FileOperationFailure> = [];\n  const attributionByStream = new Map<\n    EventNdjsonStream,\n    { count: number; logicalWriteBytes: number }\n  >();\n  const recordsBySegment = new Map<string, Array<PendingRecord>>();\n\n  for (const record of input.state.pending) {\n    const records = recordsBySegment.get(record.threadSegment) ?? [];\n    records.push(record);\n    recordsBySegment.set(record.threadSegment, records);\n  }\n\n  for (const [threadSegment, records] of recordsBySegment) {\n    const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);\n    let sink = sinks.get(threadSegment);\n    if (!sink) {\n      try {\n        sink = new RotatingFileSink({\n          filePath,\n          maxBytes: input.options.maxBytes,\n          maxFiles: input.options.maxFiles,\n          throwOnError: true,\n        });\n        sinks.set(threadSegment, sink);\n      } catch (cause) {\n        failures.push({ filePath, cause });\n        continue;\n      }\n    }\n\n    try {\n      writeBatchedMessages(sink, records, input.options.maxBytes, (writtenRecords) => {\n        for (const record of writtenRecords) {\n          const current = attributionByStream.get(record.stream) ?? {\n            count: 0,\n            logicalWriteBytes: 0,\n          };\n          attributionByStream.set(record.stream, {\n            count: current.count + 1,\n            logicalWriteBytes: current.logicalWriteBytes + record.bytes,\n          });\n        }\n      });\n    } catch (cause) {\n      sinks.delete(threadSegment);\n      failures.push({ filePath, cause });\n    }\n  }\n\n  const retentionDue =\n    input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;\n  const retention = retentionDue\n    ? enforceRetention({\n        directory: input.directory,\n        maxTotalBytes: input.options.maxTotalBytes,\n        maxAgeMs: input.options.maxAgeMs,\n        activeFilePaths: new Set(\n          Array.from(sinks.keys(), (threadSegment) =>\n            providerLogPath(input.directory, input.filePrefix, threadSegment),\n          ),\n        ),\n        filePrefix: input.filePrefix,\n        now: input.now,\n      })\n    : { failures: [] };\n\n  return [\n    {\n      attributions: Array.from(attributionByStream, ([stream, value]) => ({\n        stream,\n        ...value,\n      })),\n      failures: [...failures, ...retention.failures],\n    },\n    {\n      pending: [],\n      pendingBytes: 0,\n      sinks,\n      flushScheduled: input.timerFired ? false : input.state.flushScheduled,\n      closed: input.close,\n      lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,\n    },\n  ];\n}\n\nconst serializeEvent = Effect.fnUntraced(function* (event: unknown) {\n  return yield* encodeUnknownJsonString(event).pipe(\n    Effect.catch((error) =>\n      logWarning(\"failed to serialize provider event log record\", {\n        errorTag: errorTag(error),\n      }).pipe(Effect.as(undefined)),\n    ),\n  );\n});\n\nexport const makeEventNdjsonLogStore = Effect.fnUntraced(function* (\n  filePath: string,\n  options: EventNdjsonLogStoreOptions = {},\n): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {\n  const resolved = yield* resolveOptions(filePath, options);\n  const directory = NodePath.dirname(filePath);\n  const filePrefix = providerLogPrefix(filePath);\n\n  yield* Effect.try({\n    try: () => NodeFS.mkdirSync(directory, { recursive: true }),\n    catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),\n  });\n\n  const initializedAt = yield* Clock.currentTimeMillis;\n  const initialRetention = yield* Effect.sync(() =>\n    enforceRetention({\n      directory,\n      maxTotalBytes: resolved.maxTotalBytes,\n      maxAgeMs: resolved.maxAgeMs,\n      activeFilePaths: new Set(),\n      filePrefix,\n      now: initializedAt,\n    }),\n  );\n  for (const failure of initialRetention.failures) {\n    yield* logWarning(\"provider event log retention failed\", {\n      filePath: failure.filePath,\n      errorTag: errorTag(failure.cause),\n    });\n  }\n\n  const stateRef = yield* SynchronizedRef.make<StoreState>({\n    pending: [],\n    pendingBytes: 0,\n    sinks: new Map(),\n    flushScheduled: false,\n    closed: false,\n    lastRetentionAt: initializedAt,\n  });\n  const timerScope = yield* Scope.make();\n\n  const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {\n    const startedAt = yield* Clock.currentTimeMillis;\n    const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>\n      Effect.sync(() =>\n        drainPending({\n          directory,\n          options: resolved,\n          state,\n          filePrefix,\n          now: startedAt,\n          timerFired,\n          close,\n        }),\n      ),\n    );\n\n    for (const failure of result.failures) {\n      yield* logWarning(\"provider event log write or retention failed\", {\n        filePath: failure.filePath,\n        errorTag: errorTag(failure.cause),\n      });\n    }\n\n    if (resolved.attribution && result.attributions.length > 0) {\n      const completedAt = yield* Clock.currentTimeMillis;\n      const durationMs = Math.max(0, completedAt - startedAt);\n      const totalBytes = result.attributions.reduce(\n        (total, entry) => total + entry.logicalWriteBytes,\n        0,\n      );\n      yield* Effect.forEach(\n        result.attributions,\n        (entry) =>\n          resolved.attribution?.record({\n            component: \"provider-event-log\",\n            operation: `${entry.stream}.append`,\n            logicalWriteBytes: entry.logicalWriteBytes,\n            count: entry.count,\n            durationMs:\n              totalBytes === 0\n                ? 0\n                : Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),\n          }) ?? Effect.void,\n        { discard: true },\n      );\n    }\n  });\n\n  const scheduleFlush = Effect.fnUntraced(function* () {\n    yield* Effect.forkIn(\n      Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),\n      timerScope,\n      { startImmediately: true },\n    );\n  });\n\n  const close = Effect.fnUntraced(function* () {\n    yield* flush(false, true);\n    yield* Scope.close(timerScope, Exit.void);\n  });\n\n  const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();\n  const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {\n    const existing = loggerViews.get(stream);\n    if (existing) return existing;\n\n    const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {\n      if (!shouldPersist(stream, event)) return;\n      const payload = yield* serializeEvent(event);\n      if (payload === undefined) return;\n\n      const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));\n      const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\\n`;\n      const bytes = Buffer.byteLength(line);\n      const action = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {\n        if (state.closed) {\n          return Effect.succeed([{ flush: false }, state] as const);\n        }\n        const pending = [\n          ...state.pending,\n          { stream, threadSegment: resolveThreadSegment(threadId), line, bytes },\n        ];\n        const pendingBytes = state.pendingBytes + bytes;\n        const flush =\n          resolved.batchWindowMs === 0 ||\n          pending.length >= resolved.maxBufferedRecords ||\n          pendingBytes >= resolved.maxBufferedBytes;\n        const schedule = !flush && !state.flushScheduled;\n        const nextState = {\n          ...state,\n          pending,\n          pendingBytes,\n          flushScheduled: state.flushScheduled || schedule,\n        };\n        return (schedule ? scheduleFlush() : Effect.void).pipe(\n          Effect.as([{ flush }, nextState] as const),\n        );\n      }).pipe(Effect.uninterruptible);\n\n      if (action.flush) {\n        yield* flush(false, false);\n      }\n    });\n\n    const view = { filePath, write, close: () => Effect.void } satisfies EventNdjsonLogger;\n    loggerViews.set(stream, view);\n    return view;\n  };\n\n  return { filePath, logger, close } satisfies EventNdjsonLogStore;\n});\n\nexport const makeEventNdjsonLogger = Effect.fnUntraced(function* (\n  filePath: string,\n  options: EventNdjsonLoggerOptions,\n): Effect.fn.Return<EventNdjsonLogger | undefined> {\n  const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(\n    Effect.catch((error) =>\n      logWarning(error.message, { error }).pipe(\n        Effect.as<EventNdjsonLogStore | undefined>(undefined),\n      ),\n    ),\n  );\n  if (!store) return undefined;\n  return { ...store.logger(options.stream), close: store.close };\n});\n","/**\n * ProviderEventLoggers — single observability service that owns the shared\n * provider event log store and exposes its two runtime views:\n *\n *   - `native`    — provider-protocol events as the SDK emits them, written\n *                   from inside each `<X>Adapter` factory.\n *   - `canonical` — runtime events after `ProviderService` has normalized\n *                   them onto `ProviderRuntimeEvent`.\n *\n * Why a service tag and not constructor options?\n *\n *   - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),\n *     not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`\n *     call site where we can hand an `EventNdjsonLogger` in by hand.\n *   - Multiple driver instances per kind (`codex_personal`, `codex_work`)\n *     must share one underlying log store — opening N writers against the\n *     same rotating file would race the rotation logic. Owning the loggers on\n *     a single tag keeps that invariant intact.\n *   - Tests can swap one (or both) loggers with in-memory recorders by\n *     `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of\n *     juggling per-Layer option threading.\n *\n * Both fields are optional because observability must not prevent startup.\n *\n * @module provider/Layers/ProviderEventLoggers\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { ServerConfig } from \"../../config.ts\";\nimport * as ResourceAttribution from \"../../resourceTelemetry/ResourceAttribution.ts\";\nimport * as EventNdjsonLogger from \"./EventNdjsonLogger.ts\";\n\n/**\n * Shared logger pair for native + canonical provider event streams.\n *\n * Service value is intentionally a struct of two optional loggers rather\n * than two parallel tags. Construction site is one place\n * (`layer`); consumers (drivers, `ProviderService`) read one tag and pluck the\n * field they need.\n */\nexport class ProviderEventLoggers extends Context.Service<\n  ProviderEventLoggers,\n  {\n    readonly native: EventNdjsonLogger.EventNdjsonLogger | undefined;\n    readonly canonical: EventNdjsonLogger.EventNdjsonLogger | undefined;\n  }\n>()(\"t3/provider/Layers/ProviderEventLoggers\") {}\n\n/**\n * Constant value used by tests / boot layers that want to opt out of native\n * + canonical logging entirely. Keeps the tag non-optional in the type\n * system while letting the runtime treat absence as a no-op.\n */\nexport const NoOpProviderEventLoggers: ProviderEventLoggers[\"Service\"] = {\n  native: undefined,\n  canonical: undefined,\n};\n\n/**\n * Builds both stream views over one shared store. Setup failures are logged\n * and downgraded to the no-op service so diagnostics never block startup.\n */\nexport const make = Effect.gen(function* () {\n  const { providerEventLogPath } = yield* ServerConfig;\n  const attribution = yield* ResourceAttribution.ResourceAttribution;\n  const store = yield* EventNdjsonLogger.makeEventNdjsonLogStore(providerEventLogPath, {\n    attribution,\n  }).pipe(\n    Effect.catch((error) =>\n      Effect.logWarning(error.message, { error }).pipe(\n        Effect.annotateLogs({ scope: \"provider-observability\" }),\n        Effect.as<EventNdjsonLogger.EventNdjsonLogStore | undefined>(undefined),\n      ),\n    ),\n  );\n\n  if (!store) {\n    return ProviderEventLoggers.of(NoOpProviderEventLoggers);\n  }\n\n  yield* Effect.addFinalizer(() => store.close());\n  return ProviderEventLoggers.of({\n    native: store.logger(\"native\"),\n    canonical: store.logger(\"canonical\"),\n  });\n});\n\nexport const layer = Layer.effect(ProviderEventLoggers, make);\n","/**\n * ProviderServiceLive - Cross-provider orchestration layer.\n *\n * Routes validated transport/API calls to provider adapters through\n * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a\n * unified provider event stream for subscribers.\n *\n * It does not implement provider protocol details (adapter concern).\n *\n * @module ProviderServiceLive\n */\nimport {\n  ModelSelection,\n  NonNegativeInt,\n  ThreadId,\n  ProviderInterruptTurnInput,\n  ProviderRespondToRequestInput,\n  ProviderRespondToUserInputInput,\n  ProviderSendTurnInput,\n  ProviderSessionStartInput,\n  ProviderStopSessionInput,\n  type ProviderInstanceId,\n  type ProviderDriverKind,\n  type ProviderRuntimeEvent,\n  type ProviderSession,\n} from \"@t3tools/contracts\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n  increment,\n  providerMetricAttributes,\n  providerRuntimeEventsTotal,\n  providerSessionsTotal,\n  providerTurnDuration,\n  providerTurnsTotal,\n  providerTurnMetricAttributes,\n  withMetrics,\n} from \"../../observability/Metrics.ts\";\nimport { type ProviderAdapterError, ProviderValidationError } from \"../Errors.ts\";\nimport type { ProviderAdapterShape } from \"../Services/ProviderAdapter.ts\";\nimport * as ProviderAdapterRegistry from \"../Services/ProviderAdapterRegistry.ts\";\nimport * as ProviderService from \"../Services/ProviderService.ts\";\nimport * as ProviderSessionDirectory from \"../Services/ProviderSessionDirectory.ts\";\nimport { type EventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nimport * as ProviderEventLoggers from \"./ProviderEventLoggers.ts\";\nimport * as AnalyticsService from \"../../telemetry/AnalyticsService.ts\";\nconst isModelSelection = Schema.is(ModelSelection);\n\n/**\n * Hook for tests that want to override the canonical event logger pulled\n * from `ProviderEventLoggers`. Production wiring leaves this undefined and\n * reads the logger off the tag.\n */\nexport interface ProviderServiceLiveOptions {\n  readonly canonicalEventLogger?: EventNdjsonLogger;\n}\n\ntype ProviderServiceMethod<Name extends keyof ProviderService.ProviderService[\"Service\"]> =\n  ProviderService.ProviderService[\"Service\"][Name];\n\nconst ProviderRollbackConversationInput = Schema.Struct({\n  threadId: ThreadId,\n  numTurns: NonNegativeInt,\n});\n\nfunction toValidationError(\n  operation: string,\n  issue: string,\n  cause?: unknown,\n): ProviderValidationError {\n  return new ProviderValidationError({\n    operation,\n    issue,\n    ...(cause !== undefined ? { cause } : {}),\n  });\n}\n\nconst decodeInputOrValidationError = <S extends Schema.Top>(input: {\n  readonly operation: string;\n  readonly schema: S;\n  readonly payload: unknown;\n}) => {\n  const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema);\n  return decodeProviderRequestInput(input.payload).pipe(\n    Effect.mapError(\n      (schemaError) =>\n        new ProviderValidationError({\n          operation: input.operation,\n          issue: SchemaIssue.makeFormatterDefault()(schemaError.issue),\n          cause: schemaError,\n        }),\n    ),\n  );\n};\n\nfunction toRuntimeStatus(session: ProviderSession): \"starting\" | \"running\" | \"stopped\" | \"error\" {\n  switch (session.status) {\n    case \"connecting\":\n      return \"starting\";\n    case \"error\":\n      return \"error\";\n    case \"closed\":\n      return \"stopped\";\n    case \"ready\":\n    case \"running\":\n    default:\n      return \"running\";\n  }\n}\n\nfunction toRuntimePayloadFromSession(\n  session: ProviderSession,\n  extra?: {\n    readonly modelSelection?: unknown;\n    readonly lastRuntimeEvent?: string;\n    readonly lastRuntimeEventAt?: string;\n  },\n): Record<string, unknown> {\n  return {\n    cwd: session.cwd ?? null,\n    model: session.model ?? null,\n    activeTurnId: session.activeTurnId ?? null,\n    lastError: session.lastError ?? null,\n    ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),\n    ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),\n    ...(extra?.lastRuntimeEventAt !== undefined\n      ? { lastRuntimeEventAt: extra.lastRuntimeEventAt }\n      : {}),\n  };\n}\n\nfunction readPersistedModelSelection(\n  runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding[\"runtimePayload\"],\n): ModelSelection | undefined {\n  if (!runtimePayload || typeof runtimePayload !== \"object\" || Array.isArray(runtimePayload)) {\n    return undefined;\n  }\n  const raw = \"modelSelection\" in runtimePayload ? runtimePayload.modelSelection : undefined;\n  return isModelSelection(raw) ? raw : undefined;\n}\n\nfunction readPersistedCwd(\n  runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding[\"runtimePayload\"],\n): string | undefined {\n  if (!runtimePayload || typeof runtimePayload !== \"object\" || Array.isArray(runtimePayload)) {\n    return undefined;\n  }\n  const rawCwd = \"cwd\" in runtimePayload ? runtimePayload.cwd : undefined;\n  if (typeof rawCwd !== \"string\") return undefined;\n  const trimmed = rawCwd.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nconst dieOnMissingBindingInstanceId = (\n  operation: string,\n  payload: {\n    readonly providerInstanceId?: ProviderInstanceId | undefined;\n    readonly provider?: ProviderDriverKind | undefined;\n  },\n): ProviderInstanceId => {\n  if (payload.providerInstanceId !== undefined) {\n    return payload.providerInstanceId;\n  }\n  throw new Error(\n    payload.provider\n      ? `${operation}: provider instance id is required for provider '${payload.provider}'.`\n      : `${operation}: provider instance id is required.`,\n  );\n};\n\nconst correlateRuntimeEventWithInstance = (\n  source: {\n    readonly instanceId: ProviderInstanceId;\n    readonly provider: ProviderDriverKind;\n  },\n  event: ProviderRuntimeEvent,\n): ProviderRuntimeEvent => {\n  if (event.provider !== source.provider) {\n    throw new Error(\n      `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,\n    );\n  }\n  if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {\n    throw new Error(\n      `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,\n    );\n  }\n  return { ...event, providerInstanceId: source.instanceId };\n};\n\nconst makeProviderService = Effect.fn(\"makeProviderService\")(function* (\n  options?: ProviderServiceLiveOptions,\n) {\n  const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);\n  const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;\n  // Options-provided logger wins (test overrides); otherwise we take whatever\n  // the `ProviderEventLoggers` tag exposes — `undefined` means \"no canonical\n  // log writer is attached\", which downstream code already handles as a\n  // no-op.\n  const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;\n\n  const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;\n  const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;\n  const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();\n  const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\n  const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>\n    Effect.succeed(event).pipe(\n      Effect.tap((canonicalEvent) =>\n        canonicalEventLogger\n          ? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId)\n          : Effect.void,\n      ),\n      Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),\n      Effect.asVoid,\n    );\n\n  const requireBindingInstanceId = (\n    operation: string,\n    payload: {\n      readonly providerInstanceId?: ProviderInstanceId | undefined;\n      readonly provider?: ProviderDriverKind | undefined;\n    },\n  ): Effect.Effect<ProviderInstanceId, ProviderValidationError> =>\n    payload.providerInstanceId !== undefined\n      ? Effect.succeed(payload.providerInstanceId)\n      : Effect.fail(\n          toValidationError(\n            operation,\n            payload.provider\n              ? `Provider instance id is required for provider '${payload.provider}'.`\n              : \"Provider instance id is required.\",\n          ),\n        );\n\n  const upsertSessionBinding = (\n    session: ProviderSession,\n    threadId: ThreadId,\n    extra?: {\n      readonly modelSelection?: unknown;\n      readonly lastRuntimeEvent?: string;\n      readonly lastRuntimeEventAt?: string;\n    },\n  ) =>\n    Effect.gen(function* () {\n      const providerInstanceId = yield* requireBindingInstanceId(\n        \"ProviderService.upsertSessionBinding\",\n        session,\n      );\n      yield* directory.upsert({\n        threadId,\n        provider: session.provider,\n        providerInstanceId,\n        runtimeMode: session.runtimeMode,\n        status: toRuntimeStatus(session),\n        ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),\n        runtimePayload: toRuntimePayloadFromSession(session, extra),\n      });\n    });\n\n  const processRuntimeEvent = (\n    source: {\n      readonly instanceId: ProviderInstanceId;\n      readonly provider: ProviderDriverKind;\n    },\n    event: ProviderRuntimeEvent,\n  ): Effect.Effect<void> =>\n    Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe(\n      Effect.flatMap((canonicalEvent) =>\n        increment(providerRuntimeEventsTotal, {\n          provider: canonicalEvent.provider,\n          eventType: canonicalEvent.type,\n        }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),\n      ),\n    );\n\n  // `subscribedAdapters` is our source-of-truth for \"which instance adapters\n  // are currently wired into the runtime event bus\". It both tracks the set\n  // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and\n  // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter\n  // list consumed by `stopStaleSessionsForThread`, `listSessions`, and\n  // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added\n  // instances become visible to those call sites as soon as settings edits\n  // land.\n  const subscribedAdapters = yield* Ref.make(\n    new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),\n  );\n\n  const getAdapterEntries = Ref.get(subscribedAdapters).pipe(\n    Effect.map((map) => Array.from(map.entries())),\n  );\n\n  // Rebuild the map of id → adapter from the registry and fork a new event\n  // subscription for every instance that is either brand new or whose adapter\n  // identity changed (indicating the underlying `ProviderInstance` was torn\n  // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned\n  // fibers for removed/replaced instances exit on their own because their\n  // adapter's `streamEvents` source terminates when the old scope closes.\n  const reconcileInstanceSubscriptions = Effect.gen(function* () {\n    const previous = yield* Ref.get(subscribedAdapters);\n    const currentIds = yield* registry.listInstances();\n    const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();\n    for (const id of currentIds) {\n      const adapterOption = yield* registry\n        .getByInstance(id)\n        .pipe(Effect.tapError(Effect.logWarning), Effect.option);\n      if (Option.isNone(adapterOption)) continue;\n      const adapter = adapterOption.value;\n      next.set(id, adapter);\n      if (previous.get(id) !== adapter) {\n        yield* Stream.runForEach(adapter.streamEvents, (event) =>\n          processRuntimeEvent(\n            {\n              instanceId: id,\n              provider: adapter.provider,\n            },\n            event,\n          ),\n        ).pipe(Effect.forkScoped);\n      }\n    }\n    yield* Ref.set(subscribedAdapters, next);\n  });\n\n  const instanceChanges = yield* registry.subscribeChanges;\n  yield* reconcileInstanceSubscriptions;\n  yield* Stream.runForEach(\n    Stream.fromSubscription(instanceChanges),\n    () => reconcileInstanceSubscriptions,\n  ).pipe(Effect.forkScoped);\n\n  const recoverSessionForThread = Effect.fn(\"recoverSessionForThread\")(function* (input: {\n    readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding;\n    readonly operation: string;\n  }) {\n    const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);\n    yield* Effect.annotateCurrentSpan({\n      \"provider.operation\": \"recover-session\",\n      \"provider.kind\": input.binding.provider,\n      \"provider.instance_id\": bindingInstanceId,\n      \"provider.thread_id\": input.binding.threadId,\n    });\n    return yield* Effect.gen(function* () {\n      const adapter = yield* registry.getByInstance(bindingInstanceId);\n      const hasResumeCursor =\n        input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;\n      const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);\n      if (hasActiveSession) {\n        const activeSessions = yield* adapter.listSessions();\n        const existing = activeSessions.find(\n          (session) => session.threadId === input.binding.threadId,\n        );\n        if (existing) {\n          yield* upsertSessionBinding(\n            { ...existing, providerInstanceId: bindingInstanceId },\n            input.binding.threadId,\n          );\n          yield* analytics.record(\"provider.session.recovered\", {\n            provider: existing.provider,\n            strategy: \"adopt-existing\",\n            hasResumeCursor: existing.resumeCursor !== undefined,\n          });\n          return { adapter, session: existing } as const;\n        }\n      }\n\n      if (!hasResumeCursor) {\n        return yield* toValidationError(\n          input.operation,\n          `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,\n        );\n      }\n\n      const persistedCwd = readPersistedCwd(input.binding.runtimePayload);\n      const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);\n\n      const resumed = yield* adapter\n        .startSession({\n          threadId: input.binding.threadId,\n          provider: input.binding.provider,\n          providerInstanceId: bindingInstanceId,\n          ...(persistedCwd ? { cwd: persistedCwd } : {}),\n          ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),\n          ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),\n          runtimeMode: input.binding.runtimeMode ?? \"full-access\",\n        })\n        ;\n      if (resumed.provider !== adapter.provider) {\n        return yield* toValidationError(\n          input.operation,\n          `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,\n        );\n      }\n\n      yield* upsertSessionBinding(\n        { ...resumed, providerInstanceId: bindingInstanceId },\n        input.binding.threadId,\n      );\n      yield* analytics.record(\"provider.session.recovered\", {\n        provider: resumed.provider,\n        strategy: \"resume-thread\",\n        hasResumeCursor: resumed.resumeCursor !== undefined,\n      });\n      return { adapter, session: resumed } as const;\n    }).pipe(\n      withMetrics({\n        counter: providerSessionsTotal,\n        attributes: providerMetricAttributes(input.binding.provider, {\n          operation: \"recover\",\n        }),\n      }),\n    );\n  });\n\n  const resolveRoutableSession = Effect.fn(\"resolveRoutableSession\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly operation: string;\n    readonly allowRecovery: boolean;\n  }) {\n    const bindingOption = yield* directory.getBinding(input.threadId);\n    const binding = Option.getOrUndefined(bindingOption);\n    if (!binding) {\n      return yield* toValidationError(\n        input.operation,\n        `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,\n      );\n    }\n    const instanceId = yield* requireBindingInstanceId(input.operation, binding);\n    const adapter = yield* registry.getByInstance(instanceId);\n\n    const hasRequestedSession = yield* adapter.hasSession(input.threadId);\n    if (hasRequestedSession) {\n      return {\n        adapter,\n        instanceId,\n        threadId: input.threadId,\n        isActive: true,\n      } as const;\n    }\n\n    if (!input.allowRecovery) {\n      return {\n        adapter,\n        instanceId,\n        threadId: input.threadId,\n        isActive: false,\n      } as const;\n    }\n\n    const recovered = yield* recoverSessionForThread({\n      binding,\n      operation: input.operation,\n    });\n    return {\n      adapter: recovered.adapter,\n      instanceId,\n      threadId: input.threadId,\n      isActive: true,\n    } as const;\n  });\n\n  const stopStaleSessionsForThread = Effect.fn(\"stopStaleSessionsForThread\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly currentInstanceId: ProviderInstanceId;\n  }) {\n    const currentAdapters = yield* getAdapterEntries;\n    yield* Effect.forEach(\n      currentAdapters,\n      ([instanceId, adapter]) =>\n        instanceId === input.currentInstanceId\n          ? Effect.void\n          : Effect.gen(function* () {\n              const hasSession = yield* adapter.hasSession(input.threadId);\n              if (!hasSession) {\n                return;\n              }\n\n              yield* adapter.stopSession(input.threadId).pipe(\n                Effect.tap(() =>\n                  analytics.record(\"provider.session.stopped\", {\n                    provider: adapter.provider,\n                  }),\n                ),\n                Effect.catchCause((cause) =>\n                  Effect.logWarning(\"provider.session.stop-stale-failed\", {\n                    threadId: input.threadId,\n                    provider: adapter.provider,\n                    cause,\n                  }),\n                ),\n              );\n            }),\n      { discard: true },\n    );\n  });\n\n  const startSession: ProviderServiceMethod<\"startSession\"> = Effect.fn(\"startSession\")(\n    function* (threadId, rawInput) {\n      const parsed = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.startSession\",\n        schema: ProviderSessionStartInput,\n        payload: rawInput,\n      });\n\n      const resolvedInstanceId = yield* requireBindingInstanceId(\n        \"ProviderService.startSession\",\n        parsed,\n      );\n      let metricProvider = parsed.provider ?? String(resolvedInstanceId);\n      yield* Effect.annotateCurrentSpan({\n        \"provider.operation\": \"start-session\",\n        \"provider.instance_id\": resolvedInstanceId,\n        \"provider.thread_id\": threadId,\n        \"provider.runtime_mode\": parsed.runtimeMode,\n      });\n      return yield* Effect.gen(function* () {\n        const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);\n        const resolvedProvider = instanceInfo.driverKind;\n        metricProvider = resolvedProvider;\n        if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {\n          return yield* toValidationError(\n            \"ProviderService.startSession\",\n            `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,\n          );\n        }\n        const input = {\n          ...parsed,\n          threadId,\n          provider: resolvedProvider,\n        };\n        if (!instanceInfo.enabled) {\n          return yield* toValidationError(\n            \"ProviderService.startSession\",\n            `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`,\n          );\n        }\n        const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));\n        const effectiveResumeCursor =\n          input.resumeCursor ??\n          (persistedBinding?.providerInstanceId === resolvedInstanceId\n            ? persistedBinding.resumeCursor\n            : undefined);\n        const effectiveCwd =\n          input.cwd ??\n          (persistedBinding?.providerInstanceId === resolvedInstanceId\n            ? readPersistedCwd(persistedBinding.runtimePayload)\n            : undefined);\n        yield* Effect.annotateCurrentSpan({\n          \"provider.kind\": resolvedProvider,\n          \"provider.resume_cursor.source\":\n            input.resumeCursor !== undefined\n              ? \"request\"\n              : effectiveResumeCursor !== undefined &&\n                  persistedBinding?.providerInstanceId === resolvedInstanceId\n                ? \"persisted\"\n                : \"none\",\n          \"provider.resume_cursor.present\": effectiveResumeCursor !== undefined,\n          \"provider.cwd.source\":\n            input.cwd !== undefined\n              ? \"request\"\n              : effectiveCwd !== undefined &&\n                  persistedBinding?.providerInstanceId === resolvedInstanceId\n                ? \"persisted\"\n                : \"none\",\n          \"provider.cwd.effective\": effectiveCwd ?? \"\",\n        });\n        const adapter = yield* registry.getByInstance(resolvedInstanceId);\n        const session = yield* adapter\n          .startSession({\n            ...input,\n            providerInstanceId: resolvedInstanceId,\n            ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),\n            ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),\n          })\n          ;\n\n        if (session.provider !== adapter.provider) {\n          return yield* toValidationError(\n            \"ProviderService.startSession\",\n            `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,\n          );\n        }\n        const sessionWithInstance = {\n          ...session,\n          providerInstanceId: resolvedInstanceId,\n        };\n\n        yield* stopStaleSessionsForThread({\n          threadId,\n          currentInstanceId: resolvedInstanceId,\n        });\n        yield* upsertSessionBinding(sessionWithInstance, threadId, {\n          modelSelection: input.modelSelection,\n        });\n        yield* analytics.record(\"provider.session.started\", {\n          provider: sessionWithInstance.provider,\n          runtimeMode: input.runtimeMode,\n          hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,\n          hasCwd: typeof effectiveCwd === \"string\" && effectiveCwd.trim().length > 0,\n          hasModel:\n            typeof input.modelSelection?.model === \"string\" &&\n            input.modelSelection.model.trim().length > 0,\n        });\n\n        return sessionWithInstance;\n      }).pipe(\n        withMetrics({\n          counter: providerSessionsTotal,\n          attributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"start\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const sendTurn: ProviderServiceMethod<\"sendTurn\"> = Effect.fn(\"sendTurn\")(function* (rawInput) {\n    const parsed = yield* decodeInputOrValidationError({\n      operation: \"ProviderService.sendTurn\",\n      schema: ProviderSendTurnInput,\n      payload: rawInput,\n    });\n\n    const input = {\n      ...parsed,\n      attachments: parsed.attachments ?? [],\n    };\n    if (!input.input && input.attachments.length === 0) {\n      return yield* toValidationError(\n        \"ProviderService.sendTurn\",\n        \"Either input text or at least one attachment is required\",\n      );\n    }\n    yield* Effect.annotateCurrentSpan({\n      \"provider.operation\": \"send-turn\",\n      \"provider.thread_id\": input.threadId,\n      \"provider.interaction_mode\": input.interactionMode,\n      \"provider.attachment_count\": input.attachments.length,\n    });\n    let metricProvider = \"unknown\";\n    let metricModel = input.modelSelection?.model;\n    return yield* Effect.gen(function* () {\n      const routed = yield* resolveRoutableSession({\n        threadId: input.threadId,\n        operation: \"ProviderService.sendTurn\",\n        allowRecovery: true,\n      });\n      metricProvider = routed.adapter.provider;\n      metricModel = input.modelSelection?.model;\n      yield* Effect.annotateCurrentSpan({\n        \"provider.kind\": routed.adapter.provider,\n        ...(input.modelSelection?.model ? { \"provider.model\": input.modelSelection.model } : {}),\n      });\n      const turn = yield* routed.adapter.sendTurn(input);\n      yield* directory.upsert({\n        threadId: input.threadId,\n        provider: routed.adapter.provider,\n        providerInstanceId: routed.instanceId,\n        status: \"running\",\n        ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),\n        runtimePayload: {\n          ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),\n          activeTurnId: turn.turnId,\n          lastRuntimeEvent: \"provider.sendTurn\",\n          lastRuntimeEventAt: yield* nowIso,\n        },\n      });\n      yield* analytics.record(\"provider.turn.sent\", {\n        provider: routed.adapter.provider,\n        model: input.modelSelection?.model,\n        interactionMode: input.interactionMode,\n        attachmentCount: input.attachments.length,\n        hasInput: typeof input.input === \"string\" && input.input.trim().length > 0,\n      });\n      return turn;\n    }).pipe(\n      withMetrics({\n        counter: providerTurnsTotal,\n        timer: providerTurnDuration,\n        attributes: () =>\n          providerTurnMetricAttributes({\n            provider: metricProvider,\n            model: metricModel,\n            extra: {\n              operation: \"send\",\n            },\n          }),\n      }),\n    );\n  });\n\n  const interruptTurn: ProviderServiceMethod<\"interruptTurn\"> = Effect.fn(\"interruptTurn\")(\n    function* (rawInput) {\n      const input = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.interruptTurn\",\n        schema: ProviderInterruptTurnInput,\n        payload: rawInput,\n      });\n      let metricProvider = \"unknown\";\n      return yield* Effect.gen(function* () {\n        const routed = yield* resolveRoutableSession({\n          threadId: input.threadId,\n          operation: \"ProviderService.interruptTurn\",\n          allowRecovery: true,\n        });\n        metricProvider = routed.adapter.provider;\n        yield* Effect.annotateCurrentSpan({\n          \"provider.operation\": \"interrupt-turn\",\n          \"provider.kind\": routed.adapter.provider,\n          \"provider.thread_id\": input.threadId,\n          \"provider.turn_id\": input.turnId,\n        });\n        yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);\n        yield* analytics.record(\"provider.turn.interrupted\", {\n          provider: routed.adapter.provider,\n        });\n      }).pipe(\n        withMetrics({\n          counter: providerTurnsTotal,\n          outcomeAttributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"interrupt\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const respondToRequest: ProviderServiceMethod<\"respondToRequest\"> = Effect.fn(\"respondToRequest\")(\n    function* (rawInput) {\n      const input = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.respondToRequest\",\n        schema: ProviderRespondToRequestInput,\n        payload: rawInput,\n      });\n      let metricProvider = \"unknown\";\n      return yield* Effect.gen(function* () {\n        const routed = yield* resolveRoutableSession({\n          threadId: input.threadId,\n          operation: \"ProviderService.respondToRequest\",\n          allowRecovery: true,\n        });\n        metricProvider = routed.adapter.provider;\n        yield* Effect.annotateCurrentSpan({\n          \"provider.operation\": \"respond-to-request\",\n          \"provider.kind\": routed.adapter.provider,\n          \"provider.thread_id\": input.threadId,\n          \"provider.request_id\": input.requestId,\n        });\n        yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);\n        yield* analytics.record(\"provider.request.responded\", {\n          provider: routed.adapter.provider,\n          decision: input.decision,\n        });\n      }).pipe(\n        withMetrics({\n          counter: providerTurnsTotal,\n          outcomeAttributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"approval-response\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const respondToUserInput: ProviderServiceMethod<\"respondToUserInput\"> = Effect.fn(\n    \"respondToUserInput\",\n  )(function* (rawInput) {\n    const input = yield* decodeInputOrValidationError({\n      operation: \"ProviderService.respondToUserInput\",\n      schema: ProviderRespondToUserInputInput,\n      payload: rawInput,\n    });\n    let metricProvider = \"unknown\";\n    return yield* Effect.gen(function* () {\n      const routed = yield* resolveRoutableSession({\n        threadId: input.threadId,\n        operation: \"ProviderService.respondToUserInput\",\n        allowRecovery: true,\n      });\n      metricProvider = routed.adapter.provider;\n      yield* Effect.annotateCurrentSpan({\n        \"provider.operation\": \"respond-to-user-input\",\n        \"provider.kind\": routed.adapter.provider,\n        \"provider.thread_id\": input.threadId,\n        \"provider.request_id\": input.requestId,\n      });\n      yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);\n    }).pipe(\n      withMetrics({\n        counter: providerTurnsTotal,\n        outcomeAttributes: () =>\n          providerMetricAttributes(metricProvider, {\n            operation: \"user-input-response\",\n          }),\n      }),\n    );\n  });\n\n  const stopSession: ProviderServiceMethod<\"stopSession\"> = Effect.fn(\"stopSession\")(\n    function* (rawInput) {\n      const input = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.stopSession\",\n        schema: ProviderStopSessionInput,\n        payload: rawInput,\n      });\n      let metricProvider = \"unknown\";\n      return yield* Effect.gen(function* () {\n        const routed = yield* resolveRoutableSession({\n          threadId: input.threadId,\n          operation: \"ProviderService.stopSession\",\n          allowRecovery: false,\n        });\n        metricProvider = routed.adapter.provider;\n        yield* Effect.annotateCurrentSpan({\n          \"provider.operation\": \"stop-session\",\n          \"provider.kind\": routed.adapter.provider,\n          \"provider.thread_id\": input.threadId,\n        });\n        if (routed.isActive) {\n          yield* routed.adapter.stopSession(routed.threadId);\n        }\n        yield* directory.upsert({\n          threadId: input.threadId,\n          provider: routed.adapter.provider,\n          providerInstanceId: routed.instanceId,\n          status: \"stopped\",\n          runtimePayload: {\n            activeTurnId: null,\n          },\n        });\n        yield* analytics.record(\"provider.session.stopped\", {\n          provider: routed.adapter.provider,\n        });\n      }).pipe(\n        withMetrics({\n          counter: providerSessionsTotal,\n          outcomeAttributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"stop\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const listSessions: ProviderServiceMethod<\"listSessions\"> = Effect.fn(\"listSessions\")(\n    function* () {\n      const currentAdapters = yield* getAdapterEntries;\n      const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>\n        adapter.listSessions().pipe(\n          Effect.map((sessions) =>\n            sessions.map((session) => ({\n              ...session,\n              providerInstanceId: instanceId,\n            })),\n          ),\n        ),\n      );\n      const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);\n      const persistedBindings = yield* directory.listThreadIds().pipe(\n        Effect.flatMap((threadIds) =>\n          Effect.forEach(\n            threadIds,\n            (threadId) =>\n              directory\n                .getBinding(threadId)\n                .pipe(\n                  Effect.orElseSucceed(() =>\n                    Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),\n                  ),\n                ),\n            { concurrency: \"unbounded\" },\n          ),\n        ),\n        Effect.orElseSucceed(\n          () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,\n        ),\n      );\n      const bindingsByThreadId = new Map<\n        ThreadId,\n        ProviderSessionDirectory.ProviderRuntimeBinding\n      >();\n      for (const bindingOption of persistedBindings) {\n        const binding = Option.getOrUndefined(bindingOption);\n        if (binding) {\n          bindingsByThreadId.set(binding.threadId, binding);\n        }\n      }\n\n      const sessions: ProviderSession[] = [];\n      for (const session of activeSessions) {\n        const binding = bindingsByThreadId.get(session.threadId);\n        if (!binding) {\n          sessions.push(session);\n          continue;\n        }\n\n        const overrides: {\n          resumeCursor?: ProviderSession[\"resumeCursor\"];\n          runtimeMode?: ProviderSession[\"runtimeMode\"];\n          providerInstanceId?: ProviderSession[\"providerInstanceId\"];\n        } = {};\n        overrides.providerInstanceId = dieOnMissingBindingInstanceId(\n          \"ProviderService.listSessions\",\n          binding,\n        );\n        if (binding.provider !== session.provider) {\n          return yield* Effect.die(\n            new Error(\n              `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,\n            ),\n          );\n        }\n        if (overrides.providerInstanceId !== session.providerInstanceId) {\n          return yield* Effect.die(\n            new Error(\n              `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,\n            ),\n          );\n        }\n        if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {\n          overrides.resumeCursor = binding.resumeCursor;\n        }\n        if (binding.runtimeMode !== undefined) {\n          overrides.runtimeMode = binding.runtimeMode;\n        }\n        sessions.push(Object.assign({}, session, overrides));\n      }\n      return sessions;\n    },\n  );\n\n  const getCapabilities: ProviderServiceMethod<\"getCapabilities\"> = (instanceId) =>\n    registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));\n\n  const getInstanceInfo: ProviderServiceMethod<\"getInstanceInfo\"> = (instanceId) =>\n    registry.getInstanceInfo(instanceId);\n\n  const readThread: ProviderServiceMethod<\"readThread\"> = Effect.fn(\"readThread\")(\n    function* (threadId) {\n      const binding = Option.getOrUndefined(yield* directory.getBinding(threadId));\n      if (!binding) {\n        return yield* toValidationError(\n          \"ProviderService.readThread\",\n          `Cannot read thread '${threadId}' because no persisted provider binding exists.`,\n        );\n      }\n      const instanceId = yield* requireBindingInstanceId(\"ProviderService.readThread\", binding);\n      const adapter = yield* registry.getByInstance(instanceId);\n      const cwd = readPersistedCwd(binding.runtimePayload);\n      const modelSelection = readPersistedModelSelection(binding.runtimePayload);\n      const hasResumeCursor = binding.resumeCursor !== null && binding.resumeCursor !== undefined;\n      return yield* adapter.readThread({\n        threadId,\n        provider: binding.provider,\n        providerInstanceId: instanceId,\n        ...(cwd ? { cwd } : {}),\n        ...(modelSelection ? { modelSelection } : {}),\n        ...(hasResumeCursor ? { resumeCursor: binding.resumeCursor } : {}),\n        runtimeMode: binding.runtimeMode ?? \"full-access\",\n      });\n    },\n  );\n\n  const ensureSession: ProviderServiceMethod<\"ensureSession\"> = (threadId) =>\n    resolveRoutableSession({\n      threadId,\n      operation: \"ProviderService.ensureSession\",\n      allowRecovery: true,\n    }).pipe(Effect.asVoid);\n\n  const rollbackConversation: ProviderServiceMethod<\"rollbackConversation\"> = Effect.fn(\n    \"rollbackConversation\",\n  )(function* (rawInput) {\n    const input = yield* decodeInputOrValidationError({\n      operation: \"ProviderService.rollbackConversation\",\n      schema: ProviderRollbackConversationInput,\n      payload: rawInput,\n    });\n    if (input.numTurns === 0) {\n      return;\n    }\n    let metricProvider = \"unknown\";\n    return yield* Effect.gen(function* () {\n      const routed = yield* resolveRoutableSession({\n        threadId: input.threadId,\n        operation: \"ProviderService.rollbackConversation\",\n        allowRecovery: true,\n      });\n      metricProvider = routed.adapter.provider;\n      yield* Effect.annotateCurrentSpan({\n        \"provider.operation\": \"rollback-conversation\",\n        \"provider.kind\": routed.adapter.provider,\n        \"provider.thread_id\": input.threadId,\n        \"provider.rollback_turns\": input.numTurns,\n      });\n      yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);\n      yield* analytics.record(\"provider.conversation.rolled_back\", {\n        provider: routed.adapter.provider,\n        turns: input.numTurns,\n      });\n    }).pipe(\n      withMetrics({\n        counter: providerTurnsTotal,\n        outcomeAttributes: () =>\n          providerMetricAttributes(metricProvider, {\n            operation: \"rollback\",\n          }),\n      }),\n    );\n  });\n\n  const runStopAll = Effect.fn(\"runStopAll\")(function* () {\n    const threadIds = yield* directory.listThreadIds();\n    const currentAdapters = yield* getAdapterEntries;\n    const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>\n      adapter.listSessions().pipe(\n        Effect.map((sessions) =>\n          sessions.map((session) => ({\n            ...session,\n            providerInstanceId: instanceId,\n          })),\n        ),\n      ),\n    ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));\n    yield* Effect.forEach(activeSessions, (session) =>\n      Effect.flatMap(nowIso, (lastRuntimeEventAt) =>\n        upsertSessionBinding(session, session.threadId, {\n          lastRuntimeEvent: \"provider.stopAll\",\n          lastRuntimeEventAt,\n        }),\n      ),\n    ).pipe(Effect.asVoid);\n    yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);\n    const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));\n    yield* Effect.forEach(bindings, (binding) =>\n      Effect.gen(function* () {\n        const providerInstanceId = dieOnMissingBindingInstanceId(\n          \"ProviderService.stopAll\",\n          binding,\n        );\n        return yield* directory.upsert({\n          threadId: binding.threadId,\n          provider: binding.provider,\n          providerInstanceId,\n          status: \"stopped\",\n          runtimePayload: {\n            activeTurnId: null,\n            lastRuntimeEvent: \"provider.stopAll\",\n            lastRuntimeEventAt: yield* nowIso,\n          },\n        });\n      }),\n    ).pipe(Effect.asVoid);\n    yield* analytics.record(\"provider.sessions.stopped_all\", {\n      sessionCount: threadIds.length,\n    });\n    yield* analytics.flush;\n  });\n\n  yield* Effect.addFinalizer(() =>\n    runStopAll().pipe(\n      Effect.catchCause((cause) =>\n        Effect.logWarning(\"failed to stop provider service\", {\n          errorTag: causeErrorTag(cause),\n        }),\n      ),\n    ),\n  );\n\n  return {\n    startSession,\n    sendTurn,\n    interruptTurn,\n    respondToRequest,\n    respondToUserInput,\n    stopSession,\n    listSessions,\n    getCapabilities,\n    getInstanceInfo,\n    readThread,\n    ensureSession,\n    rollbackConversation,\n    // Each access creates a fresh PubSub subscription so that multiple\n    // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each\n    // independently receive all runtime events.\n    get streamEvents(): ProviderServiceMethod<\"streamEvents\"> {\n      return Stream.fromPubSub(runtimeEventPubSub);\n    },\n  } satisfies ProviderService.ProviderService[\"Service\"];\n});\n\nexport const ProviderServiceLive = Layer.effect(\n  ProviderService.ProviderService,\n  makeProviderService(),\n);\n\nexport function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {\n  return Layer.effect(ProviderService.ProviderService, makeProviderService(options));\n}\n","import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schedule from \"effect/Schedule\";\n\nimport { ProjectionSnapshotQuery } from \"../../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport { ProviderSessionDirectory } from \"../Services/ProviderSessionDirectory.ts\";\nimport {\n  ProviderSessionReaper,\n  type ProviderSessionReaperShape,\n} from \"../Services/ProviderSessionReaper.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\nimport { ProviderService } from \"../Services/ProviderService.ts\";\n\nconst DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;\nconst DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;\n\nexport interface ProviderSessionReaperLiveOptions {\n  readonly inactivityThresholdMs?: number;\n  readonly sweepIntervalMs?: number;\n}\n\nconst makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>\n  Effect.gen(function* () {\n    const providerService = yield* ProviderService;\n    const directory = yield* ProviderSessionDirectory;\n    const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n\n    const inactivityThresholdMs = Math.max(\n      1,\n      options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,\n    );\n    const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);\n\n    const sweep = Effect.gen(function* () {\n      const bindings = yield* directory.listBindings();\n      const now = yield* Clock.currentTimeMillis;\n      let reapedCount = 0;\n\n      for (const binding of bindings) {\n        if (binding.status === \"stopped\") {\n          continue;\n        }\n\n        const lastSeenMs = Date.parse(binding.lastSeenAt);\n        if (Number.isNaN(lastSeenMs)) {\n          yield* Effect.logWarning(\"provider.session.reaper.invalid-last-seen\", {\n            threadId: binding.threadId,\n            provider: binding.provider,\n            lastSeenAt: binding.lastSeenAt,\n          });\n          continue;\n        }\n\n        const idleDurationMs = now - lastSeenMs;\n        if (idleDurationMs < inactivityThresholdMs) {\n          continue;\n        }\n\n        const thread = yield* projectionSnapshotQuery\n          .getThreadShellById(binding.threadId)\n          .pipe(Effect.map(Option.getOrUndefined));\n        if (thread?.session?.activeTurnId != null) {\n          yield* Effect.logDebug(\"provider.session.reaper.skipped-active-turn\", {\n            threadId: binding.threadId,\n            activeTurnId: thread.session.activeTurnId,\n            idleDurationMs,\n          });\n          continue;\n        }\n\n        const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(\n          Effect.tap(() =>\n            Effect.logInfo(\"provider.session.reaped\", {\n              threadId: binding.threadId,\n              provider: binding.provider,\n              idleDurationMs,\n              reason: \"inactivity_threshold\",\n            }),\n          ),\n          Effect.as(true),\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"provider.session.reaper.stop-failed\", {\n              threadId: binding.threadId,\n              provider: binding.provider,\n              idleDurationMs,\n              cause,\n            }).pipe(Effect.as(false)),\n          ),\n        );\n\n        if (reaped) {\n          reapedCount += 1;\n        }\n      }\n\n      if (reapedCount > 0) {\n        yield* Effect.logInfo(\"provider.session.reaper.sweep-complete\", {\n          reapedCount,\n          totalBindings: bindings.length,\n        });\n      }\n    });\n\n    const start: ProviderSessionReaperShape[\"start\"] = () =>\n      Effect.gen(function* () {\n        yield* forkParked(\n          sweep.pipe(\n            Effect.catch((error: unknown) =>\n              Effect.logWarning(\"provider.session.reaper.sweep-failed\", {\n                error,\n              }),\n            ),\n            Effect.catchDefect((defect: unknown) =>\n              Effect.logWarning(\"provider.session.reaper.sweep-defect\", {\n                defect,\n              }),\n            ),\n            Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),\n          ),\n        );\n\n        yield* Effect.logInfo(\"provider.session.reaper.started\", {\n          inactivityThresholdMs,\n          sweepIntervalMs,\n        });\n      });\n\n    return {\n      start,\n    } satisfies ProviderSessionReaperShape;\n  });\n\nexport const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>\n  Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));\n\nexport const ProviderSessionReaperLive = makeProviderSessionReaperLive();\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport type { ChatAttachment, ModelSelection, ProviderInstanceId } from \"@t3tools/contracts\";\nimport { TextGenerationError } from \"@t3tools/contracts\";\n\nimport * as ProviderInstanceRegistry from \"../provider/Services/ProviderInstanceRegistry.ts\";\nimport type { ProviderInstance } from \"../provider/ProviderDriver.ts\";\nimport type { TextGenerationPolicy } from \"./TextGenerationPolicy.ts\";\n\nexport type TextGenerationProvider =\n  | \"codex\"\n  | \"claudeAgent\"\n  | \"gemini\"\n  | \"qwen\"\n  | \"kimi\"\n  | \"joycode\";\n\nexport interface CommitMessageGenerationInput {\n  cwd: string;\n  branch: string | null;\n  stagedSummary: string;\n  stagedPatch: string;\n  /** When true, the model also returns a semantic branch name for the change. */\n  includeBranch?: boolean;\n  policy?: TextGenerationPolicy | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface CommitMessageGenerationResult {\n  subject: string;\n  body: string;\n  /** Only present when `includeBranch` was set on the input. */\n  branch?: string | undefined;\n}\n\nexport interface PrContentGenerationInput {\n  cwd: string;\n  baseBranch: string;\n  headBranch: string;\n  commitSummary: string;\n  diffSummary: string;\n  diffPatch: string;\n  changeRequestTemplate?: string | undefined;\n  policy?: TextGenerationPolicy | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface PrContentGenerationResult {\n  title: string;\n  body: string;\n}\n\nexport interface BranchNameGenerationInput {\n  cwd: string;\n  message: string;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface BranchNameGenerationResult {\n  branch: string;\n}\n\nexport interface ThreadTitleGenerationInput {\n  cwd: string;\n  message: string;\n  /** Present when replacing an existing title from the current thread history. */\n  previousTitle?: string | undefined;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface ThreadTitleGenerationResult {\n  title: string;\n}\n\nexport interface TextGenerationService {\n  generateCommitMessage(\n    input: CommitMessageGenerationInput,\n  ): Promise<CommitMessageGenerationResult>;\n  generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;\n  generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;\n  generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;\n}\n\n/**\n * TextGeneration - Service tag for commit and change request text generation.\n */\nexport class TextGeneration extends Context.Service<\n  TextGeneration,\n  {\n    /**\n     * Generate a commit message from staged change context.\n     */\n    readonly generateCommitMessage: (\n      input: CommitMessageGenerationInput,\n    ) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;\n\n    /**\n     * Generate change request title/body from branch and diff context.\n     */\n    readonly generatePrContent: (\n      input: PrContentGenerationInput,\n    ) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;\n\n    /**\n     * Generate a concise branch name from a user message.\n     */\n    readonly generateBranchName: (\n      input: BranchNameGenerationInput,\n    ) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;\n\n    /** Generate a concise thread title from a first message or thread history. */\n    readonly generateThreadTitle: (\n      input: ThreadTitleGenerationInput,\n    ) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;\n  }\n>()(\"t3/textGeneration/TextGeneration\") {}\n\n/** @deprecated Use `TextGeneration[\"Service\"]`. */\nexport type TextGenerationShape = TextGeneration[\"Service\"];\n\ntype TextGenerationOp =\n  | \"generateCommitMessage\"\n  | \"generatePrContent\"\n  | \"generateBranchName\"\n  | \"generateThreadTitle\";\n\nconst resolveInstance = (\n  registry: ProviderInstanceRegistry.ProviderInstanceRegistry[\"Service\"],\n  operation: TextGenerationOp,\n  instanceId: ProviderInstanceId,\n): Effect.Effect<ProviderInstance[\"textGeneration\"], TextGenerationError> =>\n  registry.getInstance(instanceId).pipe(\n    Effect.flatMap((instance) =>\n      instance\n        ? Effect.succeed(instance.textGeneration)\n        : Effect.fail(\n            new TextGenerationError({\n              operation,\n              detail: `No provider instance registered for id '${instanceId}'.`,\n            }),\n          ),\n    ),\n  );\n\nexport const makeTextGenerationFromRegistry = (\n  registry: ProviderInstanceRegistry.ProviderInstanceRegistry[\"Service\"],\n): TextGeneration[\"Service\"] =>\n  TextGeneration.of({\n    generateCommitMessage: (input) =>\n      resolveInstance(registry, \"generateCommitMessage\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),\n      ),\n    generatePrContent: (input) =>\n      resolveInstance(registry, \"generatePrContent\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),\n      ),\n    generateBranchName: (input) =>\n      resolveInstance(registry, \"generateBranchName\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),\n      ),\n    generateThreadTitle: (input) =>\n      resolveInstance(registry, \"generateThreadTitle\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),\n      ),\n  });\n\nexport const make = Effect.gen(function* () {\n  const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;\n  return makeTextGenerationFromRegistry(registry);\n});\n\nexport const layer = Layer.effect(TextGeneration, make);\n","import { TextGenerationError } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nconst isTextGenerationError = Schema.is(TextGenerationError);\n\n/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */\nexport function toJsonSchemaObject(schema: Schema.Top): unknown {\n  const document = Schema.toJsonSchemaDocument(schema);\n  if (document.definitions && Object.keys(document.definitions).length > 0) {\n    return { ...document.schema, $defs: document.definitions };\n  }\n  return document.schema;\n}\n\n/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */\nexport function limitSection(value: string, maxChars: number): string {\n  if (value.length <= maxChars) return value;\n  const truncated = value.slice(0, maxChars);\n  return `${truncated}\\n\\n[truncated]`;\n}\n\n/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */\nexport function sanitizeCommitSubject(raw: string): string {\n  const singleLine = raw.trim().split(/\\r?\\n/g)[0]?.trim() ?? \"\";\n  const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, \"\").trim();\n  if (withoutTrailingPeriod.length === 0) {\n    return \"Update project files\";\n  }\n\n  if (withoutTrailingPeriod.length <= 72) {\n    return withoutTrailingPeriod;\n  }\n  return withoutTrailingPeriod.slice(0, 72).trimEnd();\n}\n\n/** Normalise a raw PR title to a single line with a sensible fallback. */\nexport function sanitizePrTitle(raw: string): string {\n  const singleLine = raw.trim().split(/\\r?\\n/g)[0]?.trim() ?? \"\";\n  if (singleLine.length > 0) {\n    return singleLine;\n  }\n  return \"Update project changes\";\n}\n\n/** Normalise a raw thread title to a compact single-line sidebar-safe label. */\nexport function sanitizeThreadTitle(raw: string): string {\n  const normalized = raw\n    .trim()\n    .split(/\\r?\\n/g)[0]\n    ?.trim()\n    .replace(/^['\"`]+|['\"`]+$/g, \"\")\n    .trim()\n    .replace(/\\s+/g, \" \");\n\n  if (!normalized || normalized.trim().length === 0) {\n    return \"New thread\";\n  }\n\n  if (normalized.length <= 50) {\n    return normalized;\n  }\n\n  return `${normalized.slice(0, 47).trimEnd()}...`;\n}\n\n/** CLI name to human-readable label, e.g. \"codex\" → \"Codex CLI (`codex`)\" */\nfunction cliLabel(cliName: string): string {\n  const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);\n  return `${capitalized} CLI (\\`${cliName}\\`)`;\n}\n\n/**\n * Normalize an unknown error from a CLI text generation process into a\n * typed `TextGenerationError`. Parameterized by CLI name so both Codex\n * and Claude (and future providers) can share the same logic.\n */\nexport function normalizeCliError(\n  cliName: string,\n  operation: string,\n  error: unknown,\n  fallback: string,\n): TextGenerationError {\n  if (isTextGenerationError(error)) {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    const lower = error.message.toLowerCase();\n    if (\n      error.message.includes(`Command not found: ${cliName}`) ||\n      lower.includes(`spawn ${cliName}`) ||\n      lower.includes(\"enoent\")\n    ) {\n      return new TextGenerationError({\n        operation,\n        detail: `${cliLabel(cliName)} is required but not available on PATH.`,\n        cause: error,\n      });\n    }\n    return new TextGenerationError({\n      operation,\n      detail: fallback,\n      cause: error,\n    });\n  }\n\n  return new TextGenerationError({\n    operation,\n    detail: fallback,\n    cause: error,\n  });\n}\n","/**\n * Shared prompt builders for text generation providers.\n *\n * Extracts the prompt construction logic that is identical across\n * Codex, Claude, and any future CLI-based text generation backends.\n *\n * @module textGenerationPrompts\n */\nimport * as Schema from \"effect/Schema\";\nimport type { ChatAttachment } from \"@t3tools/contracts\";\n\nimport { limitSection } from \"./TextGenerationUtils.ts\";\nimport type { TextGenerationPolicy } from \"./TextGenerationPolicy.ts\";\n\nconst EARLIER_CONTENT_TRUNCATION_MARKER = \"[Earlier content truncated]\\n\\n\";\n\nfunction policyInstruction(instruction: string | undefined): ReadonlyArray<string> {\n  const trimmed = instruction?.trim();\n  return trimmed ? [\"\", \"Additional instructions:\", limitSection(trimmed, 4_000)] : [];\n}\n\n// ---------------------------------------------------------------------------\n// Commit message\n// ---------------------------------------------------------------------------\n\nexport interface CommitMessagePromptInput {\n  branch: string | null;\n  stagedSummary: string;\n  stagedPatch: string;\n  includeBranch?: boolean;\n  policy?: TextGenerationPolicy | undefined;\n}\n\nexport function buildCommitMessagePrompt(input: CommitMessagePromptInput) {\n  const wantsBranch = input.includeBranch === true;\n\n  const prompt = [\n    \"You write concise git commit messages.\",\n    wantsBranch\n      ? \"Return a JSON object with keys: subject, body, branch.\"\n      : \"Return a JSON object with keys: subject, body.\",\n    \"Rules:\",\n    \"- subject must be imperative, <= 72 chars, and no trailing period\",\n    \"- body can be empty string or short bullet points\",\n    ...(wantsBranch\n      ? [\"- branch must be a short semantic git branch fragment for this change\"]\n      : []),\n    \"- capture the primary user-visible or developer-visible change\",\n    ...policyInstruction(input.policy?.commitInstructions),\n    \"\",\n    `Branch: ${input.branch ?? \"(detached)\"}`,\n    \"\",\n    \"Staged files:\",\n    limitSection(input.stagedSummary, 6_000),\n    \"\",\n    \"Staged patch:\",\n    limitSection(input.stagedPatch, 40_000),\n  ].join(\"\\n\");\n\n  if (wantsBranch) {\n    return {\n      prompt,\n      outputSchema: Schema.Struct({\n        subject: Schema.String,\n        body: Schema.String,\n        branch: Schema.String,\n      }),\n    };\n  }\n\n  return {\n    prompt,\n    outputSchema: Schema.Struct({\n      subject: Schema.String,\n      body: Schema.String,\n    }),\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Change request content\n// ---------------------------------------------------------------------------\n\nexport interface PrContentPromptInput {\n  baseBranch: string;\n  headBranch: string;\n  commitSummary: string;\n  diffSummary: string;\n  diffPatch: string;\n  changeRequestTemplate?: string | undefined;\n  policy?: TextGenerationPolicy | undefined;\n}\n\nexport function buildPrContentPrompt(input: PrContentPromptInput) {\n  const changeRequestTemplate = input.changeRequestTemplate?.trim();\n  const bodyRules = changeRequestTemplate\n    ? [\n        \"- body must be markdown and follow the repository change request template structure\",\n        \"- fill in the template sections appropriately for this change\",\n        \"- drop HTML comments from the template in the generated body\",\n        \"- keep the template's markdown structure\",\n      ]\n    : [\n        \"- body must be markdown and include headings '## Summary' and '## Testing'\",\n        \"- under Summary, provide short bullet points\",\n        \"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate\",\n      ];\n  const prompt = [\n    \"You write source control change request content.\",\n    \"Return a JSON object with keys: title, body.\",\n    \"Rules:\",\n    \"- title should be concise and specific\",\n    ...bodyRules,\n    ...policyInstruction(input.policy?.changeRequestInstructions),\n    ...(changeRequestTemplate\n      ? [\"\", \"Repository change request template:\", limitSection(changeRequestTemplate, 8_000)]\n      : []),\n    \"\",\n    `Base branch: ${input.baseBranch}`,\n    `Head branch: ${input.headBranch}`,\n    \"\",\n    \"Commits:\",\n    limitSection(input.commitSummary, 12_000),\n    \"\",\n    \"Diff stat:\",\n    limitSection(input.diffSummary, 12_000),\n    \"\",\n    \"Diff patch:\",\n    limitSection(input.diffPatch, 40_000),\n  ].join(\"\\n\");\n\n  const outputSchema = Schema.Struct({\n    title: Schema.String,\n    body: Schema.String,\n  });\n\n  return { prompt, outputSchema };\n}\n\n// ---------------------------------------------------------------------------\n// Branch name\n// ---------------------------------------------------------------------------\n\nexport interface BranchNamePromptInput {\n  message: string;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  policy?: TextGenerationPolicy | undefined;\n}\n\ninterface PromptFromMessageInput {\n  instruction: string;\n  responseShape: string;\n  rules: ReadonlyArray<string>;\n  message: string;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  additionalInstructions?: string | undefined;\n}\n\nfunction buildPromptFromMessage(input: PromptFromMessageInput): string {\n  const attachmentLines = (input.attachments ?? []).map(\n    (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,\n  );\n\n  const promptSections = [\n    input.instruction,\n    input.responseShape,\n    \"Rules:\",\n    ...input.rules.map((rule) => `- ${rule}`),\n    \"\",\n    \"User message:\",\n    limitSection(input.message, 8_000),\n    ...policyInstruction(input.additionalInstructions),\n  ];\n  if (attachmentLines.length > 0) {\n    promptSections.push(\n      \"\",\n      \"Attachment metadata:\",\n      limitSection(attachmentLines.join(\"\\n\"), 4_000),\n    );\n  }\n\n  return promptSections.join(\"\\n\");\n}\n\nexport function buildBranchNamePrompt(input: BranchNamePromptInput) {\n  const prompt = buildPromptFromMessage({\n    instruction: \"You generate concise git branch names.\",\n    responseShape: \"Return a JSON object with key: branch.\",\n    rules: [\n      \"Branch should describe the requested work from the user message.\",\n      \"Keep it short and specific (2-6 words).\",\n      \"Use plain words only, no issue prefixes and no punctuation-heavy text.\",\n      \"If images are attached, use them as primary context for visual/UI issues.\",\n    ],\n    message: input.message,\n    attachments: input.attachments,\n    additionalInstructions: input.policy?.branchInstructions,\n  });\n  const outputSchema = Schema.Struct({\n    branch: Schema.String,\n  });\n\n  return { prompt, outputSchema };\n}\n\n// ---------------------------------------------------------------------------\n// Thread title\n// ---------------------------------------------------------------------------\n\nexport interface ThreadTitlePromptInput {\n  message: string;\n  previousTitle?: string | undefined;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  policy?: TextGenerationPolicy | undefined;\n}\n\n// Keep shared editorial rules in these two prompts in sync. Regeneration\n// intentionally adds guidance for thread history and the previous title.\nconst INITIAL_THREAD_TITLE_PROMPT = `Generate a title that will help the user recognize this T3 Code thread weeks later.\nReturn JSON with exactly one key: title.\n\nBefore answering, silently reduce the request to:\n- Subject: What system, feature, or problem is this really about?\n- Outcome: What does the user ultimately want to understand or change?\n- Incidental instructions: What only describes how the agent should do the work?\n\nTitle the subject and outcome. Discard incidental instructions.\n\nEditorial rules:\n- 3-8 words, fewer than 40 characters.\n- Use a compact noun phrase or clear action phrase.\n- Capture the umbrella goal when the request lists several symptoms or steps.\n- Name the product change, not the mock, plan, report, branch, or PR used to produce it.\n- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.\n- For reviews, name what is being reviewed and the relevant concern. Avoid generic titles such as \"Review PR 123\" when linked or attached context reveals the subject.\n- For research, name the question domain rather than the requested research process.\n- Do not claim the work is complete.\n- Do not copy and truncate the user's message.\n- Avoid project names already visible in the UI, quotes, labels, filler, and trailing punctuation.\n- Use attached images as primary context for UI issues.\n- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.`;\n\nfunction regenerateThreadTitlePrompt(previousTitle: string): string {\n  return `Regenerate the title for an existing T3 Code thread so the user can recognize it weeks later.\nThe previous title was ${JSON.stringify(previousTitle)}.\nReturn JSON with exactly one key: title.\n\nDetermine the title in this order:\n1. Read the USER messages first. Identify the latest explicit durable goal. The original subject remains the subject until the user clearly changes what the thread is about.\n2. Use ASSISTANT messages to resolve vague links, unnamed code, and discovered product nouns. Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.\n3. Compare that subject with the previous title. Preserve accurate scope words, especially when earlier content is truncated. Replace the previous title when it is generic, artifact-based, a completion update, or contradicted by the thread.\n4. Title the durable subject and desired outcome, not the current workflow state.\n\nEditorial rules:\n- 3-8 words, fewer than 40 characters.\n- Use a compact noun phrase or clear action phrase.\n- Preserve the umbrella subject when later messages focus on one finding, provider, platform, or implementation detail.\n- A thread progressing through research, planning, implementation, review, CI, merge, and monitoring has usually not changed subjects.\n- Ignore deliverables and operations such as mocks, plans, HTML, branches, PRs, tests, CI, commits, merging, and monitoring unless they are the actual topic.\n- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.\n- Treat final operational follow-ups and assistant completion summaries as weak evidence of subject.\n- For reviews, name the reviewed feature or system and its durable concern, not one finding from the review.\n- For research, name the question domain rather than the research process.\n- Do not claim the work is complete.\n- Do not copy and truncate a thread message.\n- Avoid project names already visible in the UI, PR numbers, quotes, labels, filler, and trailing punctuation.\n- Use attached images as primary context for UI issues.\n- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.\n- Return a meaningfully improved title, not a cosmetic paraphrase of the previous title.\n\nExamples of the distinction:\n- A subagent-monitoring review that finds a Codex roster bug remains \"Review Subagent Monitoring Risks,\" not \"Codex Roster Bug Review.\"\n- A vague failing-test request later identified as a lazy thread-feed mismatch becomes \"Fix Lazy Thread Feed Test,\" not \"Prevent Mobile Feed Regressions.\"\n- A QR-sharing overhaul that ends with CI and merge work remains about QR sharing, not the PR lifecycle.`;\n}\n\nfunction preserveMessageEnd(message: string): string {\n  const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);\n  const contents = alreadyTruncated\n    ? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)\n    : message;\n  if (!alreadyTruncated && contents.length <= 8_000) {\n    return contents;\n  }\n  return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;\n}\n\nfunction threadTitlePromptSuffix(input: ThreadTitlePromptInput): string {\n  const additionalInstructions = policyInstruction(input.policy?.threadTitleInstructions);\n  const attachmentLines = (input.attachments ?? []).map(\n    (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,\n  );\n\n  let suffix = \"\";\n  if (additionalInstructions.length > 0) {\n    suffix = `\\n${additionalInstructions.join(\"\\n\")}`;\n  }\n  if (attachmentLines.length > 0) {\n    suffix += `\\n\\nAttachment metadata:\\n${limitSection(attachmentLines.join(\"\\n\"), 4_000)}`;\n  }\n  return suffix;\n}\n\nexport function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {\n  let prompt: string;\n  if (input.previousTitle === undefined) {\n    const message = limitSection(input.message, 8_000);\n    prompt = `${INITIAL_THREAD_TITLE_PROMPT}\\n\\nUser message:\\n${message}${threadTitlePromptSuffix(input)}`;\n  } else {\n    const message = preserveMessageEnd(input.message);\n    prompt = `${regenerateThreadTitlePrompt(input.previousTitle)}\\n\\nThread contents:\\n${message}${threadTitlePromptSuffix(input)}`;\n  }\n  const outputSchema = Schema.Struct({\n    title: Schema.String,\n  });\n\n  return { prompt, outputSchema };\n}\n","import type {\n  ProviderDriverKind,\n  ModelCapabilities,\n  ServerProvider,\n  ServerProviderAuth,\n  ServerProviderSkill,\n  ServerProviderSlashCommand,\n  ServerProviderModel,\n  ServerProviderState,\n  ServerProviderUsageLimits,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { normalizeCustomModelSlug } from \"@t3tools/shared/model\";\nimport { isWindowsCommandNotFound } from \"../processRunner.ts\";\nimport { createProviderVersionAdvisory } from \"./providerMaintenance.ts\";\nimport { collectUint8StreamText } from \"../stream/collectUint8StreamText.ts\";\n\nexport const DEFAULT_TIMEOUT_MS = 4_000;\n// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)\nexport const AUTH_PROBE_TIMEOUT_MS = 10_000;\n\nexport interface CommandResult {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly code: number;\n}\n\nexport class ProviderCommandNotFoundError extends Schema.TaggedErrorClass<ProviderCommandNotFoundError>()(\n  \"ProviderCommandNotFoundError\",\n  {\n    binaryPath: Schema.String,\n    exitCode: Schema.Number,\n    stdoutLength: Schema.Number,\n    stderrLength: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;\n  }\n}\n\nconst isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);\n\nexport interface ProviderProbeResult {\n  readonly installed: boolean;\n  readonly version: string | null;\n  readonly status: Exclude<ServerProviderState, \"disabled\">;\n  readonly auth: ServerProviderAuth;\n  readonly message?: string;\n  readonly usageLimits?: ServerProviderUsageLimits;\n}\n\nexport interface ServerProviderPresentation {\n  readonly displayName: string;\n  readonly badgeLabel?: string;\n  readonly showInteractionModeToggle?: boolean;\n  readonly requiresNewThreadForModelChange?: boolean;\n}\n\nexport type ServerProviderDraft = Omit<ServerProvider, \"instanceId\" | \"driver\">;\n\nexport function nonEmptyTrimmed(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isCommandMissingCause(error: unknown): boolean {\n  if (isProviderCommandNotFoundError(error)) return true;\n  return error instanceof PlatformError.PlatformError && error.reason._tag === \"NotFound\";\n}\n\nexport const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const child = yield* spawner.spawn(command);\n    const [stdout, stderr, exitCode] = yield* Effect.all(\n      [\n        collectStreamAsString(child.stdout),\n        collectStreamAsString(child.stderr),\n        child.exitCode.pipe(Effect.map(Number)),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n\n    const result: CommandResult = { stdout, stderr, code: exitCode };\n    if (yield* isWindowsCommandNotFound(exitCode, stderr)) {\n      return yield* new ProviderCommandNotFoundError({\n        binaryPath,\n        exitCode,\n        stdoutLength: stdout.length,\n        stderrLength: stderr.length,\n      });\n    }\n    return result;\n  }).pipe(Effect.scoped);\n\nexport function detailFromResult(\n  result: CommandResult & { readonly timedOut?: boolean },\n): string | undefined {\n  if (result.timedOut) return \"Timed out while running command.\";\n  const stderr = nonEmptyTrimmed(result.stderr);\n  if (stderr) return stderr;\n  const stdout = nonEmptyTrimmed(result.stdout);\n  if (stdout) return stdout;\n  if (result.code !== 0) {\n    return `Command exited with code ${result.code}.`;\n  }\n  return undefined;\n}\n\nexport function extractAuthBoolean(value: unknown): boolean | undefined {\n  if (globalThis.Array.isArray(value)) {\n    for (const entry of value) {\n      const nested = extractAuthBoolean(entry);\n      if (nested !== undefined) return nested;\n    }\n    return undefined;\n  }\n\n  if (!value || typeof value !== \"object\") return undefined;\n\n  const record = value as Record<string, unknown>;\n  for (const key of [\"authenticated\", \"isAuthenticated\", \"loggedIn\", \"isLoggedIn\"] as const) {\n    if (typeof record[key] === \"boolean\") return record[key];\n  }\n  for (const key of [\"auth\", \"status\", \"session\", \"account\"] as const) {\n    const nested = extractAuthBoolean(record[key]);\n    if (nested !== undefined) return nested;\n  }\n  return undefined;\n}\n\nexport function parseGenericCliVersion(output: string): string | null {\n  const match = output.match(/\\b(\\d+\\.\\d+\\.\\d+)\\b/);\n  return match?.[1] ?? null;\n}\n\nexport function providerModelsFromSettings(\n  builtInModels: ReadonlyArray<ServerProviderModel>,\n  customModels: ReadonlyArray<string>,\n  customModelCapabilities: ModelCapabilities,\n): ReadonlyArray<ServerProviderModel> {\n  const resolvedBuiltInModels = [...builtInModels];\n  const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));\n  const customEntries: ServerProviderModel[] = [];\n\n  for (const candidate of customModels) {\n    const normalized = normalizeCustomModelSlug(candidate);\n    if (!normalized || seen.has(normalized)) {\n      continue;\n    }\n    seen.add(normalized);\n    customEntries.push({\n      slug: normalized,\n      name: normalized,\n      isCustom: true,\n      capabilities: customModelCapabilities,\n    });\n  }\n\n  return [...resolvedBuiltInModels, ...customEntries];\n}\n\nexport function buildSelectOptionDescriptor(input: {\n  readonly id: string;\n  readonly label: string;\n  readonly options:\n    | ReadonlyArray<{ value: string; label: string; isDefault?: boolean | undefined }>\n    | undefined;\n  readonly description?: string;\n  readonly promptInjectedValues?: ReadonlyArray<string>;\n}) {\n  const options = (input.options ?? []).map((option) =>\n    option.isDefault\n      ? { id: option.value, label: option.label, isDefault: true }\n      : { id: option.value, label: option.label },\n  );\n  const currentValue = options.find((option) => option.isDefault)?.id;\n  return {\n    id: input.id,\n    label: input.label,\n    type: \"select\" as const,\n    options,\n    ...(currentValue ? { currentValue } : {}),\n    ...(input.description ? { description: input.description } : {}),\n    ...(input.promptInjectedValues && input.promptInjectedValues.length > 0\n      ? { promptInjectedValues: [...input.promptInjectedValues] }\n      : {}),\n  };\n}\n\nexport function buildBooleanOptionDescriptor(input: {\n  readonly id: string;\n  readonly label: string;\n  readonly currentValue?: boolean;\n  readonly description?: string;\n}) {\n  return {\n    id: input.id,\n    label: input.label,\n    type: \"boolean\" as const,\n    ...(input.description ? { description: input.description } : {}),\n    ...(typeof input.currentValue === \"boolean\" ? { currentValue: input.currentValue } : {}),\n  };\n}\n\nexport function buildServerProvider(input: {\n  driver?: ProviderDriverKind;\n  presentation: ServerProviderPresentation;\n  enabled: boolean;\n  checkedAt: string;\n  models: ReadonlyArray<ServerProviderModel>;\n  slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;\n  skills?: ReadonlyArray<ServerProviderSkill>;\n  probe: ProviderProbeResult;\n}): ServerProviderDraft {\n  const versionAdvisory = input.driver\n    ? createProviderVersionAdvisory({\n        driver: input.driver,\n        currentVersion: input.probe.version,\n        checkedAt: input.checkedAt,\n      })\n    : undefined;\n  return {\n    displayName: input.presentation.displayName,\n    ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),\n    ...(typeof input.presentation.showInteractionModeToggle === \"boolean\"\n      ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }\n      : {}),\n    ...(typeof input.presentation.requiresNewThreadForModelChange === \"boolean\"\n      ? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }\n      : {}),\n    enabled: input.enabled,\n    installed: input.probe.installed,\n    version: input.probe.version,\n    status: input.enabled ? input.probe.status : \"disabled\",\n    auth: input.probe.auth,\n    checkedAt: input.checkedAt,\n    ...(input.probe.message ? { message: input.probe.message } : {}),\n    models: input.models,\n    slashCommands: [...(input.slashCommands ?? [])],\n    skills: [...(input.skills ?? [])],\n    ...(input.probe.usageLimits ? { usageLimits: input.probe.usageLimits } : {}),\n    ...(versionAdvisory ? { versionAdvisory } : {}),\n  };\n}\n\nexport const collectStreamAsString = <E>(\n  stream: Stream.Stream<Uint8Array, E>,\n): Effect.Effect<string, E> =>\n  collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\n\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { SpawnExecutableResolution } from \"@t3tools/shared/shell\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\n\n/**\n * Windows launcher-script extensions that Node cannot spawn without a shell\n * (`spawn EINVAL` since Node 20.12) and that the Claude Agent SDK therefore\n * cannot use as `pathToClaudeCodeExecutable`.\n */\nconst WINDOWS_SHIM_EXTENSIONS: ReadonlySet<string> = new Set([\".cmd\", \".bat\", \".ps1\"]);\n\n/**\n * Entry points of the npm `@anthropic-ai/claude-code` package relative to the\n * global `node_modules` directory that sits next to the npm launcher shim.\n * Newer package versions ship a native `bin/claude.exe`; older versions only\n * ship `cli.js`, which the SDK runs with a JavaScript runtime.\n */\nconst NPM_PACKAGE_ENTRY_CANDIDATES = [\n  [\"node_modules\", \"@anthropic-ai\", \"claude-code\", \"bin\", \"claude.exe\"],\n  [\"node_modules\", \"@anthropic-ai\", \"claude-code\", \"cli.js\"],\n] as const;\n\nexport type ExecutableFileCheck = (filePath: string) => boolean;\n\nfunction isExistingFile(filePath: string): boolean {\n  try {\n    return NodeFS.statSync(filePath).isFile();\n  } catch {\n    return false;\n  }\n}\n\n/** Injectable file-existence check so tests can run against a fake filesystem. */\nexport const ClaudeExecutableFileCheck = Context.Reference<ExecutableFileCheck>(\n  \"server/provider/Drivers/ClaudeExecutableFileCheck\",\n  {\n    defaultValue: () => isExistingFile,\n  },\n);\n\n/**\n * Resolves the configured Claude binary path into a value the Claude Agent\n * SDK can spawn directly via `pathToClaudeCodeExecutable`.\n *\n * The SDK spawns the given path without a shell and without Windows PATH /\n * PATHEXT resolution, so a bare command name like `claude` fails with\n * \"native binary not found\" and an npm `claude.cmd` shim fails with\n * `spawn EINVAL`. CLI probes avoid this via `resolveSpawnCommand`, which can\n * fall back to `shell: true`; the SDK offers no such escape hatch.\n *\n * On Windows this resolves the command against PATH/PATHEXT and, when the\n * result is an npm launcher shim, follows it to the real package entry\n * (`bin/claude.exe`, or `cli.js` for older package versions). On other\n * platforms the configured value is returned unchanged.\n */\nexport const resolveClaudeSdkExecutablePath = Effect.fn(\"resolveClaudeSdkExecutablePath\")(\n  function* (binaryPath: string, environment: NodeJS.ProcessEnv): Effect.fn.Return<string> {\n    const platform = yield* HostProcessPlatform;\n    if (platform !== \"win32\") {\n      return binaryPath;\n    }\n\n    const resolveExecutable = yield* SpawnExecutableResolution;\n    const isFile = yield* ClaudeExecutableFileCheck;\n    const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath;\n    const extension = NodePath.win32.extname(resolved).toLowerCase();\n    if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) {\n      return resolved;\n    }\n\n    const shimDirectory = NodePath.win32.dirname(resolved);\n    for (const entrySegments of NPM_PACKAGE_ENTRY_CANDIDATES) {\n      const candidate = NodePath.win32.join(shimDirectory, ...entrySegments);\n      if (isFile(candidate)) {\n        return candidate;\n      }\n    }\n\n    yield* Effect.logWarning(\n      \"Claude launcher shim resolved but no known package entry was found next to it; the Claude Agent SDK cannot spawn launcher scripts directly.\",\n      { binaryPath, resolvedShimPath: resolved },\n    );\n    return binaryPath;\n  },\n);\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\n\n/**\n * Expand a leading `~` (or `~/…`, `~\\…`) in a user-supplied path to the\n * current user's home directory. Spawned processes don't get shell\n * expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed\n * verbatim and treated as relative paths by the receiver.\n *\n * Matches the behavior of the other `expandHomePath` helpers in the\n * workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\\`\n * separators are handled. Returns the input unchanged if it doesn't\n * start with `~` or is empty. Does not handle `~user` (other-user)\n * expansion.\n */\nexport function expandHomePath(value: string): string {\n  if (!value) return value;\n  if (value === \"~\") return NodeOS.homedir();\n  if (value.startsWith(\"~/\") || value.startsWith(\"~\\\\\")) {\n    return NodePath.join(NodeOS.homedir(), value.slice(2));\n  }\n  return value;\n}\n","import * as NodeOS from \"node:os\";\n\nimport type { ClaudeSettings } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Path from \"effect/Path\";\n\nimport { expandHomePath } from \"../../pathExpansion.ts\";\n\nexport const resolveClaudeHomePath = Effect.fn(\"resolveClaudeHomePath\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n): Effect.fn.Return<string, never, Path.Path> {\n  const path = yield* Path.Path;\n  const homePath = config.homePath.trim();\n  return path.resolve(homePath.length > 0 ? expandHomePath(homePath) : NodeOS.homedir());\n});\n\nexport const makeClaudeEnvironment = Effect.fn(\"makeClaudeEnvironment\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n  baseEnv?: NodeJS.ProcessEnv,\n): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {\n  const resolvedBaseEnv = baseEnv ?? process.env;\n  const homePath = config.homePath.trim();\n  if (homePath.length === 0) return resolvedBaseEnv;\n  const resolvedHomePath = yield* resolveClaudeHomePath(config);\n  return {\n    ...resolvedBaseEnv,\n    // Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME.\n    // Overriding HOME also relocates the macOS login keychain lookup\n    // ($HOME/Library/Keychains), so the spawned CLI can't find its stored\n    // OAuth credentials and reports \"Not logged in\". CLAUDE_CONFIG_DIR points\n    // Claude Code at its config dir directly while leaving HOME (and the\n    // keychain) intact.\n    CLAUDE_CONFIG_DIR: resolvedHomePath,\n  };\n});\n\nexport const makeClaudeContinuationGroupKey = Effect.fn(\"makeClaudeContinuationGroupKey\")(\n  function* (config: Pick<ClaudeSettings, \"homePath\">): Effect.fn.Return<string, never, Path.Path> {\n    const resolvedHomePath = yield* resolveClaudeHomePath(config);\n    return `claude:home:${resolvedHomePath}`;\n  },\n);\n\nexport const makeClaudeCapabilitiesCacheKey = Effect.fn(\"makeClaudeCapabilitiesCacheKey\")(\n  function* (\n    config: Pick<ClaudeSettings, \"binaryPath\" | \"homePath\">,\n    cwd?: string,\n  ): Effect.fn.Return<string, never, Path.Path> {\n    const resolvedHomePath = yield* resolveClaudeHomePath(config);\n    return `${config.binaryPath}\\0${resolvedHomePath}\\0${cwd ?? \"\"}`;\n  },\n);\n","/**\n * ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.\n *\n * Claude Code loads skills from `<config dir>/skills` (user scope) and\n * `<cwd>/.claude/skills` (project scope), one directory per skill with a\n * `SKILL.md` carrying YAML frontmatter. The Agent SDK init handshake surfaces\n * skills only as slash commands without their filesystem paths, so the\n * provider snapshot scans the same locations directly, mirroring how the\n * Codex app-server reports its skills.\n *\n * @module provider/Drivers/ClaudeSkills\n */\nimport * as NodeOS from \"node:os\";\n\nimport type { ClaudeSettings, ServerProviderSkill } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { parse as parseYamlDocument } from \"yaml\";\n\nimport { expandHomePath } from \"../../pathExpansion.ts\";\n\ntype ClaudeSkillScope = \"user\" | \"project\";\n\nconst FRONTMATTER_PATTERN = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/;\n\ntype SkillFrontmatter =\n  | { readonly kind: \"missing\" }\n  | { readonly kind: \"malformed\" }\n  | { readonly kind: \"parsed\"; readonly name?: string; readonly description?: string };\n\nfunction parseSkillFrontmatter(contents: string): SkillFrontmatter {\n  const match = FRONTMATTER_PATTERN.exec(contents);\n  if (!match) {\n    return { kind: \"missing\" };\n  }\n\n  let parsed: unknown;\n  try {\n    parsed = parseYamlDocument(match[1] ?? \"\");\n  } catch {\n    return { kind: \"malformed\" };\n  }\n  if (typeof parsed !== \"object\" || parsed === null) {\n    return { kind: \"malformed\" };\n  }\n\n  const record = parsed as Record<string, unknown>;\n  const name = typeof record.name === \"string\" ? record.name.trim() : \"\";\n  const description = typeof record.description === \"string\" ? record.description.trim() : \"\";\n  return {\n    kind: \"parsed\",\n    ...(name ? { name } : {}),\n    ...(description ? { description } : {}),\n  };\n}\n\n/**\n * Resolve the Claude config directory the CLI would use, matching the\n * precedence the spawned CLI sees: the instance's `homePath` (exported as\n * `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`\n * already present in the process environment, then `~/.claude`.\n */\nconst resolveClaudeConfigDirPath = Effect.fn(\"resolveClaudeConfigDirPath\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n  environment: NodeJS.ProcessEnv,\n  cwd?: string,\n): Effect.fn.Return<string, never, Path.Path> {\n  const path = yield* Path.Path;\n  const homePath = config.homePath.trim();\n  if (homePath.length > 0) {\n    return path.resolve(expandHomePath(homePath));\n  }\n  // No tilde expansion here: the spawned CLI receives this env var verbatim\n  // (env vars are never shell-expanded), so a literal `~` must stay literal\n  // for discovery to scan the same directory the runtime would. A relative\n  // value is resolved against the workspace cwd — the subprocess's own cwd —\n  // for the same reason.\n  const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? \"\";\n  if (environmentConfigDir.length > 0) {\n    return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);\n  }\n  return path.join(NodeOS.homedir(), \".claude\");\n});\n\n/**\n * Enumerate Claude Code skills from the user config dir and the workspace.\n * Discovery is best-effort: unreadable roots and malformed skill entries are\n * skipped so a broken skill never degrades the provider snapshot. On name\n * collisions the project-scoped skill wins, matching Claude Code's\n * most-specific-wins resolution.\n */\nexport const discoverClaudeSkills = Effect.fn(\"discoverClaudeSkills\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n  cwd?: string,\n  environment?: NodeJS.ProcessEnv,\n): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);\n\n  const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [\n    { directory: path.join(configDirPath, \"skills\"), scope: \"user\" },\n    ...(cwd ? [{ directory: path.join(cwd, \".claude\", \"skills\"), scope: \"project\" as const }] : []),\n  ];\n\n  const skillsByName = new Map<string, ServerProviderSkill>();\n  for (const root of roots) {\n    const entries = yield* fileSystem\n      .readDirectory(root.directory)\n      .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));\n\n    for (const entry of [...entries].sort()) {\n      const skillPath = path.join(root.directory, entry, \"SKILL.md\");\n      const contents = yield* fileSystem\n        .readFileString(skillPath)\n        .pipe(Effect.orElseSucceed(() => undefined));\n      if (contents === undefined) {\n        continue;\n      }\n\n      const frontmatter = parseSkillFrontmatter(contents);\n      // Malformed frontmatter means the skill won't load in Claude Code\n      // either — skip it rather than surfacing a broken entry under its\n      // directory name.\n      if (frontmatter.kind === \"malformed\") {\n        continue;\n      }\n\n      const name = (frontmatter.kind === \"parsed\" ? frontmatter.name : undefined) ?? entry.trim();\n      if (!name) {\n        continue;\n      }\n\n      skillsByName.set(name, {\n        name,\n        path: skillPath,\n        enabled: true,\n        scope: root.scope,\n        ...(frontmatter.kind === \"parsed\" && frontmatter.description\n          ? { description: frontmatter.description }\n          : {}),\n      });\n    }\n  }\n\n  return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));\n});\n","import type { ServerProviderUsageLimits, ServerProviderUsageWindow } from \"@t3tools/contracts\";\nimport type { SDKControlGetUsageResponse } from \"@anthropic-ai/claude-agent-sdk\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Option from \"effect/Option\";\n\nconst SESSION_WINDOW_DURATION_MINS = 5 * 60;\nconst WEEKLY_WINDOW_DURATION_MINS = 7 * 24 * 60;\n\ninterface RawUsageWindow {\n  readonly label: string;\n  readonly usedPercent: number;\n  readonly resetsAt?: string;\n  readonly windowDurationMins?: number;\n}\n\nexport interface CodexRateLimitSnapshot {\n  readonly primary?: CodexRateLimitWindow | null;\n  readonly secondary?: CodexRateLimitWindow | null;\n}\n\ninterface CodexRateLimitWindow {\n  readonly usedPercent: number;\n  readonly resetsAt?: number | null;\n  readonly windowDurationMins?: number | null;\n}\n\nfunction clampPercent(value: number): number {\n  return Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0;\n}\n\nfunction normalizeUsageWindows(windows: ReadonlyArray<RawUsageWindow>) {\n  const durations = windows\n    .map((window) => window.windowDurationMins)\n    .filter((duration): duration is number => Number.isFinite(duration))\n    .toSorted((left, right) => left - right);\n  const shortest = durations[0];\n  const longest = durations.at(-1);\n\n  return windows.flatMap((window): ReadonlyArray<ServerProviderUsageWindow> => {\n    const duration = window.windowDurationMins;\n    if (typeof duration !== \"number\" || !Number.isFinite(duration)) return [];\n    const kind =\n      duration >= WEEKLY_WINDOW_DURATION_MINS || (duration === longest && longest !== shortest)\n        ? \"weekly\"\n        : \"session\";\n    return [\n      {\n        kind,\n        label: window.label.trim() || (kind === \"session\" ? \"Session\" : \"Weekly\"),\n        usedPercent: clampPercent(window.usedPercent),\n        ...(window.resetsAt ? { resetsAt: window.resetsAt } : {}),\n        windowDurationMins: Math.max(0, Math.round(duration)),\n      },\n    ];\n  });\n}\n\nfunction unavailableUsageLimits(\n  source: ServerProviderUsageLimits[\"source\"],\n  checkedAt: string,\n  reason: string,\n): ServerProviderUsageLimits {\n  return { source, available: false, reason, windows: [], checkedAt };\n}\n\nfunction epochSecondsToIso(value: number): string | undefined {\n  const dateTime = DateTime.make(value * 1000);\n  return Option.isSome(dateTime) ? DateTime.formatIso(dateTime.value) : undefined;\n}\n\nfunction normalizeIsoTimestamp(value: string | null): string | undefined {\n  if (!value) return undefined;\n  const dateTime = DateTime.make(value);\n  return Option.isSome(dateTime) ? DateTime.formatIso(dateTime.value) : undefined;\n}\n\nexport function resolveCodexUsageLimits(input: {\n  readonly checkedAt: string;\n  readonly snapshot?: CodexRateLimitSnapshot | null;\n}): ServerProviderUsageLimits {\n  const reported = [input.snapshot?.primary, input.snapshot?.secondary].filter(\n    (window): window is CodexRateLimitWindow =>\n      window !== null && window !== undefined && Number.isFinite(window.usedPercent),\n  );\n  const windows = reported.map((window, index) => {\n    const windowDurationMins =\n      window.windowDurationMins ??\n      (reported.length > 1 && index === 0\n        ? SESSION_WINDOW_DURATION_MINS\n        : WEEKLY_WINDOW_DURATION_MINS);\n    const resetsAt =\n      typeof window.resetsAt === \"number\" ? epochSecondsToIso(window.resetsAt) : undefined;\n    return {\n      label: \"\",\n      usedPercent: window.usedPercent,\n      windowDurationMins,\n      ...(resetsAt ? { resetsAt } : {}),\n    };\n  });\n\n  return windows.length === 0\n    ? unavailableUsageLimits(\n        \"codexAppServer\",\n        input.checkedAt,\n        \"No Codex subscription quota windows reported.\",\n      )\n    : {\n        source: \"codexAppServer\",\n        available: true,\n        windows: normalizeUsageWindows(windows),\n        checkedAt: input.checkedAt,\n      };\n}\n\nexport function resolveClaudeUsageLimits(input: {\n  readonly checkedAt: string;\n  readonly usage?: Pick<SDKControlGetUsageResponse, \"rate_limits_available\" | \"rate_limits\">;\n}): ServerProviderUsageLimits {\n  const usage = input.usage;\n  const limits = usage?.rate_limits;\n  if (!usage?.rate_limits_available || !limits) {\n    return unavailableUsageLimits(\n      \"claudeAgentSdk\",\n      input.checkedAt,\n      \"Claude subscription quota is unavailable for this account.\",\n    );\n  }\n\n  const windows = [\n    { label: \"Session\", duration: SESSION_WINDOW_DURATION_MINS, limit: limits.five_hour },\n    { label: \"Weekly\", duration: WEEKLY_WINDOW_DURATION_MINS, limit: limits.seven_day },\n  ].flatMap(({ label, duration, limit }): ReadonlyArray<RawUsageWindow> => {\n    if (!limit || typeof limit.utilization !== \"number\") return [];\n    const resetsAt = normalizeIsoTimestamp(limit.resets_at);\n    return [\n      {\n        label,\n        usedPercent: limit.utilization,\n        windowDurationMins: duration,\n        ...(resetsAt ? { resetsAt } : {}),\n      },\n    ];\n  });\n\n  return windows.length === 0\n    ? unavailableUsageLimits(\n        \"claudeAgentSdk\",\n        input.checkedAt,\n        \"No Claude subscription quota windows reported.\",\n      )\n    : {\n        source: \"claudeAgentSdk\",\n        available: true,\n        windows: normalizeUsageWindows(windows),\n        checkedAt: input.checkedAt,\n      };\n}\n","import {\n  type ClaudeSettings,\n  type ModelCapabilities,\n  type ModelSelection,\n  type ServerProviderModel,\n  type ServerProviderSlashCommand,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport {\n  createModelCapabilities,\n  getModelSelectionStringOptionValue,\n  getProviderOptionCurrentValue,\n  getProviderOptionDescriptors,\n} from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport { compareSemverVersions } from \"@t3tools/shared/semver\";\nimport {\n  query as claudeQuery,\n  type Options as ClaudeQueryOptions,\n  type SDKControlGetUsageResponse,\n  type SlashCommand as ClaudeSlashCommand,\n  type SDKUserMessage,\n  type SettingSource,\n} from \"@anthropic-ai/claude-agent-sdk\";\n\nimport {\n  buildBooleanOptionDescriptor,\n  buildSelectOptionDescriptor,\n  buildServerProvider,\n  DEFAULT_TIMEOUT_MS,\n  isCommandMissingCause,\n  parseGenericCliVersion,\n  providerModelsFromSettings,\n  spawnAndCollect,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport { resolveClaudeSdkExecutablePath } from \"../Drivers/ClaudeExecutable.ts\";\nimport { makeClaudeEnvironment } from \"../Drivers/ClaudeHome.ts\";\nimport { discoverClaudeSkills } from \"../Drivers/ClaudeSkills.ts\";\nimport { resolveClaudeUsageLimits } from \"../providerUsageLimits.ts\";\n\nconst DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n  optionDescriptors: [],\n});\n\nconst CLAUDE_PRESENTATION = {\n  displayName: \"Claude\",\n  showInteractionModeToggle: true,\n} as const;\nconst MINIMUM_CLAUDE_OPUS_5_VERSION = \"2.1.219\";\nconst MINIMUM_CLAUDE_FABLE_5_VERSION = \"2.1.169\";\nconst MINIMUM_CLAUDE_OPUS_4_8_VERSION = \"2.1.154\";\nconst MINIMUM_CLAUDE_OPUS_4_7_VERSION = \"2.1.111\";\n\nconst CURRENT_CLAUDE_MODELS = new Set([\"claude-fable-5\", \"claude-opus-5\", \"claude-sonnet-5\"]);\n\nexport function isLegacyClaudeModel(model: string): boolean {\n  return !CURRENT_CLAUDE_MODELS.has(model);\n}\n\nconst CLAUDE_MODEL_CATALOG: ReadonlyArray<ServerProviderModel> = [\n  {\n    slug: \"claude-fable-5\",\n    name: \"Claude Fable 5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultracode\", label: \"Ultracode\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          options: [\n            { value: \"200k\", label: \"200k\" },\n            { value: \"1m\", label: \"1M\", isDefault: true },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-5\",\n    name: \"Claude Opus 5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultracode\", label: \"Ultracode\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          // Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).\n          options: [\n            { value: \"200k\", label: \"200k\" },\n            { value: \"1m\", label: \"1M\", isDefault: true },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-8\",\n    name: \"Claude Opus 4.8\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultracode\", label: \"Ultracode\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-7\",\n    name: \"Claude Opus 4.7\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\" },\n            { value: \"xhigh\", label: \"Extra High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-6\",\n    name: \"Claude Opus 4.6\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          options: [\n            { value: \"200k\", label: \"200k\" },\n            { value: \"1m\", label: \"1M\", isDefault: true },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-5\",\n    name: \"Claude Opus 4.5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n          ],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-sonnet-5\",\n    name: \"Claude Sonnet 5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          // Sonnet is 200k-default in Claude Code (1M is opt-in there too).\n          options: [\n            { value: \"200k\", label: \"200k\", isDefault: true },\n            { value: \"1m\", label: \"1M\" },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-sonnet-4-6\",\n    name: \"Claude Sonnet 4.6\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          // Sonnet is 200k-default in Claude Code (1M is opt-in there too).\n          options: [\n            { value: \"200k\", label: \"200k\", isDefault: true },\n            { value: \"1m\", label: \"1M\" },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-haiku-4-5\",\n    name: \"Claude Haiku 4.5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildBooleanOptionDescriptor({\n          id: \"thinking\",\n          label: \"Thinking\",\n        }),\n      ],\n    }),\n  },\n];\n\nconst BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = CLAUDE_MODEL_CATALOG.map((model) =>\n  isLegacyClaudeModel(model.slug) ? { ...model, isLegacy: true } : model,\n);\n\nfunction supportsClaudeOpus5(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;\n}\n\nfunction supportsClaudeFable5(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;\n}\n\nfunction supportsClaudeOpus48(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;\n}\n\nfunction supportsClaudeOpus47(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;\n}\n\nfunction getBuiltInClaudeModelsForVersion(\n  version: string | null | undefined,\n): ReadonlyArray<ServerProviderModel> {\n  return BUILT_IN_MODELS.filter((model) => {\n    if (model.slug === \"claude-opus-5\") {\n      return supportsClaudeOpus5(version);\n    }\n    if (model.slug === \"claude-fable-5\") {\n      return supportsClaudeFable5(version);\n    }\n    if (model.slug === \"claude-opus-4-8\") {\n      return supportsClaudeOpus48(version);\n    }\n    if (model.slug === \"claude-opus-4-7\") {\n      return supportsClaudeOpus47(version);\n    }\n    return true;\n  });\n}\n\nfunction formatClaudeOpus5UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;\n}\n\nfunction formatClaudeFable5UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;\n}\n\nfunction formatClaudeOpus48UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;\n}\n\nfunction formatClaudeOpus47UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;\n}\n\nexport function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {\n  const slug = model?.trim();\n  return (\n    BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??\n    DEFAULT_CLAUDE_MODEL_CAPABILITIES\n  );\n}\n\nexport function resolveClaudeEffort(\n  caps: ModelCapabilities,\n  raw: string | null | undefined,\n): string | undefined {\n  const descriptors = getProviderOptionDescriptors({\n    caps,\n    ...(raw ? { selections: [{ id: \"effort\", value: raw }] } : {}),\n  });\n  const effortDescriptor = descriptors.find((descriptor) => descriptor.id === \"effort\");\n  const value = getProviderOptionCurrentValue(effortDescriptor);\n  return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Normalize a resolved Claude effort value into one suitable for the Claude\n * CLI's `--effort` flag.\n *\n * Mirrors the mapping used when invoking the Claude Agent SDK\n * ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): `ultracode` is a\n * Claude Code setting that pairs with `xhigh`, `ultrathink` is filtered out\n * because it is a prompt-prefix mode, and older model compatibility mappings\n * are preserved for current Claude Code behavior.\n */\nexport function normalizeClaudeCliEffort(\n  effort: string | null | undefined,\n  model: string | null | undefined,\n): string | undefined {\n  if (!effort || effort === \"ultrathink\") {\n    return undefined;\n  }\n  if (effort === \"ultracode\") {\n    return \"xhigh\";\n  }\n  if (\n    effort === \"xhigh\" &&\n    model !== \"claude-fable-5\" &&\n    model !== \"claude-opus-5\" &&\n    model !== \"claude-opus-4-8\" &&\n    model !== \"claude-sonnet-5\"\n  ) {\n    return \"max\";\n  }\n  if (effort === \"max\" && model === \"claude-sonnet-4-6\") {\n    return \"high\";\n  }\n  return effort;\n}\n\nexport function isClaudeUltracodeEffort(effort: string | null | undefined): boolean {\n  return effort === \"ultracode\";\n}\n\nexport function resolveClaudeContextWindow(\n  modelSelection: ModelSelection | undefined,\n): string | undefined {\n  const caps = getClaudeModelCapabilities(modelSelection?.model);\n  const raw = getModelSelectionStringOptionValue(modelSelection, \"contextWindow\");\n  const descriptors = getProviderOptionDescriptors({\n    caps,\n    ...(raw ? { selections: [{ id: \"contextWindow\", value: raw }] } : {}),\n  });\n  const descriptor = descriptors.find((candidate) => candidate.id === \"contextWindow\");\n  const value = getProviderOptionCurrentValue(descriptor);\n  return typeof value === \"string\" ? value : undefined;\n}\n\nexport function resolveClaudeApiModelId(modelSelection: ModelSelection): string {\n  switch (resolveClaudeContextWindow(modelSelection)) {\n    case \"1m\":\n      return `${modelSelection.model}[1m]`;\n    default:\n      return modelSelection.model;\n  }\n}\n\nfunction toTitleCaseWords(value: string): string {\n  const parts: Array<string> = [];\n  for (const part of value.split(/[\\s_-]+/g)) {\n    if (part.length > 0) {\n      parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase());\n    }\n  }\n  return parts.join(\" \");\n}\n\nfunction claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {\n  const normalized = subscriptionType?.toLowerCase().replace(/[\\s_-]+/g, \"\");\n  if (!normalized) return undefined;\n\n  switch (normalized) {\n    case \"claudemaxsubscription\":\n      return \"Max\";\n    case \"claudemax5xsubscription\":\n      return \"Max 5x\";\n    case \"claudemax20xsubscription\":\n      return \"Max 20x\";\n    case \"claudeenterprisesubscription\":\n      return \"Enterprise\";\n    case \"claudeteamsubscription\":\n      return \"Team\";\n    case \"claudeprosubscription\":\n      return \"Pro\";\n    case \"claudefreesubscription\":\n      return \"Free\";\n    case \"max\":\n    case \"maxplan\":\n      return \"Max\";\n    case \"max5\":\n      return \"Max 5x\";\n    case \"max20\":\n      return \"Max 20x\";\n    case \"enterprise\":\n      return \"Enterprise\";\n    case \"team\":\n      return \"Team\";\n    case \"pro\":\n      return \"Pro\";\n    case \"free\":\n      return \"Free\";\n    default:\n      return toTitleCaseWords(subscriptionType!);\n  }\n}\n\nfunction normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {\n  const normalized = authMethod?.toLowerCase().replace(/[\\s_-]+/g, \"\");\n  if (!normalized) return undefined;\n  if (\n    normalized === \"apikey\" ||\n    normalized === \"anthropicapikey\" ||\n    normalized === \"anthropicauthtoken\"\n  ) {\n    return \"apiKey\";\n  }\n  return undefined;\n}\n\nfunction formatClaudeSubscriptionAuthLabel(subscriptionType: string): string {\n  const subscriptionLabel =\n    claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType);\n  const normalized = subscriptionLabel.toLowerCase().replace(/[\\s_-]+/g, \"\");\n\n  if (normalized.startsWith(\"claude\") && normalized.endsWith(\"subscription\")) {\n    return subscriptionLabel;\n  }\n  if (normalized.startsWith(\"claude\")) {\n    return `${subscriptionLabel} Subscription`;\n  }\n  if (normalized.endsWith(\"subscription\")) {\n    return `Claude ${subscriptionLabel}`;\n  }\n  return `Claude ${subscriptionLabel} Subscription`;\n}\n\nfunction claudeAuthMetadata(input: {\n  readonly subscriptionType: string | undefined;\n  readonly authMethod: string | undefined;\n}): { readonly type: string; readonly label: string } | undefined {\n  if (normalizeClaudeAuthMethod(input.authMethod) === \"apiKey\") {\n    return {\n      type: \"apiKey\",\n      label: \"Claude API Key\",\n    };\n  }\n\n  if (input.subscriptionType) {\n    return {\n      type: input.subscriptionType,\n      label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),\n    };\n  }\n\n  return undefined;\n}\n\nfunction apiProviderAuthMetadata(\n  apiProvider: string | undefined,\n): { readonly type: string; readonly label: string } | undefined {\n  return apiProvider === \"bedrock\" ? { type: \"bedrock\", label: \"Amazon Bedrock\" } : undefined;\n}\n\n// ── SDK capability probe ────────────────────────────────────────────\n\n// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the\n// Bedrock backend and runs the `awsAuthRefresh` credential hook before returning\n// account info. The previous 8s budget expired mid-init, so the probe returned\n// `undefined` and left the provider unverified and unselectable in the picker.\nconst CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;\n\n/**\n * Keep workspace-scoped command discovery intact while isolating the periodic\n * health check from configured MCP servers.\n */\nexport const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [\n  \"user\",\n  \"project\",\n  \"local\",\n] as const satisfies ReadonlyArray<SettingSource>;\n\n/** Build the exact SDK options used by the periodic Claude capability probe. */\nexport function buildClaudeCapabilitiesProbeQueryOptions(input: {\n  readonly executablePath: string;\n  readonly abortController: AbortController;\n  readonly environment: NodeJS.ProcessEnv;\n  readonly cwd: string | undefined;\n}): ClaudeQueryOptions {\n  return {\n    persistSession: false,\n    pathToClaudeCodeExecutable: input.executablePath,\n    abortController: input.abortController,\n    settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],\n    allowedTools: [],\n    // Ignore MCP definitions from every filesystem setting source above. The\n    // SDK combines this empty explicit map with --strict-mcp-config.\n    mcpServers: {},\n    strictMcpConfig: true,\n    env: {\n      ...input.environment,\n      // Connected claude.ai MCP servers are discovered outside filesystem\n      // config; disable them independently for this health check.\n      ENABLE_CLAUDEAI_MCP_SERVERS: \"false\",\n    },\n    ...(input.cwd ? { cwd: input.cwd } : {}),\n    stderr: () => {},\n  };\n}\n\nfunction nonEmptyProbeString(value: string): string | undefined {\n  const candidate = value.trim();\n  return candidate ? candidate : undefined;\n}\n\ntype ClaudeCapabilitiesProbe = {\n  readonly email: string | undefined;\n  readonly subscriptionType: string | undefined;\n  readonly tokenSource: string | undefined;\n  /**\n   * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth\n   * login only applies when `\"firstParty\"`; for Amazon Bedrock (`\"bedrock\"`)\n   * the subscription/token fields are absent and auth is external AWS creds.\n   */\n  readonly apiProvider: string | undefined;\n  readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;\n  readonly usage: SDKControlGetUsageResponse | undefined;\n};\n\nfunction parseClaudeInitializationCommands(\n  commands: ReadonlyArray<ClaudeSlashCommand> | undefined,\n): ReadonlyArray<ServerProviderSlashCommand> {\n  return dedupeSlashCommands(\n    (commands ?? []).flatMap((command) => {\n      const name = nonEmptyProbeString(command.name);\n      if (!name) {\n        return [];\n      }\n\n      const description = nonEmptyProbeString(command.description);\n      const argumentHint = nonEmptyProbeString(command.argumentHint);\n\n      return [\n        {\n          name,\n          ...(description ? { description } : {}),\n          ...(argumentHint ? { input: { hint: argumentHint } } : {}),\n        } satisfies ServerProviderSlashCommand,\n      ];\n    }),\n  );\n}\n\nfunction dedupeSlashCommands(\n  commands: ReadonlyArray<ServerProviderSlashCommand>,\n): ReadonlyArray<ServerProviderSlashCommand> {\n  const commandsByName = new Map<string, ServerProviderSlashCommand>();\n\n  for (const command of commands) {\n    const name = nonEmptyProbeString(command.name);\n    if (!name) {\n      continue;\n    }\n\n    const key = name.toLowerCase();\n    const existing = commandsByName.get(key);\n    if (!existing) {\n      commandsByName.set(key, {\n        ...command,\n        name,\n      });\n      continue;\n    }\n\n    commandsByName.set(key, {\n      ...existing,\n      ...(existing.description\n        ? {}\n        : command.description\n          ? { description: command.description }\n          : {}),\n      ...(existing.input?.hint\n        ? {}\n        : command.input?.hint\n          ? { input: { hint: command.input.hint } }\n          : {}),\n    });\n  }\n\n  return [...commandsByName.values()];\n}\n\nfunction waitForAbortSignal(signal: AbortSignal): Promise<void> {\n  if (signal.aborted) {\n    return Promise.resolve();\n  }\n  return new Promise((resolve) => {\n    signal.addEventListener(\"abort\", () => resolve(), { once: true });\n  });\n}\n\n/**\n * Probe account information by spawning a lightweight Claude Agent SDK\n * session and reading the initialization result.\n *\n * We pass a never-yielding AsyncIterable as the prompt so that no user\n * message is ever written to the subprocess stdin. This means the Claude\n * Code subprocess completes its local initialization IPC (returning\n * account info and slash commands) but never starts an API request to\n * Anthropic. We read the init data and then abort the subprocess.\n *\n * This is used as a fallback when `claude auth status` does not include\n * subscription type information.\n */\nconst probeClaudeCapabilities = (\n  claudeSettings: ClaudeSettings,\n  environment?: NodeJS.ProcessEnv,\n  cwd?: string,\n) => {\n  const abort = new AbortController();\n  return Effect.gen(function* () {\n    const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n    const executablePath = yield* resolveClaudeSdkExecutablePath(\n      claudeSettings.binaryPath,\n      claudeEnvironment,\n    );\n    return yield* Effect.tryPromise(async () => {\n      const q = claudeQuery({\n        // Never yield — we only need initialization data, not a conversation.\n        // This prevents any prompt from reaching the Anthropic API.\n        // oxlint-disable-next-line require-yield\n        prompt: (async function* (): AsyncGenerator<SDKUserMessage> {\n          await waitForAbortSignal(abort.signal);\n        })(),\n        options: buildClaudeCapabilitiesProbeQueryOptions({\n          executablePath,\n          abortController: abort,\n          environment: claudeEnvironment,\n          cwd,\n        }),\n      });\n      const init = await q.initializationResult();\n      const usage = await q\n        .usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET()\n        .catch(() => undefined);\n      const account = init.account as\n        | {\n            readonly email?: string;\n            readonly subscriptionType?: string;\n            readonly tokenSource?: string;\n            readonly apiProvider?: string;\n          }\n        | undefined;\n      return {\n        email: account?.email,\n        subscriptionType: account?.subscriptionType,\n        tokenSource: account?.tokenSource,\n        apiProvider: account?.apiProvider,\n        slashCommands: parseClaudeInitializationCommands(init.commands),\n        usage,\n      } satisfies ClaudeCapabilitiesProbe;\n    });\n  }).pipe(\n    Effect.ensuring(\n      Effect.sync(() => {\n        if (!abort.signal.aborted) abort.abort();\n      }),\n    ),\n    Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),\n    Effect.result,\n    Effect.map((result) => {\n      if (Result.isFailure(result)) return undefined;\n      return Option.isSome(result.success) ? result.success.value : undefined;\n    }),\n  );\n};\n\nconst runClaudeCommand = Effect.fn(\"runClaudeCommand\")(function* (\n  claudeSettings: ClaudeSettings,\n  args: ReadonlyArray<string>,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n  const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {\n    env: claudeEnvironment,\n  });\n  const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n    env: claudeEnvironment,\n    shell: spawnCommand.shell,\n  });\n  return yield* spawnAndCollect(claudeSettings.binaryPath, command);\n});\n\nexport const checkClaudeProviderStatus = Effect.fn(\"checkClaudeProviderStatus\")(function* (\n  claudeSettings: ClaudeSettings,\n  resolveCapabilities?: (\n    claudeSettings: ClaudeSettings,\n  ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,\n  environment?: NodeJS.ProcessEnv,\n  cwd?: string,\n): Effect.fn.Return<\n  ServerProviderDraft,\n  never,\n  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path\n> {\n  const resolvedEnvironment = environment ?? process.env;\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const allModels = providerModelsFromSettings(\n    BUILT_IN_MODELS,\n    claudeSettings.customModels,\n    DEFAULT_CLAUDE_MODEL_CAPABILITIES,\n  );\n\n  if (!claudeSettings.enabled) {\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Claude is disabled in T3 Code settings.\",\n      },\n    });\n  }\n\n  const versionProbe = yield* runClaudeCommand(\n    claudeSettings,\n    [\"--version\"],\n    resolvedEnvironment,\n  ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);\n\n  if (Result.isFailure(versionProbe)) {\n    const error = versionProbe.failure;\n    yield* Effect.logWarning(\"Claude Agent CLI health check failed.\", {\n      errorTag: error._tag,\n    });\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: !isCommandMissingCause(error),\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: isCommandMissingCause(error)\n          ? \"Claude Agent CLI (`claude`) is not installed or not on PATH.\"\n          : \"Failed to execute Claude Agent CLI health check.\",\n      },\n    });\n  }\n\n  if (Option.isNone(versionProbe.success)) {\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message:\n          \"Claude Agent CLI is installed but failed to run. Timed out while running command.\",\n      },\n    });\n  }\n\n  const version = versionProbe.success.value;\n  const parsedVersion = parseGenericCliVersion(`${version.stdout}\\n${version.stderr}`);\n  if (version.code !== 0) {\n    yield* Effect.logWarning(\"Claude Agent CLI version probe exited with a non-zero status.\", {\n      exitCode: version.code,\n      stdoutLength: version.stdout.length,\n      stderrLength: version.stderr.length,\n    });\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: true,\n        version: parsedVersion,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Claude Agent CLI is installed but failed to run.\",\n      },\n    });\n  }\n\n  const models = providerModelsFromSettings(\n    getBuiltInClaudeModelsForVersion(parsedVersion),\n    claudeSettings.customModels,\n    DEFAULT_CLAUDE_MODEL_CAPABILITIES,\n  );\n  const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)\n    ? undefined\n    : supportsClaudeFable5(parsedVersion)\n      ? formatClaudeOpus5UpgradeMessage(parsedVersion)\n      : supportsClaudeOpus48(parsedVersion)\n        ? formatClaudeFable5UpgradeMessage(parsedVersion)\n        : supportsClaudeOpus47(parsedVersion)\n          ? formatClaudeOpus48UpgradeMessage(parsedVersion)\n          : formatClaudeOpus47UpgradeMessage(parsedVersion);\n\n  const capabilities = resolveCapabilities\n    ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))\n    : undefined;\n  const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);\n  const slashCommands = capabilities?.slashCommands ?? [];\n  const dedupedSlashCommands = dedupeSlashCommands(slashCommands);\n\n  if (!capabilities) {\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models,\n      slashCommands: dedupedSlashCommands,\n      skills,\n      probe: {\n        installed: true,\n        version: parsedVersion,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Could not verify Claude authentication status from initialization result.\",\n      },\n    });\n  }\n\n  const authMetadata =\n    claudeAuthMetadata({\n      subscriptionType: capabilities.subscriptionType,\n      authMethod: capabilities.tokenSource,\n    }) ?? apiProviderAuthMetadata(capabilities.apiProvider);\n  const usageLimits = resolveClaudeUsageLimits({\n    checkedAt,\n    ...(capabilities.usage ? { usage: capabilities.usage } : {}),\n  });\n  return buildServerProvider({\n    presentation: CLAUDE_PRESENTATION,\n    enabled: claudeSettings.enabled,\n    checkedAt,\n    models,\n    slashCommands: dedupedSlashCommands,\n    skills,\n    probe: {\n      installed: true,\n      version: parsedVersion,\n      status: \"ready\",\n      auth: {\n        status: \"authenticated\",\n        ...(capabilities.email ? { email: capabilities.email } : {}),\n        ...(authMetadata ? authMetadata : {}),\n      },\n      ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),\n      usageLimits,\n    },\n  });\n});\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\nexport const makePendingClaudeProvider = (\n  claudeSettings: ClaudeSettings,\n): Effect.Effect<ServerProviderDraft> =>\n  Effect.gen(function* () {\n    const checkedAt = yield* nowIso;\n    const models = providerModelsFromSettings(\n      BUILT_IN_MODELS,\n      claudeSettings.customModels,\n      DEFAULT_CLAUDE_MODEL_CAPABILITIES,\n    );\n\n    if (!claudeSettings.enabled) {\n      return buildServerProvider({\n        presentation: CLAUDE_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: \"Claude is disabled in T3 Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Claude provider status has not been checked in this session yet.\",\n      },\n    });\n  });\n\nexport { probeClaudeCapabilities };\n","/**\n * ClaudeTextGeneration – Text generation layer using the Claude CLI.\n *\n * Implements the same TextGeneration service contract as CodexTextGeneration but\n * delegates to the `claude` CLI (`claude -p`) with structured JSON output\n * instead of the `codex exec` CLI.\n *\n * @module ClaudeTextGeneration\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { type ClaudeSettings, type ModelSelection } from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport { TextGenerationError } from \"@t3tools/contracts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  normalizeCliError,\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n  toJsonSchemaObject,\n} from \"./TextGenerationUtils.ts\";\nimport {\n  getModelSelectionStringOptionValue,\n  getProviderOptionDescriptors,\n} from \"@t3tools/shared/model\";\nimport {\n  getClaudeModelCapabilities,\n  isClaudeUltracodeEffort,\n  normalizeClaudeCliEffort,\n  resolveClaudeApiModelId,\n  resolveClaudeEffort,\n} from \"../provider/Layers/ClaudeProvider.ts\";\nimport { makeClaudeEnvironment } from \"../provider/Drivers/ClaudeHome.ts\";\n\nconst CLAUDE_TIMEOUT_MS = 180_000;\n\n/**\n * Schema for the wrapper JSON returned by `claude -p --output-format json`.\n * We only care about `structured_output`.\n */\nconst ClaudeOutputEnvelope = Schema.Struct({\n  structured_output: Schema.Unknown,\n});\n\nconst encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));\nconst decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));\n\nexport const makeClaudeTextGeneration = Effect.fn(\"makeClaudeTextGeneration\")(function* (\n  claudeSettings: ClaudeSettings,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n\n  const readStreamAsString = <E>(\n    operation: string,\n    stream: Stream.Stream<Uint8Array, E>,\n  ): Effect.Effect<string, TextGenerationError> =>\n    stream.pipe(\n      Stream.decodeText(),\n      Stream.runFold(\n        () => \"\",\n        (acc, chunk) => acc + chunk,\n      ),\n      Effect.mapError((cause) =>\n        normalizeCliError(\"claude\", operation, cause, \"Failed to collect process output\"),\n      ),\n    );\n\n  const encodeJsonForOperation = (\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\",\n    value: unknown,\n    detail: string,\n  ): Effect.Effect<string, TextGenerationError> =>\n    encodeJsonString(value).pipe(\n      Effect.mapError(\n        (cause) =>\n          new TextGenerationError({\n            operation,\n            detail,\n            cause,\n          }),\n      ),\n    );\n\n  /**\n   * Spawn the Claude CLI with structured JSON output and return the parsed,\n   * schema-validated result.\n   */\n  const runClaudeJson = Effect.fn(\"runClaudeJson\")(function* <S extends Schema.Top>({\n    operation,\n    cwd,\n    prompt,\n    outputSchemaJson,\n    modelSelection,\n  }: {\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n    cwd: string;\n    prompt: string;\n    outputSchemaJson: S;\n    modelSelection: ModelSelection;\n  }): Effect.fn.Return<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> {\n    const jsonSchemaStr = yield* encodeJsonForOperation(\n      operation,\n      toJsonSchemaObject(outputSchemaJson),\n      \"Failed to encode structured output schema.\",\n    );\n    const caps = getClaudeModelCapabilities(modelSelection.model);\n    const descriptors = getProviderOptionDescriptors({\n      caps,\n      selections: modelSelection.options,\n    });\n    const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);\n    const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, \"effort\");\n    const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);\n    const cliEffort = normalizeClaudeCliEffort(resolvedEffort, modelSelection.model);\n    const ultracode = isClaudeUltracodeEffort(resolvedEffort);\n    const thinkingDescriptor = findDescriptor(\"thinking\");\n    const fastModeDescriptor = findDescriptor(\"fastMode\");\n    const thinking =\n      thinkingDescriptor?.type === \"boolean\" ? thinkingDescriptor.currentValue : undefined;\n    const fastMode =\n      fastModeDescriptor?.type === \"boolean\" ? fastModeDescriptor.currentValue : undefined;\n    const settings = {\n      ...(typeof thinking === \"boolean\" ? { alwaysThinkingEnabled: thinking } : {}),\n      ...(fastMode ? { fastMode: true } : {}),\n      ...(ultracode ? { ultracode: true } : {}),\n    };\n    const settingsJson =\n      Object.keys(settings).length > 0\n        ? yield* encodeJsonForOperation(\n            operation,\n            settings,\n            \"Failed to encode Claude CLI settings.\",\n          )\n        : undefined;\n\n    const runClaudeCommand = Effect.fn(\"runClaudeJson.runClaudeCommand\")(function* () {\n      const spawnCommand = yield* resolveSpawnCommand(\n        claudeSettings.binaryPath || \"claude\",\n        [\n          \"-p\",\n          \"--output-format\",\n          \"json\",\n          \"--json-schema\",\n          jsonSchemaStr,\n          \"--model\",\n          resolveClaudeApiModelId(modelSelection),\n          ...(cliEffort ? [\"--effort\", cliEffort] : []),\n          ...(settingsJson ? [\"--settings\", settingsJson] : []),\n          \"--dangerously-skip-permissions\",\n        ],\n        { env: claudeEnvironment },\n      );\n      const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        env: claudeEnvironment,\n        cwd,\n        shell: spawnCommand.shell,\n        stdin: {\n          stream: Stream.encodeText(Stream.make(prompt)),\n        },\n      });\n\n      const child = yield* commandSpawner\n        .spawn(command)\n        .pipe(\n          Effect.mapError((cause) =>\n            normalizeCliError(\"claude\", operation, cause, \"Failed to spawn Claude CLI process\"),\n          ),\n        );\n\n      const [stdout, stderr, exitCode] = yield* Effect.all(\n        [\n          readStreamAsString(operation, child.stdout),\n          readStreamAsString(operation, child.stderr),\n          child.exitCode.pipe(\n            Effect.mapError((cause) =>\n              normalizeCliError(\"claude\", operation, cause, \"Failed to read Claude CLI exit code\"),\n            ),\n          ),\n        ],\n        { concurrency: \"unbounded\" },\n      );\n\n      if (exitCode !== 0) {\n        const stderrDetail = stderr.trim();\n        const stdoutDetail = stdout.trim();\n        const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;\n        return yield* new TextGenerationError({\n          operation,\n          detail:\n            detail.length > 0\n              ? `Claude CLI command failed: ${detail}`\n              : `Claude CLI command failed with code ${exitCode}.`,\n        });\n      }\n\n      return stdout;\n    });\n\n    const rawStdout = yield* runClaudeCommand().pipe(\n      Effect.scoped,\n      Effect.timeoutOption(CLAUDE_TIMEOUT_MS),\n      Effect.flatMap(\n        Option.match({\n          onNone: () =>\n            Effect.fail(\n              new TextGenerationError({ operation, detail: \"Claude CLI request timed out.\" }),\n            ),\n          onSome: (value) => Effect.succeed(value),\n        }),\n      ),\n    );\n\n    const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(\n      Effect.catchTags({\n        SchemaError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation,\n              detail: \"Claude CLI returned unexpected output format.\",\n              cause,\n            }),\n          ),\n      }),\n    );\n\n    const decodeOutput = Schema.decodeEffect(outputSchemaJson);\n    return yield* decodeOutput(envelope.structured_output).pipe(\n      Effect.catchTags({\n        SchemaError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation,\n              detail: \"Claude returned invalid structured output.\",\n              cause,\n            }),\n          ),\n      }),\n    );\n  });\n\n  // ---------------------------------------------------------------------------\n  // TextGeneration service methods\n  // ---------------------------------------------------------------------------\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"ClaudeTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"ClaudeTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"ClaudeTextGeneration.generateBranchName\")(function* (input) {\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"ClaudeTextGeneration.generateThreadTitle\")(function* (input) {\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      };\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","export interface ParsedCliArgs {\n  readonly flags: Record<string, string | null>;\n  readonly positionals: string[];\n}\n\nexport interface ParseCliArgsOptions {\n  readonly booleanFlags?: readonly string[];\n}\n\nexport function tokenizeCliArgs(args?: string): ReadonlyArray<string> {\n  const input = args?.trim();\n  if (!input) return [];\n\n  const tokens: string[] = [];\n  let current = \"\";\n  let quote: \"'\" | '\"' | undefined;\n  let quoted = false;\n\n  for (let index = 0; index < input.length; index++) {\n    const char = input[index];\n    if (char === undefined) continue;\n\n    if (quote) {\n      if (char === quote) {\n        quote = undefined;\n        quoted = true;\n      } else if (char === \"\\\\\" && quote === '\"') {\n        const next = input[index + 1];\n        if (next !== undefined && ['\"', \"\\\\\", \"$\", \"`\"].includes(next)) {\n          current += next;\n          index++;\n        } else {\n          current += char;\n        }\n      } else {\n        current += char;\n      }\n      continue;\n    }\n\n    if (char === \"'\" || char === '\"') {\n      quote = char;\n      quoted = true;\n    } else if (/\\s/.test(char)) {\n      if (current || quoted) {\n        tokens.push(current);\n        current = \"\";\n        quoted = false;\n      }\n    } else if (char === \"\\\\\") {\n      const next = input[index + 1];\n      if (next !== undefined && /\\s/.test(next)) {\n        current += next;\n        index++;\n      } else {\n        current += char;\n      }\n    } else {\n      current += char;\n    }\n  }\n\n  if (current || quoted) tokens.push(current);\n  return tokens;\n}\n\n/**\n * Parse CLI-style arguments into flags and positionals.\n *\n * Accepts a string (quote-aware tokenized) or a pre-split argv array.\n * Supports `--key value`, `--key=value`, and `--flag` (boolean) syntax.\n *\n *   parseCliArgs(\"\")\n *     → { flags: {}, positionals: [] }\n *\n *   parseCliArgs(\"--chrome\")\n *     → { flags: { chrome: null }, positionals: [] }\n *\n *   parseCliArgs(\"--chrome --effort high\")\n *     → { flags: { chrome: null, effort: \"high\" }, positionals: [] }\n *\n *   parseCliArgs(\"--effort=high\")\n *     → { flags: { effort: \"high\" }, positionals: [] }\n *\n *   parseCliArgs([\"1.2.3\", \"--root\", \"/path\", \"--github-output\"], { booleanFlags: [\"github-output\"] })\n *     → { flags: { root: \"/path\", \"github-output\": null }, positionals: [\"1.2.3\"] }\n */\nexport function parseCliArgs(\n  args: string | readonly string[],\n  options?: ParseCliArgsOptions,\n): ParsedCliArgs {\n  const tokens = typeof args === \"string\" ? tokenizeCliArgs(args) : Array.from(args);\n  const booleanSet = options?.booleanFlags ? new Set(options.booleanFlags) : undefined;\n\n  const flags: Record<string, string | null> = {};\n  const positionals: string[] = [];\n\n  for (let i = 0; i < tokens.length; i++) {\n    const token = tokens[i]!;\n\n    if (token.startsWith(\"--\")) {\n      const rest = token.slice(2);\n      if (!rest) continue;\n\n      // Handle --key=value syntax\n      const eqIndex = rest.indexOf(\"=\");\n      if (eqIndex !== -1) {\n        flags[rest.slice(0, eqIndex)] = rest.slice(eqIndex + 1);\n        continue;\n      }\n\n      // Known boolean flag — never consumes next token\n      if (booleanSet?.has(rest)) {\n        flags[rest] = null;\n        continue;\n      }\n\n      // Handle --key value or --flag (boolean)\n      const next = tokens[i + 1];\n      if (next !== undefined && !next.startsWith(\"--\")) {\n        flags[rest] = next;\n        i++;\n      } else {\n        flags[rest] = null;\n      }\n    } else {\n      positionals.push(token);\n    }\n  }\n\n  return { flags, positionals };\n}\n","/**\n * ClaudeAdapterLive - Scoped live implementation for the Claude Agent provider adapter.\n *\n * Wraps `@anthropic-ai/claude-agent-sdk` query sessions behind the generic\n * provider adapter contract and emits canonical runtime events.\n *\n * @module ClaudeAdapterLive\n */\nimport {\n  type CanUseTool,\n  query,\n  type Options as ClaudeQueryOptions,\n  type PermissionMode,\n  type PermissionResult,\n  type PermissionUpdate,\n  type SDKMessage,\n  type SDKControlGetContextUsageResponse,\n  type SDKResultMessage,\n  type SettingSource,\n  type SDKUserMessage,\n  type ModelUsage,\n} from \"@anthropic-ai/claude-agent-sdk\";\nimport { parseCliArgs } from \"@t3tools/shared/cliArgs\";\nimport {\n  ApprovalRequestId,\n  type CanonicalItemType,\n  type CanonicalRequestType,\n  type ClaudeSettings,\n  EventId,\n  type ProviderApprovalDecision,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  type ModelSelection,\n  ProviderItemId,\n  type ProviderRuntimeEvent,\n  type ProviderRuntimeTurnStatus,\n  type ProviderSendTurnInput,\n  type ProviderSession,\n  type ThreadTokenUsageSnapshot,\n  type ProviderUserInputAnswers,\n  type RuntimeContentStreamKind,\n  RuntimeItemId,\n  RuntimeRequestId,\n  RuntimeTaskId,\n  type RuntimeTaskStatus,\n  type RuntimeTaskUsage,\n  type TaskAgentLinkage,\n  type TaskRunHandles,\n  ThreadId,\n  TurnId,\n  type UserInputQuestion,\n} from \"@t3tools/contracts\";\nimport {\n  applyClaudePromptEffortPrefix,\n  getModelSelectionBooleanOptionValue,\n  getModelSelectionStringOptionValue,\n  getProviderOptionDescriptors,\n  resolvePromptInjectedEffort,\n} from \"@t3tools/shared/model\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Path from \"effect/Path\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { resolveClaudeSdkExecutablePath } from \"../Drivers/ClaudeExecutable.ts\";\nimport { makeClaudeEnvironment } from \"../Drivers/ClaudeHome.ts\";\nimport {\n  getClaudeModelCapabilities,\n  isClaudeUltracodeEffort,\n  normalizeClaudeCliEffort,\n  resolveClaudeApiModelId,\n  resolveClaudeContextWindow,\n  resolveClaudeEffort,\n} from \"./ClaudeProvider.ts\";\nimport {\n  ProviderAdapterProcessError,\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionClosedError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n  type ProviderAdapterError,\n} from \"../Errors.ts\";\nimport { type ClaudeAdapterShape } from \"../Services/ClaudeAdapter.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nconst encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\nconst decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\n\nconst PROVIDER = ProviderDriverKind.make(\"claudeAgent\");\ntype ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, \"assistant_text\" | \"reasoning_text\">;\ntype ClaudeToolResultStreamKind = Extract<\n  RuntimeContentStreamKind,\n  \"command_output\" | \"file_change_output\"\n>;\ntype ClaudeSdkEffort = NonNullable<ClaudeQueryOptions[\"effort\"]>;\n\nfunction encodeJsonStringForDiagnostics(input: unknown): string | undefined {\n  const result = encodeUnknownJsonStringExit(input);\n  return Exit.isSuccess(result) ? result.value : undefined;\n}\n\ntype PromptQueueItem =\n  | {\n      readonly type: \"message\";\n      readonly message: SDKUserMessage;\n    }\n  | {\n      readonly type: \"terminate\";\n    };\n\ninterface ClaudeResumeState {\n  readonly threadId?: ThreadId;\n  readonly resume?: string;\n  readonly resumeSessionAt?: string;\n  readonly turnCount?: number;\n}\n\ninterface ClaudeTurnState {\n  readonly turnId: TurnId;\n  readonly startedAt: string;\n  /**\n   * True for turns auto-started by assistant output arriving without an\n   * active turn (background agent/subagent responses between user prompts).\n   * Synthetic turns are auto-closed by the next sendTurn; real turns are\n   * steered instead (the queued message continues the same turn).\n   */\n  readonly synthetic?: boolean;\n  readonly items: Array<unknown>;\n  readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;\n  readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;\n  readonly capturedProposedPlanKeys: Set<string>;\n  nextSyntheticAssistantBlockIndex: number;\n}\n\ninterface AssistantTextBlockState {\n  readonly itemId: string;\n  readonly blockIndex: number;\n  emittedTextDelta: boolean;\n  fallbackText: string;\n  streamClosed: boolean;\n  completionEmitted: boolean;\n}\n\ninterface PendingApproval {\n  readonly requestType: CanonicalRequestType;\n  readonly detail?: string;\n  readonly suggestions?: ReadonlyArray<PermissionUpdate>;\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n}\n\ninterface PendingUserInput {\n  readonly questions: ReadonlyArray<UserInputQuestion>;\n  readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;\n}\n\ninterface ToolInFlight {\n  readonly itemId: string;\n  readonly itemType: CanonicalItemType;\n  readonly toolName: string;\n  readonly title: string;\n  readonly detail?: string;\n  readonly input: Record<string, unknown>;\n  readonly partialInputJson: string;\n  readonly lastEmittedInputFingerprint?: string;\n  /** Owning agent when this tool ran inside a subagent (see attribution note). */\n  readonly agentId?: string;\n  readonly parentToolUseId?: string;\n}\n\ninterface ClaudeTaskState {\n  readonly id: string;\n  subject: string;\n  status: PlanStep[\"status\"];\n  readonly blockedBy: Set<string>;\n}\n\n/**\n * Agent identity captured from task_started and repeated on every subsequent\n * task.* payload, so client folds can reconstruct an agent even when its\n * start row aged out of activity retention.\n */\ninterface ClaudeTaskAgentState {\n  readonly taskId: string;\n  toolUseId: string | undefined;\n  description: string | undefined;\n  subagentType: string | undefined;\n  taskType: string | undefined;\n  workflowName: string | undefined;\n  skipTranscript: boolean;\n  runHandles: TaskRunHandles | undefined;\n  /** Set when this task was launched from inside a subagent. */\n  owningAgentId: string | undefined;\n  /** Seeded from the launching tool's input; refined by the subagent's own\n   * assistant snapshots (authoritative API model). */\n  model: string | undefined;\n  effort: string | undefined;\n}\n\ninterface ClaudeSessionContext {\n  session: ProviderSession;\n  readonly promptQueue: Queue.Queue<PromptQueueItem>;\n  readonly query: ClaudeQueryRuntime;\n  streamFiber: Fiber.Fiber<void, Error> | undefined;\n  readonly startedAt: string;\n  readonly basePermissionMode: PermissionMode | undefined;\n  currentApiModelId: string | undefined;\n  /** Effective effort for the session's turns; subagents without an explicit\n   * effort override inherit this. */\n  currentEffort: string | undefined;\n  resumeSessionId: string | undefined;\n  readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;\n  readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;\n  readonly turns: Array<{\n    id: TurnId;\n    items: Array<unknown>;\n  }>;\n  readonly inFlightTools: Map<number, ToolInFlight>;\n  readonly claudeTasks: Map<string, ClaudeTaskState>;\n  readonly taskAgents: Map<string, ClaudeTaskAgentState>;\n  /**\n   * Last emitted workflow-member fingerprint per member slot. A coordinator\n   * task_progress repeats the FULL member array every tick; without a\n   * material-transition filter one provider tick fans out into up to 100\n   * runtime events (event-log writes, queue pressure, client reducer work)\n   * even when nothing changed for most members.\n   */\n  readonly workflowMemberFingerprints: Map<string, string>;\n  /** Task ids that have started and not yet reached a terminal state. */\n  readonly liveTaskIds: Set<string>;\n  turnState: ClaudeTurnState | undefined;\n  lastKnownContextWindow: number | undefined;\n  lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;\n  lastKnownTotalProcessedTokens: number | undefined;\n  lastAssistantUuid: string | undefined;\n  lastThreadStartedId: string | undefined;\n  stopped: boolean;\n}\n\ninterface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {\n  readonly interrupt: () => Promise<void>;\n  /** SDK Query.stopTask — present on real queries; optional for test doubles. */\n  readonly stopTask?: (taskId: string) => Promise<void>;\n  readonly setModel: (model?: string) => Promise<void>;\n  readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;\n  readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;\n  readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;\n  readonly close: () => void;\n}\n\nexport interface ClaudeAdapterLiveOptions {\n  readonly instanceId?: ProviderInstanceId;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly createQuery?: (input: {\n    readonly prompt: AsyncIterable<SDKUserMessage>;\n    readonly options: ClaudeQueryOptions;\n  }) => ClaudeQueryRuntime;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n}\n\nfunction isUuid(value: string): boolean {\n  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\n}\n\nfunction isSyntheticClaudeThreadId(value: string): boolean {\n  return value.startsWith(\"claude-thread-\");\n}\n\nfunction hasDurableClaudeSessionId(message: SDKMessage): boolean {\n  if (message.type !== \"system\") {\n    return true;\n  }\n\n  return (\n    message.subtype !== \"hook_started\" &&\n    message.subtype !== \"hook_progress\" &&\n    message.subtype !== \"hook_response\"\n  );\n}\n\nfunction toMessage(cause: unknown, fallback: string): string {\n  if (cause instanceof Error && cause.message.length > 0) {\n    return cause.message;\n  }\n  return fallback;\n}\n\nfunction normalizeClaudeStreamMessages(\n  cause: Cause.Cause<ProviderAdapterProcessError>,\n): ReadonlyArray<string> {\n  const errors: Array<string> = [];\n  for (const error of Cause.prettyErrors(cause)) {\n    const message = error.message.trim();\n    if (message.length > 0) {\n      errors.push(message);\n    }\n  }\n  if (errors.length > 0) {\n    return errors;\n  }\n\n  const squashed = toMessage(Cause.squash(cause), \"\").trim();\n  return squashed.length > 0 ? [squashed] : [];\n}\n\nfunction getEffectiveClaudeAgentEffort(\n  effort: string | null | undefined,\n  model: string | null | undefined,\n): ClaudeSdkEffort | null {\n  const normalized = normalizeClaudeCliEffort(effort, model);\n  return normalized ? (normalized as ClaudeSdkEffort) : null;\n}\n\nfunction isClaudeInterruptedMessage(message: string): boolean {\n  const normalized = message.toLowerCase();\n  return (\n    normalized.includes(\"all fibers interrupted without error\") ||\n    normalized.includes(\"request was aborted\") ||\n    normalized.includes(\"interrupted by user\")\n  );\n}\n\nfunction isClaudeInterruptedCause(cause: Cause.Cause<ProviderAdapterProcessError>): boolean {\n  return (\n    Cause.hasInterruptsOnly(cause) ||\n    normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage) ||\n    cause.reasons.some(\n      (reason) =>\n        Cause.isFailReason(reason) && isClaudeInterruptedMessage(toMessage(reason.error.cause, \"\")),\n    )\n  );\n}\n\nfunction resultErrorsText(result: SDKResultMessage): string {\n  return \"errors\" in result && Array.isArray(result.errors)\n    ? result.errors.join(\" \").toLowerCase()\n    : \"\";\n}\n\nfunction isInterruptedResult(result: SDKResultMessage): boolean {\n  const errors = resultErrorsText(result);\n  if (errors.includes(\"interrupt\")) {\n    return true;\n  }\n\n  return (\n    result.subtype === \"error_during_execution\" &&\n    result.is_error === false &&\n    (errors.includes(\"request was aborted\") ||\n      errors.includes(\"interrupted by user\") ||\n      errors.includes(\"aborted\"))\n  );\n}\n\nfunction asRuntimeItemId(value: string): RuntimeItemId {\n  return RuntimeItemId.make(value);\n}\n\nfunction maxClaudeContextWindowFromModelUsage(\n  modelUsage: Record<string, ModelUsage> | undefined,\n): number | undefined {\n  if (!modelUsage) return undefined;\n\n  let maxContextWindow: number | undefined;\n  for (const value of Object.values(modelUsage)) {\n    const contextWindow = value.contextWindow;\n    maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);\n  }\n\n  return maxContextWindow;\n}\n\nfunction selectedClaudeContextWindow(\n  modelSelection: ModelSelection | undefined,\n): number | undefined {\n  switch (modelSelection?.model) {\n    case \"claude-opus-4-8\":\n    case \"claude-opus-4-7\":\n      // Always 1M at the API; these models expose no contextWindow option.\n      return 1_000_000;\n  }\n\n  switch (resolveClaudeContextWindow(modelSelection)) {\n    case \"1m\":\n      return 1_000_000;\n    case \"200k\":\n      return 200_000;\n    default:\n      return undefined;\n  }\n}\n\nfunction finiteNonNegativeInteger(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.round(value)\n    : undefined;\n}\n\nfunction finitePositiveInteger(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0\n    ? Math.round(value)\n    : undefined;\n}\n\nfunction claudeUsageInputTokens(usage: Record<string, unknown>): number {\n  return (\n    (finiteNonNegativeInteger(usage.input_tokens) ?? 0) +\n    (finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) +\n    (finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0)\n  );\n}\n\nfunction claudeUsageOutputTokens(usage: Record<string, unknown>): number {\n  return finiteNonNegativeInteger(usage.output_tokens) ?? 0;\n}\n\nfunction lastClaudeUsageIteration(\n  value: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n  const iterations = Array.isArray(value.iterations) ? value.iterations : [];\n  return iterations.findLast(\n    (iteration): iteration is Record<string, unknown> =>\n      iteration !== null && typeof iteration === \"object\" && !Array.isArray(iteration),\n  );\n}\n\nfunction claudeTotalProcessedTokens(value: unknown): number | undefined {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    return undefined;\n  }\n\n  const usage = value as Record<string, unknown>;\n  const explicitTotal = finiteNonNegativeInteger(usage.total_tokens);\n  if (explicitTotal !== undefined && explicitTotal > 0) {\n    return explicitTotal;\n  }\n\n  const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage);\n  return total > 0 ? total : undefined;\n}\n\nfunction makeClaudeTokenUsageSnapshot(input: {\n  readonly activeTokens: number;\n  readonly inputTokens?: number;\n  readonly outputTokens?: number;\n  readonly contextWindow?: number;\n  readonly totalProcessedTokens?: number;\n  readonly lastUsedTokens?: number;\n  readonly compactsAutomatically?: boolean;\n}): ThreadTokenUsageSnapshot | undefined {\n  const activeTokens = finiteNonNegativeInteger(input.activeTokens);\n  if (activeTokens === undefined || activeTokens <= 0) {\n    return undefined;\n  }\n\n  const maxTokens = finitePositiveInteger(input.contextWindow);\n  const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens;\n  const lastUsedTokens =\n    finiteNonNegativeInteger(input.lastUsedTokens) ??\n    (maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens);\n  const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens);\n  const inputTokens = finiteNonNegativeInteger(input.inputTokens);\n  const outputTokens = finiteNonNegativeInteger(input.outputTokens);\n\n  return {\n    usedTokens,\n    lastUsedTokens,\n    ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens\n      ? { totalProcessedTokens }\n      : {}),\n    ...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}),\n    ...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}),\n    ...(maxTokens !== undefined ? { maxTokens } : {}),\n    ...(input.compactsAutomatically !== undefined\n      ? { compactsAutomatically: input.compactsAutomatically }\n      : {}),\n  };\n}\n\nfunction normalizeClaudeActiveTokenUsage(\n  value: unknown,\n  contextWindow?: number,\n  totalProcessedTokens?: number,\n): ThreadTokenUsageSnapshot | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n\n  const usage = value as Record<string, unknown>;\n  const activeUsage = lastClaudeUsageIteration(usage) ?? usage;\n  const inputTokens = claudeUsageInputTokens(activeUsage);\n  const outputTokens = claudeUsageOutputTokens(activeUsage);\n  const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens;\n  if (activeTokens <= 0) {\n    return undefined;\n  }\n\n  return makeClaudeTokenUsageSnapshot({\n    activeTokens,\n    inputTokens,\n    outputTokens,\n    ...(contextWindow !== undefined ? { contextWindow } : {}),\n    ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),\n  });\n}\n\nfunction normalizeClaudeContextUsageApiSnapshot(\n  value: SDKControlGetContextUsageResponse,\n  totalProcessedTokens?: number,\n): ThreadTokenUsageSnapshot | undefined {\n  return makeClaudeTokenUsageSnapshot({\n    activeTokens: value.totalTokens,\n    contextWindow: value.maxTokens,\n    ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),\n    compactsAutomatically: value.isAutoCompactEnabled,\n  });\n}\n\nfunction compactBoundaryTokenUsageSnapshot(\n  message: Record<string, unknown>,\n  contextWindow?: number,\n  totalProcessedTokens?: number,\n): ThreadTokenUsageSnapshot | undefined {\n  const metadata = message.compact_metadata;\n  if (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n    return undefined;\n  }\n\n  const compactMetadata = metadata as Record<string, unknown>;\n  const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens);\n  if (postTokens === undefined || postTokens <= 0) {\n    return undefined;\n  }\n\n  const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens);\n  return makeClaudeTokenUsageSnapshot({\n    activeTokens: postTokens,\n    ...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}),\n    ...(contextWindow !== undefined ? { contextWindow } : {}),\n    ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),\n  });\n}\n\nfunction normalizeClaudeTaskProgressTokenUsage(\n  value: unknown,\n  context: ClaudeSessionContext,\n): ThreadTokenUsageSnapshot | undefined {\n  const totalTokens = claudeTotalProcessedTokens(value);\n  if (totalTokens === undefined || totalTokens <= 0) {\n    return undefined;\n  }\n\n  const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens;\n  const activeTokens =\n    lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;\n  if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {\n    return undefined;\n  }\n\n  const usage = value as Record<string, unknown>;\n  const snapshot = makeClaudeTokenUsageSnapshot({\n    activeTokens,\n    ...(context.lastKnownContextWindow !== undefined\n      ? { contextWindow: context.lastKnownContextWindow }\n      : {}),\n    totalProcessedTokens: Math.max(\n      totalTokens,\n      context.lastKnownTotalProcessedTokens ?? totalTokens,\n    ),\n  });\n  if (!snapshot) {\n    return undefined;\n  }\n\n  const toolUses = finiteNonNegativeInteger(usage.tool_uses);\n  const durationMs = finiteNonNegativeInteger(usage.duration_ms);\n  return {\n    ...snapshot,\n    ...(toolUses !== undefined ? { toolUses } : {}),\n    ...(durationMs !== undefined ? { durationMs } : {}),\n  };\n}\n\nfunction asCanonicalTurnId(value: TurnId): TurnId {\n  return value;\n}\n\nfunction asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId {\n  return RuntimeRequestId.make(value);\n}\n\nfunction readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined {\n  if (!resumeCursor || typeof resumeCursor !== \"object\") {\n    return undefined;\n  }\n  const cursor = resumeCursor as {\n    threadId?: unknown;\n    resume?: unknown;\n    sessionId?: unknown;\n    resumeSessionAt?: unknown;\n    turnCount?: unknown;\n  };\n\n  const threadIdCandidate = typeof cursor.threadId === \"string\" ? cursor.threadId : undefined;\n  const threadId =\n    threadIdCandidate && !isSyntheticClaudeThreadId(threadIdCandidate)\n      ? ThreadId.make(threadIdCandidate)\n      : undefined;\n  const resumeCandidate =\n    typeof cursor.resume === \"string\"\n      ? cursor.resume\n      : typeof cursor.sessionId === \"string\"\n        ? cursor.sessionId\n        : undefined;\n  const resume = resumeCandidate && isUuid(resumeCandidate) ? resumeCandidate : undefined;\n  const resumeSessionAt =\n    typeof cursor.resumeSessionAt === \"string\" ? cursor.resumeSessionAt : undefined;\n  const turnCountValue = typeof cursor.turnCount === \"number\" ? cursor.turnCount : undefined;\n\n  return {\n    ...(threadId ? { threadId } : {}),\n    ...(resume ? { resume } : {}),\n    ...(resumeSessionAt ? { resumeSessionAt } : {}),\n    ...(turnCountValue !== undefined && Number.isInteger(turnCountValue) && turnCountValue >= 0\n      ? { turnCount: turnCountValue }\n      : {}),\n  };\n}\n\nfunction classifyToolItemType(toolName: string): CanonicalItemType {\n  const normalized = toolName.toLowerCase();\n  if (normalized.includes(\"agent\")) {\n    return \"collab_agent_tool_call\";\n  }\n  if (\n    normalized === \"task\" ||\n    normalized === \"agent\" ||\n    normalized.includes(\"subagent\") ||\n    normalized.includes(\"sub-agent\")\n  ) {\n    return \"collab_agent_tool_call\";\n  }\n  if (\n    normalized.includes(\"bash\") ||\n    normalized.includes(\"command\") ||\n    normalized.includes(\"shell\") ||\n    normalized.includes(\"terminal\")\n  ) {\n    return \"command_execution\";\n  }\n  if (\n    normalized.includes(\"edit\") ||\n    normalized.includes(\"write\") ||\n    normalized.includes(\"file\") ||\n    normalized.includes(\"patch\") ||\n    normalized.includes(\"replace\") ||\n    normalized.includes(\"create\") ||\n    normalized.includes(\"delete\")\n  ) {\n    return \"file_change\";\n  }\n  if (normalized.includes(\"mcp\")) {\n    return \"mcp_tool_call\";\n  }\n  if (normalized.includes(\"websearch\") || normalized.includes(\"web search\")) {\n    return \"web_search\";\n  }\n  if (normalized.includes(\"image\")) {\n    return \"image_view\";\n  }\n  return \"dynamic_tool_call\";\n}\n\nfunction isReadOnlyToolName(toolName: string): boolean {\n  const normalized = toolName.toLowerCase();\n  return (\n    normalized === \"read\" ||\n    normalized.includes(\"read file\") ||\n    normalized.includes(\"view\") ||\n    normalized.includes(\"grep\") ||\n    normalized.includes(\"glob\") ||\n    normalized.includes(\"search\")\n  );\n}\n\nfunction classifyRequestType(toolName: string): CanonicalRequestType {\n  if (isReadOnlyToolName(toolName)) {\n    return \"file_read_approval\";\n  }\n  const itemType = classifyToolItemType(toolName);\n  return itemType === \"command_execution\"\n    ? \"command_execution_approval\"\n    : itemType === \"file_change\"\n      ? \"file_change_approval\"\n      : \"dynamic_tool_call\";\n}\n\nfunction isTodoTool(toolName: string): boolean {\n  return toolName.toLowerCase().includes(\"todowrite\");\n}\n\ntype PlanStep = {\n  step: string;\n  status: \"pending\" | \"inProgress\" | \"completed\";\n};\n\nfunction extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep[] | null {\n  // TodoWrite format: { todos: [{ content, status, activeForm? }] }\n  const todos = input.todos;\n  if (!Array.isArray(todos) || todos.length === 0) {\n    return null;\n  }\n  return todos\n    .filter((t): t is Record<string, unknown> => t !== null && typeof t === \"object\")\n    .map((todo) => ({\n      step:\n        typeof todo.content === \"string\" && todo.content.trim().length > 0\n          ? todo.content.trim()\n          : \"Task\",\n      status:\n        todo.status === \"completed\"\n          ? \"completed\"\n          : todo.status === \"in_progress\"\n            ? \"inProgress\"\n            : \"pending\",\n    }));\n}\n\nfunction isClaudeTaskTool(toolName: string): boolean {\n  return toolName === \"TaskCreate\" || toolName === \"TaskUpdate\" || toolName === \"TaskList\";\n}\n\nfunction normalizeClaudeTaskStatus(value: unknown): PlanStep[\"status\"] {\n  return value === \"completed\" ? \"completed\" : value === \"in_progress\" ? \"inProgress\" : \"pending\";\n}\n\nfunction readString(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction readStringArray(value: unknown): Array<string> {\n  return Array.isArray(value)\n    ? value.filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0)\n    : [];\n}\n\nfunction readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {\n  if (message.type !== \"user\") {\n    return undefined;\n  }\n  const result = (message as { readonly tool_use_result?: unknown }).tool_use_result;\n  return result !== null && typeof result === \"object\" && !Array.isArray(result)\n    ? (result as Record<string, unknown>)\n    : undefined;\n}\n\nfunction readClaudeTaskFromResult(\n  result: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n  const task = result?.task;\n  return task !== null && typeof task === \"object\" && !Array.isArray(task)\n    ? (task as Record<string, unknown>)\n    : undefined;\n}\n\nfunction applyClaudeTaskToolResult(\n  tasks: Map<string, ClaudeTaskState>,\n  tool: ToolInFlight,\n  result: Record<string, unknown> | undefined,\n): boolean {\n  if (!isClaudeTaskTool(tool.toolName)) {\n    return false;\n  }\n\n  let changed = false;\n  if (tool.toolName === \"TaskList\") {\n    const resultTasks = result?.tasks;\n    if (!Array.isArray(resultTasks)) {\n      return false;\n    }\n    tasks.clear();\n    for (const entry of resultTasks) {\n      if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) {\n        continue;\n      }\n      const task = entry as Record<string, unknown>;\n      const id = readString(task.id);\n      const subject = readString(task.subject);\n      if (!id || !subject) {\n        continue;\n      }\n      tasks.set(id, {\n        id,\n        subject,\n        status: normalizeClaudeTaskStatus(task.status),\n        blockedBy: new Set(readStringArray(task.blockedBy)),\n      });\n    }\n    return tasks.size > 0;\n  }\n\n  if (tool.toolName === \"TaskCreate\") {\n    const resultTask = readClaudeTaskFromResult(result);\n    const id = readString(resultTask?.id);\n    const subject = readString(resultTask?.subject) ?? readString(tool.input.subject);\n    if (!id || !subject) {\n      return false;\n    }\n    tasks.set(id, {\n      id,\n      subject,\n      status: normalizeClaudeTaskStatus(tool.input.status),\n      blockedBy: new Set(readStringArray(tool.input.blockedBy)),\n    });\n    return true;\n  }\n\n  const taskId = readString(tool.input.taskId) ?? readString(result?.taskId);\n  if (!taskId) {\n    return false;\n  }\n  const task = tasks.get(taskId);\n  if (!task) {\n    return false;\n  }\n  const subject = readString(tool.input.subject);\n  if (subject && task.subject !== subject) {\n    task.subject = subject;\n    changed = true;\n  }\n  if (typeof tool.input.status === \"string\") {\n    const status = normalizeClaudeTaskStatus(tool.input.status);\n    if (task.status !== status) {\n      task.status = status;\n      changed = true;\n    }\n  }\n  for (const dependency of readStringArray(tool.input.addBlockedBy)) {\n    if (!task.blockedBy.has(dependency)) {\n      task.blockedBy.add(dependency);\n      changed = true;\n    }\n  }\n  for (const dependency of readStringArray(tool.input.removeBlockedBy)) {\n    if (task.blockedBy.delete(dependency)) {\n      changed = true;\n    }\n  }\n  return changed;\n}\n\nfunction planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep[] {\n  return Array.from(tasks.values()).map((task) => {\n    const blockedBy = Array.from(task.blockedBy);\n    const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(\", #\")})` : \"\";\n    return {\n      step: `${task.subject}${blockedSuffix}`,\n      status: task.status,\n    };\n  });\n}\n\n/** Only http/https survive; anything else (javascript:, file:, …) is dropped. */\nfunction sanitizeSessionUrl(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  if (!/^https?:\\/\\//i.test(trimmed)) {\n    return undefined;\n  }\n  return trimmed;\n}\n\nfunction nonNegativeInt(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.floor(value)\n    : undefined;\n}\n\nfunction trimmedString(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * SDK task usage ({total_tokens, tool_uses, duration_ms}, sometimes with\n * input/output/cache breakdowns) → the typed contract shape. Unknown or\n * malformed input yields undefined rather than a partial guess.\n */\nfunction normalizeTaskUsage(usage: unknown): RuntimeTaskUsage | undefined {\n  if (typeof usage !== \"object\" || usage === null) {\n    return undefined;\n  }\n  const record = usage as Record<string, unknown>;\n  const totalTokens = nonNegativeInt(record.total_tokens);\n  if (totalTokens === undefined) {\n    return undefined;\n  }\n  const inputTokens = nonNegativeInt(record.input_tokens);\n  const cachedInputTokens = nonNegativeInt(record.cache_read_input_tokens);\n  const outputTokens = nonNegativeInt(record.output_tokens);\n  const toolUses = nonNegativeInt(record.tool_uses);\n  const durationMs = nonNegativeInt(record.duration_ms);\n  return {\n    totalTokens,\n    ...(inputTokens !== undefined ? { inputTokens } : {}),\n    ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n    ...(outputTokens !== undefined ? { outputTokens } : {}),\n    ...(toolUses !== undefined ? { toolUses } : {}),\n    ...(durationMs !== undefined ? { durationMs } : {}),\n  };\n}\n\n/** SDK task_updated patch status → the shared wire vocabulary. */\nconst CLAUDE_TASK_PATCH_STATUS: Record<string, RuntimeTaskStatus> = {\n  pending: \"pending\",\n  running: \"running\",\n  completed: \"completed\",\n  failed: \"failed\",\n  killed: \"cancelled\",\n  paused: \"idle\",\n};\n\n/**\n * Resolves a stream message's parent_tool_use_id to the owning agent's\n * taskId. The Task tool's tool_use_id is remembered on task_started; any\n * subagent-forwarded block carries that id as its parent. Returns undefined\n * for parent-conversation traffic.\n */\nfunction agentIdForParentToolUse(\n  agents: Map<string, ClaudeTaskAgentState>,\n  parentToolUseId: string | null | undefined,\n): string | undefined {\n  if (parentToolUseId === null || parentToolUseId === undefined) {\n    return undefined;\n  }\n  for (const agent of agents.values()) {\n    if (agent.toolUseId === parentToolUseId) {\n      return agent.taskId;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Linkage bundle repeated on every task.* payload for `taskId`. Reads the\n * remembered identity (from task_started) so progress/terminal rows are\n * self-describing even when the start row ages out of activity retention.\n */\nfunction taskLinkageFor(\n  agents: Map<string, ClaudeTaskAgentState>,\n  taskId: string,\n): TaskAgentLinkage {\n  const agent = agents.get(taskId);\n  if (!agent) {\n    return {};\n  }\n  return {\n    ...(agent.taskType ? { taskType: agent.taskType } : {}),\n    ...(agent.owningAgentId ? { agentId: agent.owningAgentId } : {}),\n    ...(agent.description ? { title: agent.description } : {}),\n    ...(agent.subagentType ? { role: agent.subagentType } : {}),\n    ...(agent.model ? { model: agent.model } : {}),\n    ...(agent.effort ? { effort: agent.effort } : {}),\n    ...(agent.toolUseId ? { toolUseId: agent.toolUseId } : {}),\n    ...(agent.workflowName ? { workflowName: agent.workflowName } : {}),\n    ...(agent.runHandles ? { runHandles: agent.runHandles } : {}),\n  };\n}\n\nconst WORKFLOW_PHASE_CAP = 64;\nconst WORKFLOW_AGENT_CAP = 100;\n\ninterface ClaudeWorkflowAgentEntry {\n  readonly index: number;\n  readonly state: string;\n  readonly label: string | undefined;\n  readonly phaseIndex: number | undefined;\n  readonly phaseTitle: string | undefined;\n  readonly model: string | undefined;\n  readonly attempt: number | undefined;\n  readonly lastToolName: string | undefined;\n  readonly startedAt: string | undefined;\n  readonly error: string | undefined;\n  readonly tokens: number | undefined;\n  readonly toolCalls: number | undefined;\n}\n\ninterface ClaudeWorkflowProgress {\n  readonly phases: ReadonlyArray<{ index: number; title: string }>;\n  readonly agents: ReadonlyArray<ClaudeWorkflowAgentEntry>;\n}\n\n/**\n * Defensive parse of the SDK's undeclared-but-real workflow_progress array on\n * task_progress messages (wire-confirmed; absent from sdk.d.ts). Unknown\n * shapes are skipped per-entry; phases and agents dedupe by index before\n * caps; a vanished field never throws. If the array disappears upstream the\n * caller keeps the coordinator row and plain task lifecycle.\n */\nfunction parseWorkflowProgress(value: unknown): ClaudeWorkflowProgress | undefined {\n  if (!Array.isArray(value) || value.length === 0) {\n    return undefined;\n  }\n  const phasesByIndex = new Map<number, string>();\n  const agentsByIndex = new Map<number, ClaudeWorkflowAgentEntry>();\n  for (const entry of value) {\n    if (typeof entry !== \"object\" || entry === null) {\n      continue;\n    }\n    const record = entry as Record<string, unknown>;\n    const entryType = trimmedString(record.type);\n    if (entryType === \"workflow_phase\") {\n      const index = nonNegativeInt(record.index);\n      const title = trimmedString(record.title);\n      if (index !== undefined && title && !phasesByIndex.has(index)) {\n        phasesByIndex.set(index, title);\n      }\n      continue;\n    }\n    if (entryType !== \"workflow_agent\") {\n      continue;\n    }\n    const index = nonNegativeInt(record.index);\n    const state = trimmedString(record.state);\n    if (index === undefined || !state || agentsByIndex.has(index)) {\n      continue;\n    }\n    agentsByIndex.set(index, {\n      index,\n      state,\n      label: trimmedString(record.label),\n      phaseIndex: nonNegativeInt(record.phaseIndex),\n      phaseTitle: trimmedString(record.phaseTitle),\n      model: trimmedString(record.model),\n      attempt: nonNegativeInt(record.attempt),\n      lastToolName: trimmedString(record.lastToolName),\n      startedAt: trimmedString(record.startedAt),\n      error: trimmedString(record.error),\n      tokens: nonNegativeInt(record.tokens),\n      toolCalls: nonNegativeInt(record.toolCalls),\n    });\n  }\n  if (phasesByIndex.size === 0 && agentsByIndex.size === 0) {\n    return undefined;\n  }\n  const phases = Array.from(phasesByIndex.entries())\n    .map(([index, title]) => ({ index, title }))\n    .toSorted((a, b) => a.index - b.index)\n    .slice(0, WORKFLOW_PHASE_CAP);\n  const agents = Array.from(agentsByIndex.values())\n    .toSorted((a, b) => a.index - b.index)\n    .slice(0, WORKFLOW_AGENT_CAP);\n  return { phases, agents };\n}\n\n/**\n * Workflow member states from workflow_progress → shared task status.\n * Unknown states read running after startedAt, pending before it.\n */\nfunction workflowAgentStatus(entry: ClaudeWorkflowAgentEntry): RuntimeTaskStatus {\n  switch (entry.state) {\n    case \"queued\":\n    case \"pending\":\n      return \"pending\";\n    case \"start\":\n    case \"running\":\n      return entry.startedAt === undefined ? \"pending\" : \"running\";\n    case \"done\":\n      return \"completed\";\n    case \"error\":\n      return \"failed\";\n    default:\n      return entry.startedAt === undefined ? \"pending\" : \"running\";\n  }\n}\n\nfunction summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {\n  const commandValue = input.command ?? input.cmd;\n  const command = typeof commandValue === \"string\" ? commandValue : undefined;\n  if (command && command.trim().length > 0) {\n    return `${toolName}: ${command.trim().slice(0, 400)}`;\n  }\n\n  // For agent/subagent tools, prefer the human-readable description or prompt\n  // over raw JSON. The structured subagent_type is carried separately on the\n  // task.* payloads (role) — the label is display-only.\n  const itemType = classifyToolItemType(toolName);\n  if (itemType === \"collab_agent_tool_call\") {\n    const description =\n      typeof input.description === \"string\" ? input.description.trim() : undefined;\n    const prompt = typeof input.prompt === \"string\" ? input.prompt.trim() : undefined;\n    const label = description || (prompt ? prompt.slice(0, 200) : undefined);\n    if (label) {\n      return label;\n    }\n  }\n\n  const serialized = encodeJsonStringForDiagnostics(input) ?? \"[unserializable input]\";\n  if (serialized.length <= 400) {\n    return `${toolName}: ${serialized}`;\n  }\n  return `${toolName}: ${serialized.slice(0, 397)}...`;\n}\n\nfunction titleForTool(itemType: CanonicalItemType): string {\n  switch (itemType) {\n    case \"command_execution\":\n      return \"Command run\";\n    case \"file_change\":\n      return \"File change\";\n    case \"mcp_tool_call\":\n      return \"MCP tool call\";\n    case \"collab_agent_tool_call\":\n      return \"Subagent task\";\n    case \"web_search\":\n      return \"Web search\";\n    case \"image_view\":\n      return \"Image view\";\n    case \"dynamic_tool_call\":\n      return \"Tool call\";\n    default:\n      return \"Item\";\n  }\n}\n\nconst SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([\n  \"image/gif\",\n  \"image/jpeg\",\n  \"image/png\",\n  \"image/webp\",\n]);\nconst CLAUDE_SETTING_SOURCES = [\n  \"user\",\n  \"project\",\n  \"local\",\n] as const satisfies ReadonlyArray<SettingSource>;\n\nfunction buildPromptText(\n  input: ProviderSendTurnInput,\n  boundInstanceId: ProviderInstanceId,\n): string {\n  const rawEffort =\n    input.modelSelection?.instanceId === boundInstanceId\n      ? getModelSelectionStringOptionValue(input.modelSelection, \"effort\")\n      : null;\n  const claudeModel =\n    input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined;\n  const caps = getClaudeModelCapabilities(claudeModel);\n\n  const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);\n  return applyClaudePromptEffortPrefix(input.input?.trim() ?? \"\", promptEffort);\n}\n\nfunction buildUserMessage(input: {\n  readonly sdkContent: Array<Record<string, unknown>>;\n}): SDKUserMessage {\n  return {\n    type: \"user\",\n    session_id: \"\",\n    parent_tool_use_id: null,\n    message: {\n      role: \"user\",\n      content: input.sdkContent as unknown as SDKUserMessage[\"message\"][\"content\"],\n    },\n  } as SDKUserMessage;\n}\n\nfunction buildClaudeImageContentBlock(input: {\n  readonly mimeType: string;\n  readonly bytes: Uint8Array;\n}): Record<string, unknown> {\n  return {\n    type: \"image\",\n    source: {\n      type: \"base64\",\n      media_type: input.mimeType,\n      data: Buffer.from(input.bytes).toString(\"base64\"),\n    },\n  };\n}\n\nconst buildUserMessageEffect = Effect.fn(\"buildUserMessageEffect\")(function* (\n  input: ProviderSendTurnInput,\n  dependencies: {\n    readonly fileSystem: FileSystem.FileSystem;\n    readonly attachmentsDir: string;\n    readonly boundInstanceId: ProviderInstanceId;\n  },\n) {\n  const text = buildPromptText(input, dependencies.boundInstanceId);\n  const sdkContent: Array<Record<string, unknown>> = [];\n\n  if (text.length > 0) {\n    sdkContent.push({ type: \"text\", text });\n  }\n\n  for (const attachment of input.attachments ?? []) {\n    if (attachment.type !== \"image\") {\n      continue;\n    }\n\n    if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"turn/start\",\n        detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,\n      });\n    }\n\n    const attachmentPath = resolveAttachmentPath({\n      attachmentsDir: dependencies.attachmentsDir,\n      attachment,\n    });\n    if (!attachmentPath) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"turn/start\",\n        detail: `Invalid attachment id '${attachment.id}'.`,\n      });\n    }\n\n    const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"turn/start\",\n            detail: \"Failed to read attachment file.\",\n            cause,\n          }),\n      ),\n    );\n\n    sdkContent.push(\n      buildClaudeImageContentBlock({\n        mimeType: attachment.mimeType,\n        bytes,\n      }),\n    );\n  }\n\n  return buildUserMessage({ sdkContent });\n});\n\nfunction turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {\n  if (result.subtype === \"success\") {\n    return \"completed\";\n  }\n\n  const errors = resultErrorsText(result);\n  if (isInterruptedResult(result)) {\n    return \"interrupted\";\n  }\n  if (errors.includes(\"cancel\")) {\n    return \"cancelled\";\n  }\n  return \"failed\";\n}\n\nfunction streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {\n  return deltaType.includes(\"thinking\") ? \"reasoning_text\" : \"assistant_text\";\n}\n\nfunction nativeProviderRefs(\n  _context: ClaudeSessionContext,\n  options?: {\n    readonly providerItemId?: string | undefined;\n  },\n): NonNullable<ProviderRuntimeEvent[\"providerRefs\"]> {\n  if (options?.providerItemId) {\n    return {\n      providerItemId: ProviderItemId.make(options.providerItemId),\n    };\n  }\n  return {};\n}\n\nfunction extractAssistantTextBlocks(message: SDKMessage): Array<string> {\n  if (message.type !== \"assistant\") {\n    return [];\n  }\n\n  const content = (message.message as { content?: unknown } | undefined)?.content;\n  if (!Array.isArray(content)) {\n    return [];\n  }\n\n  const fragments: string[] = [];\n  for (const block of content) {\n    if (!block || typeof block !== \"object\") {\n      continue;\n    }\n    const candidate = block as { type?: unknown; text?: unknown };\n    if (\n      candidate.type === \"text\" &&\n      typeof candidate.text === \"string\" &&\n      candidate.text.length > 0\n    ) {\n      fragments.push(candidate.text);\n    }\n  }\n\n  return fragments;\n}\n\nfunction extractContentBlockText(block: unknown): string {\n  if (!block || typeof block !== \"object\") {\n    return \"\";\n  }\n\n  const candidate = block as { type?: unknown; text?: unknown };\n  return candidate.type === \"text\" && typeof candidate.text === \"string\" ? candidate.text : \"\";\n}\n\nfunction extractTextContent(value: unknown): string {\n  if (typeof value === \"string\") {\n    return value;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map((entry) => extractTextContent(entry)).join(\"\");\n  }\n\n  if (!value || typeof value !== \"object\") {\n    return \"\";\n  }\n\n  const record = value as {\n    text?: unknown;\n    content?: unknown;\n  };\n\n  if (typeof record.text === \"string\") {\n    return record.text;\n  }\n\n  return extractTextContent(record.content);\n}\n\nfunction extractExitPlanModePlan(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n\n  const record = value as {\n    plan?: unknown;\n  };\n  return typeof record.plan === \"string\" && record.plan.trim().length > 0\n    ? record.plan.trim()\n    : undefined;\n}\n\nfunction exitPlanCaptureKey(input: {\n  readonly toolUseId?: string | undefined;\n  readonly planMarkdown: string;\n}): string {\n  return input.toolUseId && input.toolUseId.length > 0\n    ? `tool:${input.toolUseId}`\n    : `plan:${input.planMarkdown}`;\n}\n\nfunction tryParseJsonRecord(value: string): Record<string, unknown> | undefined {\n  const result = decodeUnknownJsonStringExit(value);\n  if (!Exit.isSuccess(result)) {\n    return undefined;\n  }\n  const parsed = result.value;\n  return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n    ? (parsed as Record<string, unknown>)\n    : undefined;\n}\n\nfunction toolInputFingerprint(input: Record<string, unknown>): string | undefined {\n  return encodeJsonStringForDiagnostics(input);\n}\n\nfunction toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {\n  switch (itemType) {\n    case \"command_execution\":\n      return \"command_output\";\n    case \"file_change\":\n      return \"file_change_output\";\n    default:\n      return undefined;\n  }\n}\n\nfunction toolResultBlocksFromUserMessage(message: SDKMessage): Array<{\n  readonly toolUseId: string;\n  readonly block: Record<string, unknown>;\n  readonly text: string;\n  readonly isError: boolean;\n}> {\n  if (message.type !== \"user\") {\n    return [];\n  }\n\n  const content = (message.message as { content?: unknown } | undefined)?.content;\n  if (!Array.isArray(content)) {\n    return [];\n  }\n\n  const blocks: Array<{\n    readonly toolUseId: string;\n    readonly block: Record<string, unknown>;\n    readonly text: string;\n    readonly isError: boolean;\n  }> = [];\n\n  for (const entry of content) {\n    if (!entry || typeof entry !== \"object\") {\n      continue;\n    }\n\n    const block = entry as Record<string, unknown>;\n    if (block.type !== \"tool_result\") {\n      continue;\n    }\n\n    const toolUseId = typeof block.tool_use_id === \"string\" ? block.tool_use_id : undefined;\n    if (!toolUseId) {\n      continue;\n    }\n\n    blocks.push({\n      toolUseId,\n      block,\n      text: extractTextContent(block.content),\n      isError: block.is_error === true,\n    });\n  }\n\n  return blocks;\n}\n\nfunction toSessionError(\n  threadId: ThreadId,\n  cause: unknown,\n): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {\n  const normalized = toMessage(cause, \"\").toLowerCase();\n  if (normalized.includes(\"unknown session\") || normalized.includes(\"not found\")) {\n    return new ProviderAdapterSessionNotFoundError({\n      provider: PROVIDER,\n      threadId,\n      cause,\n    });\n  }\n  if (normalized.includes(\"closed\")) {\n    return new ProviderAdapterSessionClosedError({\n      provider: PROVIDER,\n      threadId,\n      cause,\n    });\n  }\n  return undefined;\n}\n\nfunction toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError {\n  const sessionError = toSessionError(threadId, cause);\n  if (sessionError) {\n    return sessionError;\n  }\n  return new ProviderAdapterRequestError({\n    provider: PROVIDER,\n    method,\n    detail: `${method} failed`,\n    cause,\n  });\n}\n\nfunction sdkMessageType(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n  const record = value as { type?: unknown };\n  return typeof record.type === \"string\" ? record.type : undefined;\n}\n\nfunction sdkMessageSubtype(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n  const record = value as { subtype?: unknown };\n  return typeof record.subtype === \"string\" ? record.subtype : undefined;\n}\n\nfunction sdkNativeMethod(message: SDKMessage): string {\n  const subtype = sdkMessageSubtype(message);\n  if (subtype) {\n    return `claude/${message.type}/${subtype}`;\n  }\n\n  if (message.type === \"stream_event\") {\n    const streamType = sdkMessageType(message.event);\n    if (streamType) {\n      const deltaType =\n        streamType === \"content_block_delta\"\n          ? sdkMessageType((message.event as { delta?: unknown }).delta)\n          : undefined;\n      if (deltaType) {\n        return `claude/${message.type}/${streamType}/${deltaType}`;\n      }\n      return `claude/${message.type}/${streamType}`;\n    }\n  }\n\n  return `claude/${message.type}`;\n}\n\n// Discriminator/identity keys carry no human-readable content; everything else\n// on an unmodeled SDK message is potentially worth surfacing in the work log.\nconst SDK_MESSAGE_NOISE_KEYS = new Set([\n  \"type\",\n  \"subtype\",\n  \"uuid\",\n  \"parent_uuid\",\n  \"session_id\",\n  \"parent_tool_use_id\",\n  \"request_id\",\n]);\n\n// Pull the salient scalar content out of a message the adapter doesn't model\n// yet, so the work-log row shows what actually arrived (e.g. a notification's\n// text) instead of an opaque \"unhandled subtype\" placeholder. Nested structures\n// are left to the full payload retained in the event's `detail`.\nfunction previewUnknownSdkContent(message: unknown): string | undefined {\n  if (!message || typeof message !== \"object\") {\n    return undefined;\n  }\n  const parts: string[] = [];\n  for (const [key, value] of Object.entries(message as Record<string, unknown>)) {\n    if (SDK_MESSAGE_NOISE_KEYS.has(key)) {\n      continue;\n    }\n    if (typeof value === \"string\") {\n      const trimmed = value.trim();\n      if (trimmed.length > 0) {\n        parts.push(`${key}: ${trimmed}`);\n      }\n    } else if (typeof value === \"number\" || typeof value === \"boolean\") {\n      parts.push(`${key}: ${String(value)}`);\n    }\n  }\n  if (parts.length === 0) {\n    return undefined;\n  }\n  const joined = parts.join(\" · \");\n  return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;\n}\n\nfunction describeUnknownSdkMessage(kind: string, message: unknown): string {\n  const preview = previewUnknownSdkContent(message);\n  return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;\n}\n\nfunction sdkNativeItemId(message: SDKMessage): string | undefined {\n  if (message.type === \"assistant\") {\n    const maybeId = (message.message as { id?: unknown }).id;\n    if (typeof maybeId === \"string\") {\n      return maybeId;\n    }\n    return undefined;\n  }\n\n  if (message.type === \"user\") {\n    return toolResultBlocksFromUserMessage(message)[0]?.toolUseId;\n  }\n\n  if (message.type === \"stream_event\") {\n    const event = message.event as {\n      type?: unknown;\n      content_block?: { id?: unknown };\n    };\n    if (event.type === \"content_block_start\" && typeof event.content_block?.id === \"string\") {\n      return event.content_block.id;\n    }\n  }\n\n  return undefined;\n}\n\nexport const makeClaudeAdapter = Effect.fn(\"makeClaudeAdapter\")(function* (\n  claudeSettings: ClaudeSettings,\n  options?: ClaudeAdapterLiveOptions,\n) {\n  const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"claudeAgent\");\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const serverConfig = yield* ServerConfig;\n  const crypto = yield* Crypto.Crypto;\n  const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(\n    Effect.provideService(Path.Path, path),\n  );\n  const claudeSdkExecutablePath = yield* resolveClaudeSdkExecutablePath(\n    claudeSettings.binaryPath,\n    claudeEnvironment,\n  );\n  const nativeEventLogger =\n    options?.nativeEventLogger ??\n    (options?.nativeEventLogPath !== undefined\n      ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n          stream: \"native\",\n        })\n      : undefined);\n  const managedNativeEventLogger =\n    options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n\n  const createQuery =\n    options?.createQuery ??\n    ((input: {\n      readonly prompt: AsyncIterable<SDKUserMessage>;\n      readonly options: ClaudeQueryOptions;\n    }) =>\n      query({\n        prompt: input.prompt,\n        options: input.options,\n      }) as ClaudeQueryRuntime);\n\n  const sessions = new Map<ThreadId, ClaudeSessionContext>();\n  const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();\n\n  const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n  const randomUUIDv4 = crypto.randomUUIDv4.pipe(\n    Effect.mapError(\n      (cause) =>\n        new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"crypto/randomUUIDv4\",\n          detail: \"Failed to generate Claude runtime identifier.\",\n          cause,\n        }),\n    ),\n  );\n  const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));\n  const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });\n\n  const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>\n    Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);\n\n  const logNativeSdkMessage = Effect.fnUntraced(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (!nativeEventLogger) {\n      return;\n    }\n\n    const observedAt = yield* nowIso;\n    const itemId = sdkNativeItemId(message);\n\n    yield* nativeEventLogger.write(\n      {\n        observedAt,\n        event: {\n          id:\n            \"uuid\" in message && typeof message.uuid === \"string\"\n              ? message.uuid\n              : yield* randomUUIDv4,\n          kind: \"notification\",\n          provider: PROVIDER,\n          createdAt: observedAt,\n          method: sdkNativeMethod(message),\n          ...(typeof message.session_id === \"string\"\n            ? { providerThreadId: message.session_id }\n            : {}),\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          ...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),\n          payload: message,\n        },\n      },\n      context.session.threadId,\n    );\n  });\n\n  const snapshotThread = Effect.fn(\"snapshotThread\")(function* (context: ClaudeSessionContext) {\n    const threadId = context.session.threadId;\n    if (!threadId) {\n      return yield* new ProviderAdapterValidationError({\n        provider: PROVIDER,\n        operation: \"readThread\",\n        issue: \"Session thread id is not initialized yet.\",\n      });\n    }\n    return {\n      threadId,\n      turns: context.turns.map((turn) => ({\n        id: turn.id,\n        items: [...turn.items],\n      })),\n    };\n  });\n\n  const updateResumeCursor = Effect.fn(\"updateResumeCursor\")(function* (\n    context: ClaudeSessionContext,\n  ) {\n    const threadId = context.session.threadId;\n    if (!threadId) return;\n\n    const resumeCursor = {\n      threadId,\n      ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}),\n      ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}),\n      turnCount: context.turns.length,\n    };\n\n    context.session = {\n      ...context.session,\n      resumeCursor,\n      updatedAt: yield* nowIso,\n    };\n  });\n\n  const ensureAssistantTextBlock = Effect.fn(\"ensureAssistantTextBlock\")(function* (\n    context: ClaudeSessionContext,\n    blockIndex: number,\n    options?: {\n      readonly fallbackText?: string;\n      readonly streamClosed?: boolean;\n    },\n  ) {\n    const turnState = context.turnState;\n    if (!turnState) {\n      return undefined;\n    }\n\n    const existing = turnState.assistantTextBlocks.get(blockIndex);\n    if (existing && !existing.completionEmitted) {\n      if (existing.fallbackText.length === 0 && options?.fallbackText) {\n        existing.fallbackText = options.fallbackText;\n      }\n      if (options?.streamClosed) {\n        existing.streamClosed = true;\n      }\n      return { blockIndex, block: existing };\n    }\n\n    const block: AssistantTextBlockState = {\n      itemId: yield* randomUUIDv4,\n      blockIndex,\n      emittedTextDelta: false,\n      fallbackText: options?.fallbackText ?? \"\",\n      streamClosed: options?.streamClosed ?? false,\n      completionEmitted: false,\n    };\n    turnState.assistantTextBlocks.set(blockIndex, block);\n    turnState.assistantTextBlockOrder.push(block);\n    return { blockIndex, block };\n  });\n\n  const createSyntheticAssistantTextBlock = Effect.fn(\"createSyntheticAssistantTextBlock\")(\n    function* (context: ClaudeSessionContext, fallbackText: string) {\n      const turnState = context.turnState;\n      if (!turnState) {\n        return undefined;\n      }\n\n      const blockIndex = turnState.nextSyntheticAssistantBlockIndex;\n      turnState.nextSyntheticAssistantBlockIndex -= 1;\n      return yield* ensureAssistantTextBlock(context, blockIndex, {\n        fallbackText,\n        streamClosed: true,\n      });\n    },\n  );\n\n  const completeAssistantTextBlock = Effect.fn(\"completeAssistantTextBlock\")(function* (\n    context: ClaudeSessionContext,\n    block: AssistantTextBlockState,\n    options?: {\n      readonly force?: boolean;\n      readonly rawMethod?: string;\n      readonly rawPayload?: unknown;\n    },\n  ) {\n    const turnState = context.turnState;\n    if (!turnState || block.completionEmitted) {\n      return;\n    }\n\n    if (!options?.force && !block.streamClosed) {\n      return;\n    }\n\n    if (!block.emittedTextDelta && block.fallbackText.length > 0) {\n      const deltaStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"content.delta\",\n        eventId: deltaStamp.eventId,\n        provider: PROVIDER,\n        createdAt: deltaStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId: turnState.turnId,\n        itemId: asRuntimeItemId(block.itemId),\n        payload: {\n          streamKind: \"assistant_text\",\n          delta: block.fallbackText,\n        },\n        providerRefs: nativeProviderRefs(context),\n        ...(options?.rawMethod || options?.rawPayload\n          ? {\n              raw: {\n                source: \"claude.sdk.message\" as const,\n                ...(options.rawMethod ? { method: options.rawMethod } : {}),\n                payload: options?.rawPayload,\n              },\n            }\n          : {}),\n      });\n    }\n\n    block.completionEmitted = true;\n    if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {\n      turnState.assistantTextBlocks.delete(block.blockIndex);\n    }\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"item.completed\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      itemId: asRuntimeItemId(block.itemId),\n      threadId: context.session.threadId,\n      turnId: turnState.turnId,\n      payload: {\n        itemType: \"assistant_message\",\n        status: \"completed\",\n        title: \"Assistant message\",\n        ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n      ...(options?.rawMethod || options?.rawPayload\n        ? {\n            raw: {\n              source: \"claude.sdk.message\" as const,\n              ...(options.rawMethod ? { method: options.rawMethod } : {}),\n              payload: options?.rawPayload,\n            },\n          }\n        : {}),\n    });\n  });\n\n  const backfillAssistantTextBlocksFromSnapshot = Effect.fn(\n    \"backfillAssistantTextBlocksFromSnapshot\",\n  )(function* (context: ClaudeSessionContext, message: SDKMessage) {\n    const turnState = context.turnState;\n    if (!turnState) {\n      return;\n    }\n\n    const snapshotTextBlocks = extractAssistantTextBlocks(message);\n    if (snapshotTextBlocks.length === 0) {\n      return;\n    }\n\n    const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({\n      blockIndex: block.blockIndex,\n      block,\n    }));\n\n    for (const [position, text] of snapshotTextBlocks.entries()) {\n      const existingEntry = orderedBlocks[position];\n      const entry =\n        existingEntry ??\n        (yield* createSyntheticAssistantTextBlock(context, text).pipe(\n          Effect.map((created) => {\n            if (!created) {\n              return undefined;\n            }\n            orderedBlocks.push(created);\n            return created;\n          }),\n        ));\n      if (!entry) {\n        continue;\n      }\n\n      if (entry.block.fallbackText.length === 0) {\n        entry.block.fallbackText = text;\n      }\n\n      if (entry.block.streamClosed && !entry.block.completionEmitted) {\n        yield* completeAssistantTextBlock(context, entry.block, {\n          rawMethod: \"claude/assistant\",\n          rawPayload: message,\n        });\n      }\n    }\n  });\n\n  const ensureThreadId = Effect.fn(\"ensureThreadId\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (typeof message.session_id !== \"string\" || message.session_id.length === 0) {\n      return;\n    }\n    if (!hasDurableClaudeSessionId(message)) {\n      return;\n    }\n    const nextThreadId = message.session_id;\n    context.resumeSessionId = message.session_id;\n    yield* updateResumeCursor(context);\n\n    if (context.lastThreadStartedId !== nextThreadId) {\n      context.lastThreadStartedId = nextThreadId;\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"thread.started\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        payload: {\n          providerThreadId: nextThreadId,\n        },\n        providerRefs: {},\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/thread/started\",\n          payload: {\n            session_id: message.session_id,\n          },\n        },\n      });\n    }\n  });\n\n  const emitRuntimeError = Effect.fn(\"emitRuntimeError\")(function* (\n    context: ClaudeSessionContext,\n    message: string,\n    cause?: unknown,\n  ) {\n    if (cause !== undefined) {\n      void cause;\n    }\n    const turnState = context.turnState;\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"runtime.error\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),\n      payload: {\n        message,\n        class: \"provider_error\",\n        ...(cause !== undefined ? { detail: cause } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n    });\n  });\n\n  const emitRuntimeWarning = Effect.fn(\"emitRuntimeWarning\")(function* (\n    context: ClaudeSessionContext,\n    message: string,\n    detail?: unknown,\n  ) {\n    const turnState = context.turnState;\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"runtime.warning\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),\n      payload: {\n        message,\n        ...(detail !== undefined ? { detail } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n    });\n  });\n\n  const emitThreadTokenUsage = Effect.fn(\"emitThreadTokenUsage\")(function* (\n    context: ClaudeSessionContext,\n    usage: ThreadTokenUsageSnapshot | undefined,\n    options?: {\n      readonly rawMethod?: string;\n      readonly rawPayload?: unknown;\n    },\n  ) {\n    if (!usage) {\n      return;\n    }\n\n    context.lastKnownTokenUsage = usage;\n    context.lastKnownTotalProcessedTokens =\n      usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;\n\n    const turnState = context.turnState;\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"thread.token-usage.updated\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(turnState ? { turnId: turnState.turnId } : {}),\n      payload: {\n        usage,\n      },\n      providerRefs: nativeProviderRefs(context),\n      ...(options?.rawMethod || options?.rawPayload\n        ? {\n            raw: {\n              source: \"claude.sdk.message\" as const,\n              ...(options.rawMethod ? { method: options.rawMethod } : {}),\n              payload: options.rawPayload,\n            },\n          }\n        : {}),\n    });\n  });\n\n  const queryCurrentContextUsage = Effect.fn(\"queryCurrentContextUsage\")(function* (\n    context: ClaudeSessionContext,\n    totalProcessedTokens?: number,\n  ) {\n    if (!context.query.getContextUsage) {\n      return undefined;\n    }\n\n    const usage = yield* Effect.promise(async () => {\n      try {\n        return await context.query.getContextUsage?.();\n      } catch {\n        return undefined;\n      }\n    });\n    if (!usage) {\n      return undefined;\n    }\n\n    context.lastKnownContextWindow = usage.maxTokens;\n    return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens);\n  });\n\n  const emitProposedPlanCompleted = Effect.fn(\"emitProposedPlanCompleted\")(function* (\n    context: ClaudeSessionContext,\n    input: {\n      readonly planMarkdown: string;\n      readonly toolUseId?: string | undefined;\n      readonly rawSource: \"claude.sdk.message\" | \"claude.sdk.permission\";\n      readonly rawMethod: string;\n      readonly rawPayload: unknown;\n    },\n  ) {\n    const turnState = context.turnState;\n    const planMarkdown = input.planMarkdown.trim();\n    if (!turnState || planMarkdown.length === 0) {\n      return;\n    }\n\n    const captureKey = exitPlanCaptureKey({\n      toolUseId: input.toolUseId,\n      planMarkdown,\n    });\n    if (turnState.capturedProposedPlanKeys.has(captureKey)) {\n      return;\n    }\n    turnState.capturedProposedPlanKeys.add(captureKey);\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"turn.proposed.completed\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      turnId: turnState.turnId,\n      payload: {\n        planMarkdown,\n      },\n      providerRefs: nativeProviderRefs(context, {\n        providerItemId: input.toolUseId,\n      }),\n      raw: {\n        source: input.rawSource,\n        method: input.rawMethod,\n        payload: input.rawPayload,\n      },\n    });\n  });\n\n  const emitClaudeTaskPlanUpdated = Effect.fn(\"emitClaudeTaskPlanUpdated\")(function* (\n    context: ClaudeSessionContext,\n    input: {\n      readonly toolUseId: string;\n      readonly rawMethod: string;\n      readonly rawPayload: unknown;\n    },\n  ) {\n    const plan = planStepsFromClaudeTasks(context.claudeTasks);\n    if (plan.length === 0) {\n      return;\n    }\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"turn.plan.updated\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n      payload: {\n        explanation: \"Claude Tasks\",\n        plan,\n      },\n      providerRefs: nativeProviderRefs(context, {\n        providerItemId: input.toolUseId,\n      }),\n      raw: {\n        source: \"claude.sdk.message\",\n        method: input.rawMethod,\n        payload: input.rawPayload,\n      },\n    });\n  });\n\n  const completeTurn = Effect.fn(\"completeTurn\")(function* (\n    context: ClaudeSessionContext,\n    status: ProviderRuntimeTurnStatus,\n    errorMessage?: string,\n    result?: SDKResultMessage,\n  ) {\n    const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);\n    if (resultContextWindow !== undefined) {\n      context.lastKnownContextWindow = resultContextWindow;\n    }\n\n    const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;\n    const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage);\n    if (accumulatedTotalProcessedTokens !== undefined) {\n      context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens;\n    }\n\n    const contextUsageSnapshot = yield* queryCurrentContextUsage(\n      context,\n      accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,\n    );\n    const resultUsageRecord =\n      result?.usage && typeof result.usage === \"object\" && !Array.isArray(result.usage)\n        ? (result.usage as Record<string, unknown>)\n        : undefined;\n    const hasResultUsageIteration =\n      resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined;\n    const resultHasActiveUsage =\n      resultUsageRecord !== undefined &&\n      (hasResultUsageIteration ||\n        claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0);\n    const resultTotalOnly =\n      resultUsageRecord !== undefined &&\n      !resultHasActiveUsage &&\n      claudeTotalProcessedTokens(resultUsageRecord) !== undefined;\n    const resultIterationSnapshot = resultUsageRecord\n      ? normalizeClaudeActiveTokenUsage(\n          resultUsageRecord,\n          maxTokens,\n          accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,\n        )\n      : undefined;\n    const lastGoodUsage = context.lastKnownTokenUsage;\n    const usageSnapshot: ThreadTokenUsageSnapshot | undefined =\n      contextUsageSnapshot ??\n      (resultTotalOnly && lastGoodUsage\n        ? {\n            ...lastGoodUsage,\n            ...(typeof maxTokens === \"number\" && Number.isFinite(maxTokens) && maxTokens > 0\n              ? { maxTokens }\n              : {}),\n            ...(typeof accumulatedTotalProcessedTokens === \"number\" &&\n            Number.isFinite(accumulatedTotalProcessedTokens) &&\n            accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens\n              ? {\n                  totalProcessedTokens: accumulatedTotalProcessedTokens,\n                }\n              : {}),\n          }\n        : resultIterationSnapshot) ??\n      (lastGoodUsage\n        ? {\n            ...lastGoodUsage,\n            ...(typeof maxTokens === \"number\" && Number.isFinite(maxTokens) && maxTokens > 0\n              ? { maxTokens }\n              : {}),\n            ...(typeof accumulatedTotalProcessedTokens === \"number\" &&\n            Number.isFinite(accumulatedTotalProcessedTokens) &&\n            accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens\n              ? {\n                  totalProcessedTokens: accumulatedTotalProcessedTokens,\n                }\n              : {}),\n          }\n        : undefined);\n\n    const turnState = context.turnState;\n    if (!turnState) {\n      yield* emitThreadTokenUsage(context, usageSnapshot, {\n        rawMethod: \"claude/result\",\n        rawPayload: result ?? { status },\n      });\n\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"turn.completed\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        payload: {\n          state: status,\n          ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),\n          ...(result?.usage ? { usage: result.usage } : {}),\n          ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),\n          ...(typeof result?.total_cost_usd === \"number\"\n            ? { totalCostUsd: result.total_cost_usd }\n            : {}),\n          ...(errorMessage ? { errorMessage } : {}),\n        },\n        providerRefs: {},\n      });\n      return;\n    }\n\n    for (const [index, tool] of context.inFlightTools.entries()) {\n      const toolStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.completed\",\n        eventId: toolStamp.eventId,\n        provider: PROVIDER,\n        createdAt: toolStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId: turnState.turnId,\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: status === \"completed\" ? \"completed\" : \"failed\",\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          data: {\n            toolName: tool.toolName,\n            input: tool.input,\n          },\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/result\",\n          payload: result ?? { status },\n        },\n      });\n      context.inFlightTools.delete(index);\n    }\n    // Clear any remaining stale entries (e.g. from interrupted content blocks)\n    context.inFlightTools.clear();\n\n    for (const block of turnState.assistantTextBlockOrder) {\n      yield* completeAssistantTextBlock(context, block, {\n        force: true,\n        rawMethod: \"claude/result\",\n        rawPayload: result ?? { status },\n      });\n    }\n\n    context.turns.push({\n      id: turnState.turnId,\n      items: [...turnState.items],\n    });\n\n    yield* emitThreadTokenUsage(context, usageSnapshot, {\n      rawMethod: \"claude/result\",\n      rawPayload: result ?? { status },\n    });\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"turn.completed\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      turnId: turnState.turnId,\n      payload: {\n        state: status,\n        ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),\n        ...(result?.usage ? { usage: result.usage } : {}),\n        ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),\n        ...(typeof result?.total_cost_usd === \"number\"\n          ? { totalCostUsd: result.total_cost_usd }\n          : {}),\n        ...(errorMessage ? { errorMessage } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n    });\n\n    const updatedAt = yield* nowIso;\n    context.turnState = undefined;\n    context.session = {\n      ...context.session,\n      status: \"ready\",\n      activeTurnId: undefined,\n      updatedAt,\n      ...(status === \"failed\" && errorMessage ? { lastError: errorMessage } : {}),\n    };\n    yield* updateResumeCursor(context);\n  });\n\n  const handleStreamEvent = Effect.fn(\"handleStreamEvent\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"stream_event\") {\n      return;\n    }\n\n    const { event } = message;\n\n    // Subagent-owned stream traffic (parent_tool_use_id set) must not write\n    // into the parent transcript: with forwardSubagentText off the SDK still\n    // forwards subagent tool_use/tool_result blocks and their wrapping\n    // text/thinking deltas, and emitting them interleaved N subagents'\n    // narration into the chat (live-test finding). Their results reach the\n    // UI via the task.* lifecycle; their tool blocks are attributed and\n    // re-homed by the quiet-timeline filter.\n    const streamParentToolUseId = (message as { parent_tool_use_id?: string | null })\n      .parent_tool_use_id;\n    if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) {\n      // Drop only the subagent's narration (text/thinking); tool_use blocks\n      // and their input_json_delta frames must flow so attributed tool items\n      // keep their inputs (review finding: dropping deltas emptied inputs).\n      const dropStart =\n        event.type === \"content_block_start\" &&\n        event.content_block.type !== \"tool_use\" &&\n        event.content_block.type !== \"server_tool_use\" &&\n        event.content_block.type !== \"mcp_tool_use\";\n      const dropDelta =\n        event.type === \"content_block_delta\" &&\n        (event.delta.type === \"text_delta\" || event.delta.type === \"thinking_delta\");\n      if (dropStart || dropDelta) {\n        return;\n      }\n    }\n\n    if (event.type === \"message_delta\") {\n      if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {\n        return;\n      }\n\n      const snapshot = normalizeClaudeActiveTokenUsage(\n        event.usage,\n        context.lastKnownContextWindow,\n        context.lastKnownTotalProcessedTokens,\n      );\n      yield* emitThreadTokenUsage(context, snapshot, {\n        rawMethod: \"claude/stream_event/message_delta\",\n        rawPayload: message,\n      });\n      return;\n    }\n\n    if (event.type === \"content_block_delta\") {\n      if (\n        (event.delta.type === \"text_delta\" || event.delta.type === \"thinking_delta\") &&\n        context.turnState\n      ) {\n        const deltaText =\n          event.delta.type === \"text_delta\"\n            ? event.delta.text\n            : typeof event.delta.thinking === \"string\"\n              ? event.delta.thinking\n              : \"\";\n        if (deltaText.length === 0) {\n          return;\n        }\n        const streamKind = streamKindFromDeltaType(event.delta.type);\n        const assistantBlockEntry =\n          event.delta.type === \"text_delta\"\n            ? yield* ensureAssistantTextBlock(context, event.index)\n            : context.turnState.assistantTextBlocks.get(event.index)\n              ? {\n                  blockIndex: event.index,\n                  block: context.turnState.assistantTextBlocks.get(\n                    event.index,\n                  ) as AssistantTextBlockState,\n                }\n              : undefined;\n        if (assistantBlockEntry?.block && event.delta.type === \"text_delta\") {\n          assistantBlockEntry.block.emittedTextDelta = true;\n        }\n        const stamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"content.delta\",\n          eventId: stamp.eventId,\n          provider: PROVIDER,\n          createdAt: stamp.createdAt,\n          threadId: context.session.threadId,\n          turnId: context.turnState.turnId,\n          ...(assistantBlockEntry?.block\n            ? {\n                itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),\n              }\n            : {}),\n          payload: {\n            streamKind,\n            delta: deltaText,\n          },\n          providerRefs: nativeProviderRefs(context),\n          raw: {\n            source: \"claude.sdk.message\",\n            method: \"claude/stream_event/content_block_delta\",\n            payload: message,\n          },\n        });\n        return;\n      }\n\n      if (event.delta.type === \"input_json_delta\") {\n        const tool = context.inFlightTools.get(event.index);\n        if (!tool || typeof event.delta.partial_json !== \"string\") {\n          return;\n        }\n\n        const partialInputJson = tool.partialInputJson + event.delta.partial_json;\n        const parsedInput = tryParseJsonRecord(partialInputJson);\n        const detail = parsedInput ? summarizeToolRequest(tool.toolName, parsedInput) : tool.detail;\n        let nextTool: ToolInFlight = {\n          ...tool,\n          partialInputJson,\n          ...(parsedInput ? { input: parsedInput } : {}),\n          ...(detail ? { detail } : {}),\n        };\n\n        const nextFingerprint =\n          parsedInput && Object.keys(parsedInput).length > 0\n            ? toolInputFingerprint(parsedInput)\n            : undefined;\n        context.inFlightTools.set(event.index, nextTool);\n\n        if (\n          !parsedInput ||\n          !nextFingerprint ||\n          tool.lastEmittedInputFingerprint === nextFingerprint\n        ) {\n          return;\n        }\n\n        nextTool = {\n          ...nextTool,\n          lastEmittedInputFingerprint: nextFingerprint,\n        };\n        context.inFlightTools.set(event.index, nextTool);\n\n        const stamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"item.updated\",\n          eventId: stamp.eventId,\n          provider: PROVIDER,\n          createdAt: stamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          itemId: asRuntimeItemId(nextTool.itemId),\n          payload: {\n            itemType: nextTool.itemType,\n            status: \"inProgress\",\n            title: nextTool.title,\n            ...(nextTool.detail ? { detail: nextTool.detail } : {}),\n            ...(nextTool.agentId ? { agentId: nextTool.agentId } : {}),\n            ...(nextTool.parentToolUseId ? { parentToolUseId: nextTool.parentToolUseId } : {}),\n            data: {\n              toolName: nextTool.toolName,\n              input: nextTool.input,\n            },\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: nextTool.itemId,\n          }),\n          raw: {\n            source: \"claude.sdk.message\",\n            method: \"claude/stream_event/content_block_delta/input_json_delta\",\n            payload: message,\n          },\n        });\n\n        // Emit plan update when TodoWrite input is parsed\n        if (parsedInput && isTodoTool(nextTool.toolName)) {\n          const planSteps = extractPlanStepsFromTodoInput(parsedInput);\n          if (planSteps && planSteps.length > 0) {\n            const planStamp = yield* makeEventStamp();\n            yield* offerRuntimeEvent({\n              type: \"turn.plan.updated\",\n              eventId: planStamp.eventId,\n              provider: PROVIDER,\n              createdAt: planStamp.createdAt,\n              threadId: context.session.threadId,\n              ...(context.turnState\n                ? {\n                    turnId: asCanonicalTurnId(context.turnState.turnId),\n                  }\n                : {}),\n              payload: {\n                plan: planSteps,\n              },\n              providerRefs: nativeProviderRefs(context),\n            });\n          }\n        }\n      }\n      return;\n    }\n\n    if (event.type === \"content_block_start\") {\n      const { index, content_block: block } = event;\n      if (block.type === \"text\") {\n        yield* ensureAssistantTextBlock(context, index, {\n          fallbackText: extractContentBlockText(block),\n        });\n        return;\n      }\n      if (\n        block.type !== \"tool_use\" &&\n        block.type !== \"server_tool_use\" &&\n        block.type !== \"mcp_tool_use\"\n      ) {\n        return;\n      }\n\n      const toolName = block.name;\n      const itemType = classifyToolItemType(toolName);\n      const toolInput =\n        typeof block.input === \"object\" && block.input !== null\n          ? (block.input as Record<string, unknown>)\n          : {};\n      const itemId = block.id;\n      const detail = summarizeToolRequest(toolName, toolInput);\n      const inputFingerprint =\n        Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;\n\n      // Attribute tools that ran inside a subagent to their owning agent so\n      // clients can re-home them out of the main timeline (quiet-timeline\n      // guarantee): the SDK forwards subagent tool_use blocks tagged with the\n      // spawning Task tool's id as parent_tool_use_id.\n      const parentToolUseId =\n        (message as { parent_tool_use_id?: string | null }).parent_tool_use_id ?? undefined;\n      const owningAgentId = agentIdForParentToolUse(context.taskAgents, parentToolUseId);\n\n      const tool: ToolInFlight = {\n        itemId,\n        itemType,\n        toolName,\n        title: titleForTool(itemType),\n        detail,\n        input: toolInput,\n        partialInputJson: \"\",\n        ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),\n        ...(owningAgentId ? { agentId: owningAgentId } : {}),\n        ...(parentToolUseId ? { parentToolUseId } : {}),\n      };\n      context.inFlightTools.set(index, tool);\n\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.started\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: \"inProgress\",\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          ...(tool.agentId ? { agentId: tool.agentId } : {}),\n          ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),\n          data: {\n            toolName: tool.toolName,\n            input: toolInput,\n          },\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/stream_event/content_block_start\",\n          payload: message,\n        },\n      });\n      return;\n    }\n\n    if (event.type === \"content_block_stop\") {\n      const { index } = event;\n      const assistantBlock = context.turnState?.assistantTextBlocks.get(index);\n      if (assistantBlock) {\n        assistantBlock.streamClosed = true;\n        yield* completeAssistantTextBlock(context, assistantBlock, {\n          rawMethod: \"claude/stream_event/content_block_stop\",\n          rawPayload: message,\n        });\n        return;\n      }\n      const tool = context.inFlightTools.get(index);\n      if (!tool) {\n        return;\n      }\n    }\n  });\n\n  const handleUserMessage = Effect.fn(\"handleUserMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"user\") {\n      return;\n    }\n\n    if (context.turnState) {\n      context.turnState.items.push(message.message);\n    }\n\n    for (const toolResult of toolResultBlocksFromUserMessage(message)) {\n      const toolEntry = Array.from(context.inFlightTools.entries()).find(\n        ([, tool]) => tool.itemId === toolResult.toolUseId,\n      );\n      if (!toolEntry) {\n        continue;\n      }\n\n      const [index, tool] = toolEntry;\n      const itemStatus = toolResult.isError ? \"failed\" : \"completed\";\n      const toolUseResult = readClaudeToolUseResult(message);\n      const toolData = {\n        toolName: tool.toolName,\n        input: tool.input,\n        result: toolResult.block,\n      };\n\n      const updatedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.updated\",\n        eventId: updatedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: updatedStamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: toolResult.isError ? \"failed\" : \"inProgress\",\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          ...(tool.agentId ? { agentId: tool.agentId } : {}),\n          ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),\n          data: toolData,\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/user\",\n          payload: message,\n        },\n      });\n\n      const streamKind = toolResultStreamKind(tool.itemType);\n      if (streamKind && toolResult.text.length > 0 && context.turnState) {\n        const deltaStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"content.delta\",\n          eventId: deltaStamp.eventId,\n          provider: PROVIDER,\n          createdAt: deltaStamp.createdAt,\n          threadId: context.session.threadId,\n          turnId: context.turnState.turnId,\n          itemId: asRuntimeItemId(tool.itemId),\n          payload: {\n            streamKind,\n            delta: toolResult.text,\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: tool.itemId,\n          }),\n          raw: {\n            source: \"claude.sdk.message\",\n            method: \"claude/user\",\n            payload: message,\n          },\n        });\n      }\n\n      const completedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.completed\",\n        eventId: completedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: completedStamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: itemStatus,\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          ...(tool.agentId ? { agentId: tool.agentId } : {}),\n          ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),\n          data: toolData,\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/user\",\n          payload: message,\n        },\n      });\n\n      // The Workflow tool's result carries the run handles (runId, scriptPath,\n      // transcriptDir, sessionUrl). Attach them to the workflow's task agent so\n      // the next task.* payload advertises them to clients.\n      if (!toolResult.isError && tool.toolName.toLowerCase() === \"workflow\" && toolUseResult) {\n        const workflowTaskId = trimmedString(toolUseResult.taskId);\n        if (workflowTaskId) {\n          const runHandles: TaskRunHandles = {\n            ...(trimmedString(toolUseResult.runId)\n              ? { runId: trimmedString(toolUseResult.runId) }\n              : {}),\n            ...(trimmedString(toolUseResult.scriptPath)\n              ? { scriptPath: trimmedString(toolUseResult.scriptPath) }\n              : {}),\n            ...(trimmedString(toolUseResult.transcriptDir)\n              ? { transcriptDir: trimmedString(toolUseResult.transcriptDir) }\n              : {}),\n            ...(sanitizeSessionUrl(toolUseResult.sessionUrl)\n              ? { sessionUrl: sanitizeSessionUrl(toolUseResult.sessionUrl) }\n              : {}),\n          };\n          const existing = context.taskAgents.get(workflowTaskId);\n          context.taskAgents.set(workflowTaskId, {\n            taskId: workflowTaskId,\n            toolUseId: existing?.toolUseId ?? tool.itemId,\n            description: existing?.description,\n            subagentType: existing?.subagentType,\n            taskType: existing?.taskType ?? \"local_workflow\",\n            workflowName: existing?.workflowName,\n            skipTranscript: existing?.skipTranscript ?? false,\n            runHandles,\n            owningAgentId: existing?.owningAgentId,\n            model: existing?.model,\n            effort: existing?.effort,\n          });\n        }\n      }\n\n      if (\n        !toolResult.isError &&\n        applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)\n      ) {\n        yield* emitClaudeTaskPlanUpdated(context, {\n          toolUseId: tool.itemId,\n          rawMethod: \"claude/user\",\n          rawPayload: message,\n        });\n      }\n\n      context.inFlightTools.delete(index);\n    }\n  });\n\n  const handleAssistantMessage = Effect.fn(\"handleAssistantMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"assistant\") {\n      return;\n    }\n\n    // Subagent-owned assistant snapshots (parent_tool_use_id set) are the\n    // subagent's own conversation, not the parent's. Emitting them created\n    // interleaved \"Agent N done\"-adjacent leak messages and spawned synthetic\n    // turns per subagent completion (which also reset the Working timer).\n    const assistantParentToolUseId = (message as { parent_tool_use_id?: string | null })\n      .parent_tool_use_id;\n    if (assistantParentToolUseId !== null && assistantParentToolUseId !== undefined) {\n      // The snapshot's message.model is the authoritative API model the\n      // subagent actually ran on — refine the seeded launch-time value.\n      const owningTaskId = agentIdForParentToolUse(context.taskAgents, assistantParentToolUseId);\n      const snapshotModel = trimmedString(message.message.model);\n      const owningAgent = owningTaskId ? context.taskAgents.get(owningTaskId) : undefined;\n      if (owningAgent && snapshotModel) {\n        owningAgent.model = snapshotModel;\n      }\n      context.lastAssistantUuid = message.uuid;\n      yield* updateResumeCursor(context);\n      return;\n    }\n\n    // Auto-start a synthetic turn for assistant messages that arrive without\n    // an active turn (e.g., background agent/subagent responses between user prompts).\n    if (!context.turnState) {\n      const turnId = TurnId.make(yield* randomUUIDv4);\n      const startedAt = yield* nowIso;\n      context.turnState = {\n        turnId,\n        startedAt,\n        synthetic: true,\n        items: [],\n        assistantTextBlocks: new Map(),\n        assistantTextBlockOrder: [],\n        capturedProposedPlanKeys: new Set(),\n        nextSyntheticAssistantBlockIndex: -1,\n      };\n      context.session = {\n        ...context.session,\n        status: \"running\",\n        activeTurnId: turnId,\n        updatedAt: startedAt,\n      };\n      const turnStartedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"turn.started\",\n        eventId: turnStartedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: turnStartedStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId,\n        payload: {},\n        providerRefs: {\n          ...nativeProviderRefs(context),\n          providerTurnId: turnId,\n        },\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/synthetic-turn-start\",\n          payload: {},\n        },\n      });\n    }\n\n    const content = message.message?.content;\n    if (Array.isArray(content)) {\n      for (const block of content) {\n        if (!block || typeof block !== \"object\") {\n          continue;\n        }\n        const toolUse = block as {\n          type?: unknown;\n          id?: unknown;\n          name?: unknown;\n          input?: unknown;\n        };\n        if (toolUse.type !== \"tool_use\" || toolUse.name !== \"ExitPlanMode\") {\n          continue;\n        }\n        const planMarkdown = extractExitPlanModePlan(toolUse.input);\n        if (!planMarkdown) {\n          continue;\n        }\n        yield* emitProposedPlanCompleted(context, {\n          planMarkdown,\n          toolUseId: typeof toolUse.id === \"string\" ? toolUse.id : undefined,\n          rawSource: \"claude.sdk.message\",\n          rawMethod: \"claude/assistant\",\n          rawPayload: message,\n        });\n      }\n    }\n\n    if (context.turnState) {\n      context.turnState.items.push(message.message);\n      yield* backfillAssistantTextBlocksFromSnapshot(context, message);\n    }\n\n    context.lastAssistantUuid = message.uuid;\n    yield* updateResumeCursor(context);\n  });\n\n  const handleResultMessage = Effect.fn(\"handleResultMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"result\") {\n      return;\n    }\n\n    const status = turnStatusFromResult(message);\n    const errorMessage = message.subtype === \"success\" ? undefined : message.errors[0];\n\n    if (status === \"failed\") {\n      yield* emitRuntimeError(context, errorMessage ?? \"Claude turn failed.\");\n    }\n\n    yield* completeTurn(context, status, errorMessage, message);\n  });\n\n  /**\n   * Synthesizes per-member task.progress rows from the coordinator's\n   * workflow_progress array. Member identity is the stable slot\n   * `<coordinatorTaskId>:wf:<index>` (never the per-attempt agent id, which\n   * changes on retry and would split one member into duplicate rows).\n   * timelineBypass keeps these out of the parent chat; the Agents surface and\n   * workflow card consume them.\n   */\n  const emitWorkflowMemberProgress = Effect.fn(\"emitWorkflowMemberProgress\")(function* (\n    context: ClaudeSessionContext,\n    base: Omit<ProviderRuntimeEvent, \"type\" | \"payload\">,\n    message: Extract<SDKMessage, { type: \"system\"; subtype: \"task_progress\" }>,\n  ) {\n    const progress = parseWorkflowProgress(\n      (message as unknown as Record<string, unknown>).workflow_progress,\n    );\n    if (!progress) {\n      return;\n    }\n    const coordinatorId = message.task_id;\n    for (const entry of progress.agents) {\n      const memberTaskId = `${coordinatorId}:wf:${entry.index}`;\n      const status = workflowAgentStatus(entry);\n      // Material-transition filter: the wire repeats every member each tick.\n      // Emit only when something the client renders actually changed, so a\n      // 100-agent fleet costs ~1 event per changed member instead of 100\n      // per tick (review finding: unbounded event amplification).\n      const fingerprint = [\n        status,\n        entry.label ?? \"\",\n        entry.model ?? \"\",\n        entry.lastToolName ?? \"\",\n        entry.error ?? \"\",\n        entry.tokens ?? \"\",\n        entry.toolCalls ?? \"\",\n        entry.phaseIndex ?? \"\",\n        entry.phaseTitle ?? \"\",\n        entry.attempt ?? \"\",\n      ].join(\"\\u001f\");\n      if (context.workflowMemberFingerprints.get(memberTaskId) === fingerprint) {\n        continue;\n      }\n      context.workflowMemberFingerprints.set(memberTaskId, fingerprint);\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        ...base,\n        eventId: stamp.eventId,\n        createdAt: stamp.createdAt,\n        type: \"task.progress\",\n        payload: {\n          taskId: RuntimeTaskId.make(memberTaskId),\n          description: entry.label ?? `agent ${entry.index}`,\n          status,\n          ...(entry.error ? { error: entry.error } : {}),\n          ...(entry.label ? { title: entry.label } : {}),\n          ...(entry.model ? { model: entry.model } : {}),\n          ...(entry.lastToolName ? { lastToolName: entry.lastToolName } : {}),\n          ...(entry.tokens !== undefined\n            ? {\n                typedUsage: {\n                  totalTokens: entry.tokens,\n                  ...(entry.toolCalls !== undefined ? { toolUses: entry.toolCalls } : {}),\n                },\n              }\n            : {}),\n          parentAgentId: coordinatorId,\n          agentIndex: entry.index,\n          ...(entry.phaseIndex !== undefined ? { phaseIndex: entry.phaseIndex } : {}),\n          ...(entry.phaseTitle ? { phaseTitle: entry.phaseTitle } : {}),\n          ...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),\n          timelineBypass: true,\n        },\n      });\n    }\n  });\n\n  const handleSystemMessage = Effect.fn(\"handleSystemMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"system\") {\n      return;\n    }\n\n    const stamp = yield* makeEventStamp();\n    const base = {\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n      providerRefs: nativeProviderRefs(context),\n      raw: {\n        source: \"claude.sdk.message\" as const,\n        method: sdkNativeMethod(message),\n        messageType: `${message.type}:${message.subtype}`,\n        payload: message,\n      },\n    };\n\n    // Undeclared-but-real subtypes (absent from the SDK's union, so they can't\n    // be switch cases): consumed intentionally without emitting, otherwise\n    // they fall through to the unknown-subtype warning and surface as spurious\n    // error rows in client work logs. `background_tasks_changed` is a roster\n    // snapshot ({tasks: [...]}) — the task_* lifecycle events carry the\n    // authoritative per-agent data and the typed background_tasks control\n    // request is the reconciliation source.\n    if ((message.subtype as string) === \"background_tasks_changed\") {\n      return;\n    }\n\n    switch (message.subtype) {\n      case \"init\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.configured\",\n          payload: {\n            config: message as Record<string, unknown>,\n          },\n        });\n        return;\n      case \"status\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.state.changed\",\n          payload: {\n            state: message.status === \"compacting\" ? \"waiting\" : \"running\",\n            reason: `status:${message.status ?? \"active\"}`,\n            detail: message,\n          },\n        });\n        return;\n      case \"compact_boundary\":\n        yield* emitThreadTokenUsage(\n          context,\n          compactBoundaryTokenUsageSnapshot(\n            message as unknown as Record<string, unknown>,\n            context.lastKnownContextWindow,\n            context.lastKnownTotalProcessedTokens,\n          ),\n          {\n            rawMethod: \"claude/system/compact_boundary\",\n            rawPayload: message,\n          },\n        );\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"thread.state.changed\",\n          payload: {\n            state: \"compacted\",\n            detail: message,\n          },\n        });\n        return;\n      case \"hook_started\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"hook.started\",\n          payload: {\n            hookId: message.hook_id,\n            hookName: message.hook_name,\n            hookEvent: message.hook_event,\n          },\n        });\n        return;\n      case \"hook_progress\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"hook.progress\",\n          payload: {\n            hookId: message.hook_id,\n            output: message.output,\n            stdout: message.stdout,\n            stderr: message.stderr,\n          },\n        });\n        return;\n      case \"hook_response\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"hook.completed\",\n          payload: {\n            hookId: message.hook_id,\n            outcome: message.outcome,\n            output: message.output,\n            stdout: message.stdout,\n            stderr: message.stderr,\n            ...(typeof message.exit_code === \"number\" ? { exitCode: message.exit_code } : {}),\n          },\n        });\n        return;\n      case \"task_started\": {\n        // A task launched by a tool that itself ran inside a subagent (the\n        // in-flight tool carries agentId from parent_tool_use_id) is\n        // agent-internal: a subagent's background shell, not parent work.\n        const launchingTool = message.tool_use_id\n          ? Array.from(context.inFlightTools.values()).find(\n              (tool) => tool.itemId === message.tool_use_id,\n            )\n          : undefined;\n        const owningAgentId = launchingTool?.agentId;\n        // Model/effort: the Agent tool's input carries explicit overrides;\n        // absent ones inherit the session's selection (SDK behavior).\n        // Subagent assistant snapshots later refine model with the\n        // authoritative API id. AgentInput.effort may be a named level or an\n        // integer.\n        const launchInput = launchingTool?.input;\n        const model =\n          trimmedString(launchInput?.model) ?? trimmedString(context.session.model ?? undefined);\n        const rawLaunchEffort = launchInput?.effort;\n        const effort =\n          trimmedString(rawLaunchEffort) ??\n          (typeof rawLaunchEffort === \"number\" && Number.isFinite(rawLaunchEffort)\n            ? String(rawLaunchEffort)\n            : context.currentEffort);\n        // Remember the agent identity so every later task.* payload for this\n        // taskId is self-describing (identity must survive activity retention).\n        context.taskAgents.set(message.task_id, {\n          taskId: message.task_id,\n          toolUseId: message.tool_use_id,\n          description: message.description,\n          subagentType: message.subagent_type,\n          taskType: message.task_type,\n          workflowName: message.workflow_name,\n          skipTranscript: message.skip_transcript === true,\n          runHandles: context.taskAgents.get(message.task_id)?.runHandles,\n          owningAgentId,\n          model,\n          effort,\n        });\n        context.liveTaskIds.add(message.task_id);\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.started\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            description: message.description,\n            ...(message.task_type ? { taskType: message.task_type } : {}),\n            ...(owningAgentId ? { agentId: owningAgentId } : {}),\n            ...(message.description ? { title: message.description } : {}),\n            ...(message.subagent_type ? { role: message.subagent_type } : {}),\n            ...(model ? { model } : {}),\n            ...(effort ? { effort } : {}),\n            ...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),\n            ...(message.workflow_name ? { workflowName: message.workflow_name } : {}),\n          },\n        });\n        return;\n      }\n      case \"task_progress\": {\n        yield* emitThreadTokenUsage(\n          context,\n          normalizeClaudeTaskProgressTokenUsage(message.usage, context),\n          {\n            rawMethod: \"claude/system/task_progress\",\n            rawPayload: message,\n          },\n        );\n        const linkage = taskLinkageFor(context.taskAgents, message.task_id);\n        const typedUsage = normalizeTaskUsage(message.usage);\n        // Phases ride on the coordinator's ONE progress row per tick. A\n        // separate phases-only row shared the stable ingestion activity id\n        // with this full row, and the thinner upsert overwrote usage and\n        // progress text (review finding).\n        const workflowPhases = parseWorkflowProgress(\n          (message as unknown as Record<string, unknown>).workflow_progress,\n        )?.phases;\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.progress\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            description: message.description,\n            ...(message.summary ? { summary: message.summary } : {}),\n            ...(message.usage ? { usage: message.usage } : {}),\n            ...(typedUsage ? { typedUsage } : {}),\n            ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),\n            ...(workflowPhases && workflowPhases.length > 0 ? { phases: workflowPhases } : {}),\n            ...linkage,\n            ...(message.subagent_type ? { role: message.subagent_type } : {}),\n          },\n        });\n        yield* emitWorkflowMemberProgress(context, base, message);\n        return;\n      }\n      case \"task_updated\": {\n        // Status patch (killed/paused/backgrounded/end_time/error) — main\n        // previously dropped this on the floor, losing all transitions.\n        const patch = message.patch;\n        const status =\n          patch.status !== undefined ? CLAUDE_TASK_PATCH_STATUS[patch.status] : undefined;\n        if (status === \"completed\" || status === \"failed\" || status === \"cancelled\") {\n          context.liveTaskIds.delete(message.task_id);\n        }\n        const endedAt =\n          typeof patch.end_time === \"number\" && Number.isFinite(patch.end_time)\n            ? DateTime.formatIso(DateTime.makeUnsafe(patch.end_time))\n            : undefined;\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.updated\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            ...(status ? { status } : {}),\n            ...(patch.description ? { description: patch.description } : {}),\n            ...(patch.error ? { error: patch.error } : {}),\n            ...(endedAt ? { endedAt } : {}),\n            ...(patch.is_backgrounded !== undefined\n              ? { isBackgrounded: patch.is_backgrounded }\n              : {}),\n            ...taskLinkageFor(context.taskAgents, message.task_id),\n          },\n        });\n        return;\n      }\n      case \"task_notification\": {\n        context.liveTaskIds.delete(message.task_id);\n        yield* emitThreadTokenUsage(\n          context,\n          normalizeClaudeTaskProgressTokenUsage(message.usage, context),\n          {\n            rawMethod: \"claude/system/task_notification\",\n            rawPayload: message,\n          },\n        );\n        const typedUsage = normalizeTaskUsage(message.usage);\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.completed\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            status: message.status,\n            ...(message.summary ? { summary: message.summary } : {}),\n            ...(message.usage ? { usage: message.usage } : {}),\n            ...(typedUsage ? { typedUsage } : {}),\n            ...(message.output_file ? { outputFile: message.output_file } : {}),\n            ...taskLinkageFor(context.taskAgents, message.task_id),\n          },\n        });\n        return;\n      }\n      case \"files_persisted\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"files.persisted\",\n          payload: {\n            files: Array.isArray(message.files)\n              ? message.files.map((file: { filename: string; file_id: string }) => ({\n                  filename: file.filename,\n                  fileId: file.file_id,\n                }))\n              : [],\n            ...(Array.isArray(message.failed)\n              ? {\n                  failed: message.failed.map((entry: { filename: string; error: string }) => ({\n                    filename: entry.filename,\n                    error: entry.error,\n                  })),\n                }\n              : {}),\n          },\n        });\n        return;\n      case \"thinking_tokens\":\n        return;\n      case \"api_retry\":\n        // Transport-level retry heartbeat. Surfacing each attempt as a\n        // warning row spammed the work log (10 rows during a 502 storm);\n        // the terminal result/error path reports the actual failure. Keep\n        // the session visibly alive instead.\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.state.changed\",\n          payload: {\n            state: \"running\",\n            reason: `api_retry:${message.attempt}/${message.max_retries}`,\n          },\n        });\n        return;\n      case \"session_state_changed\":\n        // Authoritative turn-over signal from the CLI.\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.state.changed\",\n          payload: {\n            state:\n              message.state === \"running\"\n                ? \"running\"\n                : message.state === \"requires_action\"\n                  ? \"waiting\"\n                  : \"ready\",\n            reason: `session_state:${message.state}`,\n          },\n        });\n        return;\n      case \"notification\":\n        // User-facing CLI notification (e.g. context-limit warnings). Only\n        // high-priority ones warrant a work-log row.\n        if (message.priority === \"high\" || message.priority === \"immediate\") {\n          yield* emitRuntimeWarning(context, message.text, message);\n        }\n        return;\n      // Inner protocol/UX details with no T3 surface today — consumed\n      // deliberately so they don't masquerade as unknown-subtype warnings.\n      case \"model_refusal_fallback\":\n      case \"local_command_output\":\n      case \"plugin_install\":\n      case \"commands_changed\":\n      case \"memory_recall\":\n      case \"elicitation_complete\":\n        return;\n      case \"permission_denied\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"tool.denied\",\n          payload: {\n            toolName: message.tool_name,\n            ...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),\n            ...(message.decision_reason ? { reason: message.decision_reason } : {}),\n            ...(message.agent_id ? { agentId: message.agent_id } : {}),\n          },\n        });\n        return;\n      case \"mirror_error\":\n        yield* emitRuntimeError(\n          context,\n          `Claude workspace mirror error: ${message.error}`,\n          message,\n        );\n        return;\n      default: {\n        // Exhaustiveness guard: every subtype in the SDK's typed union is\n        // handled above, so `message` narrows to never here — a new SDK\n        // release adding a subtype fails this typecheck instead of silently\n        // warning at runtime. The runtime fallback still catches undeclared\n        // wire-only subtypes (like background_tasks_changed used to be).\n        message satisfies never;\n        const unknownMessage = message as never as { subtype: string };\n        yield* emitRuntimeWarning(\n          context,\n          describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),\n          message,\n        );\n        return;\n      }\n    }\n  });\n\n  const handleSdkTelemetryMessage = Effect.fn(\"handleSdkTelemetryMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    const stamp = yield* makeEventStamp();\n    const base = {\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n      providerRefs: nativeProviderRefs(context),\n      raw: {\n        source: \"claude.sdk.message\" as const,\n        method: sdkNativeMethod(message),\n        messageType: message.type,\n        payload: message,\n      },\n    };\n\n    if (message.type === \"tool_progress\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"tool.progress\",\n        payload: {\n          toolUseId: message.tool_use_id,\n          toolName: message.tool_name,\n          elapsedSeconds: message.elapsed_time_seconds,\n          ...(message.task_id ? { taskId: RuntimeTaskId.make(message.task_id) } : {}),\n          ...(message.parent_tool_use_id !== null\n            ? { parentToolUseId: message.parent_tool_use_id }\n            : {}),\n        },\n      });\n      return;\n    }\n\n    if (message.type === \"tool_use_summary\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"tool.summary\",\n        payload: {\n          summary: message.summary,\n          ...(message.preceding_tool_use_ids.length > 0\n            ? {\n                precedingToolUseIds: message.preceding_tool_use_ids,\n              }\n            : {}),\n        },\n      });\n      return;\n    }\n\n    if (message.type === \"auth_status\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"auth.status\",\n        payload: {\n          isAuthenticating: message.isAuthenticating,\n          output: message.output,\n          ...(message.error ? { error: message.error } : {}),\n        },\n      });\n      return;\n    }\n\n    if (message.type === \"rate_limit_event\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"account.rate-limits.updated\",\n        payload: {\n          rateLimits: message,\n        },\n      });\n      return;\n    }\n  });\n\n  const handleSdkMessage = Effect.fn(\"handleSdkMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    yield* logNativeSdkMessage(context, message);\n    yield* ensureThreadId(context, message);\n\n    switch (message.type) {\n      case \"stream_event\":\n        yield* handleStreamEvent(context, message);\n        return;\n      case \"user\":\n        yield* handleUserMessage(context, message);\n        return;\n      case \"assistant\":\n        yield* handleAssistantMessage(context, message);\n        return;\n      case \"result\":\n        yield* handleResultMessage(context, message);\n        return;\n      case \"system\":\n        yield* handleSystemMessage(context, message);\n        return;\n      case \"tool_progress\":\n      case \"tool_use_summary\":\n      case \"auth_status\":\n      case \"rate_limit_event\":\n        yield* handleSdkTelemetryMessage(context, message);\n        return;\n      // Composer prompt suggestions have no T3 surface; consumed deliberately.\n      case \"prompt_suggestion\":\n        return;\n      default: {\n        // Exhaustiveness guard (see handleSystemMessage): new SDK top-level\n        // message types fail typecheck here instead of warning at runtime.\n        message satisfies never;\n        const unknownMessage = message as never as { type: string };\n        yield* emitRuntimeWarning(\n          context,\n          describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),\n          message,\n        );\n        return;\n      }\n    }\n  });\n\n  const runSdkStream = (\n    context: ClaudeSessionContext,\n  ): Effect.Effect<void, ProviderAdapterProcessError> =>\n    Stream.fromAsyncIterable(\n      context.query,\n      (cause) =>\n        new ProviderAdapterProcessError({\n          provider: PROVIDER,\n          threadId: context.session.threadId,\n          detail: \"Claude runtime stream failed.\",\n          cause,\n        }),\n    ).pipe(\n      Stream.takeWhile(() => !context.stopped),\n      Stream.runForEach((message) =>\n        handleSdkMessage(context, message).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderAdapterProcessError({\n                provider: PROVIDER,\n                threadId: context.session.threadId,\n                detail: \"Failed to process Claude runtime event.\",\n                cause,\n              }),\n          ),\n        ),\n      ),\n    );\n\n  const handleStreamExit = Effect.fn(\"handleStreamExit\")(function* (\n    context: ClaudeSessionContext,\n    exit: Exit.Exit<void, ProviderAdapterProcessError>,\n  ) {\n    if (context.stopped) {\n      return;\n    }\n\n    if (Exit.isFailure(exit)) {\n      if (isClaudeInterruptedCause(exit.cause)) {\n        if (context.turnState) {\n          yield* completeTurn(context, \"interrupted\", \"Claude runtime interrupted.\");\n        }\n      } else {\n        const failures = exit.cause.reasons.flatMap((reason) =>\n          Cause.isFailReason(reason) ? [reason.error] : [],\n        );\n        const message = failures[0]?.detail ?? \"Claude runtime stream failed.\";\n        yield* emitRuntimeError(context, message, {\n          failureCount: failures.length,\n          failureTags: failures.map((failure) => failure._tag),\n        });\n        yield* completeTurn(context, \"failed\", message);\n      }\n    } else if (context.turnState) {\n      yield* completeTurn(context, \"interrupted\", \"Claude runtime stream ended.\");\n    }\n\n    yield* stopSessionInternal(context, {\n      emitExitEvent: true,\n    });\n  });\n\n  const stopSessionInternal = Effect.fn(\"stopSessionInternal\")(function* (\n    context: ClaudeSessionContext,\n    options?: { readonly emitExitEvent?: boolean },\n  ) {\n    if (context.stopped) return;\n\n    context.stopped = true;\n\n    for (const [requestId, pending] of context.pendingApprovals) {\n      yield* Deferred.succeed(pending.decision, \"cancel\");\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"request.resolved\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        requestId: asRuntimeRequestId(requestId),\n        payload: {\n          requestType: pending.requestType,\n          decision: \"cancel\",\n        },\n        providerRefs: nativeProviderRefs(context),\n      });\n    }\n    context.pendingApprovals.clear();\n\n    if (context.turnState) {\n      yield* completeTurn(context, \"interrupted\", \"Session stopped.\");\n    }\n\n    yield* Queue.shutdown(context.promptQueue);\n\n    const streamFiber = context.streamFiber;\n    context.streamFiber = undefined;\n    if (streamFiber && streamFiber.pollUnsafe() === undefined) {\n      yield* Fiber.interrupt(streamFiber);\n    }\n\n    yield* Effect.try({\n      try: () => context.query.close(),\n      catch: (cause) =>\n        new ProviderAdapterProcessError({\n          provider: PROVIDER,\n          threadId: context.session.threadId,\n          detail: \"Failed to close Claude runtime query.\",\n          cause,\n        }),\n    }).pipe(\n      Effect.catch((error) =>\n        emitRuntimeError(context, \"Failed to close Claude runtime query.\", {\n          errorTag: error._tag,\n          provider: error.provider,\n          threadId: error.threadId,\n          detail: error.detail,\n        }),\n      ),\n    );\n\n    const updatedAt = yield* nowIso;\n    context.session = {\n      ...context.session,\n      status: \"closed\",\n      activeTurnId: undefined,\n      updatedAt,\n    };\n\n    if (options?.emitExitEvent !== false) {\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.exited\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        payload: {\n          reason: \"Session stopped\",\n          exitKind: \"graceful\",\n        },\n        providerRefs: {},\n      });\n    }\n\n    sessions.delete(context.session.threadId);\n  });\n\n  const requireSession = (\n    threadId: ThreadId,\n  ): Effect.Effect<ClaudeSessionContext, ProviderAdapterError> => {\n    const context = sessions.get(threadId);\n    if (!context) {\n      return Effect.fail(\n        new ProviderAdapterSessionNotFoundError({\n          provider: PROVIDER,\n          threadId,\n        }),\n      );\n    }\n    if (context.stopped || context.session.status === \"closed\") {\n      return Effect.fail(\n        new ProviderAdapterSessionClosedError({\n          provider: PROVIDER,\n          threadId,\n        }),\n      );\n    }\n    return Effect.succeed(context);\n  };\n\n  const startSession: ClaudeAdapterShape[\"startSession\"] = Effect.fn(\"startSession\")(\n    function* (input) {\n      if (input.provider !== undefined && input.provider !== PROVIDER) {\n        return yield* new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"startSession\",\n          issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n        });\n      }\n\n      const existingContext = sessions.get(input.threadId);\n      if (existingContext) {\n        yield* Effect.logWarning(\"claude.session.replacing\", {\n          threadId: input.threadId,\n          existingSessionStatus: existingContext.session.status,\n          reason: \"startSession called with existing active session\",\n        });\n        yield* stopSessionInternal(existingContext, {\n          emitExitEvent: false,\n        }).pipe(\n          // Replacement cleanup is best-effort: never block the new session on\n          // either typed failures or unexpected defects from tearing down the old one.\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"claude.session.replace.stop-failed\", {\n              threadId: input.threadId,\n              cause,\n            }),\n          ),\n        );\n      }\n\n      const startedAt = yield* nowIso;\n      const resumeState = readClaudeResumeState(input.resumeCursor);\n      const threadId = input.threadId;\n      const existingResumeSessionId = resumeState?.resume;\n      const newSessionId = existingResumeSessionId === undefined ? yield* randomUUIDv4 : undefined;\n      const sessionId = existingResumeSessionId ?? newSessionId;\n\n      const runtimeContext = yield* Effect.context<never>();\n      const runFork = Effect.runForkWith(runtimeContext);\n      const runPromise = Effect.runPromiseWith(runtimeContext);\n\n      const promptQueue = yield* Queue.unbounded<PromptQueueItem>();\n      const prompt = Stream.fromQueue(promptQueue).pipe(\n        Stream.filter((item) => item.type === \"message\"),\n        Stream.map((item) => item.message),\n        Stream.catchCause((cause) =>\n          Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),\n        ),\n        Stream.toAsyncIterable,\n      );\n\n      const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();\n      const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();\n      const inFlightTools = new Map<number, ToolInFlight>();\n      const claudeTasks = new Map<string, ClaudeTaskState>();\n      const taskAgents = new Map<string, ClaudeTaskAgentState>();\n      const workflowMemberFingerprints = new Map<string, string>();\n      const liveTaskIds = new Set<string>();\n\n      const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);\n\n      /**\n       * Handle AskUserQuestion tool calls by emitting a `user-input.requested`\n       * runtime event and waiting for the user to respond via `respondToUserInput`.\n       */\n      const handleAskUserQuestion = Effect.fn(\"handleAskUserQuestion\")(function* (\n        context: ClaudeSessionContext,\n        toolInput: Record<string, unknown>,\n        callbackOptions: {\n          readonly signal: AbortSignal;\n          readonly toolUseID?: string;\n        },\n      ) {\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n\n        // Parse questions from the SDK's AskUserQuestion input.\n        // `id` MUST equal the full question text — Claude SDK >= 2.1.121 looks\n        // up answers by question text in `mapToolResultToToolResultBlockParam`,\n        // so the key the UI uses to keep its draft answer must match the SDK's\n        // expected lookup key. See https://github.com/pingdotgg/t3code/issues/2388\n        const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : [];\n        const questions: Array<UserInputQuestion> = rawQuestions.map(\n          (q: Record<string, unknown>, idx: number) => ({\n            id: typeof q.question === \"string\" && q.question.length > 0 ? q.question : `q-${idx}`,\n            header: typeof q.header === \"string\" ? q.header : `Question ${idx + 1}`,\n            question: typeof q.question === \"string\" ? q.question : \"\",\n            options: Array.isArray(q.options)\n              ? q.options.map((opt: Record<string, unknown>) => ({\n                  label: typeof opt.label === \"string\" ? opt.label : \"\",\n                  description: typeof opt.description === \"string\" ? opt.description : \"\",\n                }))\n              : [],\n            multiSelect: typeof q.multiSelect === \"boolean\" ? q.multiSelect : false,\n          }),\n        );\n\n        const answersDeferred = yield* Deferred.make<ProviderUserInputAnswers>();\n        let aborted = false;\n        const pendingInput: PendingUserInput = {\n          questions,\n          answers: answersDeferred,\n        };\n\n        // Emit user-input.requested so the UI can present the questions.\n        const requestedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"user-input.requested\",\n          eventId: requestedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: requestedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: { questions },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/AskUserQuestion\",\n            payload: {\n              toolName: \"AskUserQuestion\",\n              input: toolInput,\n            },\n          },\n        });\n\n        pendingUserInputs.set(requestId, pendingInput);\n\n        // Handle abort (e.g. turn interrupted while waiting for user input).\n        const onAbort = () => {\n          if (!pendingUserInputs.has(requestId)) {\n            return;\n          }\n          aborted = true;\n          pendingUserInputs.delete(requestId);\n          runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));\n        };\n        callbackOptions.signal.addEventListener(\"abort\", onAbort, {\n          once: true,\n        });\n\n        // Block until the user provides answers.\n        const answers = yield* Deferred.await(answersDeferred);\n        pendingUserInputs.delete(requestId);\n\n        // Emit user-input.resolved so the UI knows the interaction completed.\n        const resolvedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"user-input.resolved\",\n          eventId: resolvedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: resolvedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: { answers },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/AskUserQuestion/resolved\",\n            payload: { answers },\n          },\n        });\n\n        if (aborted) {\n          return {\n            behavior: \"deny\",\n            message: \"User cancelled tool execution.\",\n          } satisfies PermissionResult;\n        }\n\n        // Return the answers to the SDK in the expected format:\n        // { questions: [...], answers: { questionText: selectedLabel } }\n        return {\n          behavior: \"allow\",\n          updatedInput: {\n            questions: toolInput.questions,\n            answers,\n          },\n        } satisfies PermissionResult;\n      });\n\n      const canUseToolEffect = Effect.fn(\"canUseTool\")(function* (\n        toolName: Parameters<CanUseTool>[0],\n        toolInput: Parameters<CanUseTool>[1],\n        callbackOptions: Parameters<CanUseTool>[2],\n      ) {\n        const context = yield* Ref.get(contextRef);\n        if (!context) {\n          return {\n            behavior: \"deny\",\n            message: \"Claude session context is unavailable.\",\n          } satisfies PermissionResult;\n        }\n\n        // Handle AskUserQuestion: surface clarifying questions to the\n        // user via the user-input runtime event channel, regardless of\n        // runtime mode (plan mode relies on this heavily).\n        if (toolName === \"AskUserQuestion\") {\n          return yield* handleAskUserQuestion(context, toolInput, callbackOptions);\n        }\n\n        if (toolName === \"ExitPlanMode\") {\n          const planMarkdown = extractExitPlanModePlan(toolInput);\n          if (planMarkdown) {\n            yield* emitProposedPlanCompleted(context, {\n              planMarkdown,\n              toolUseId: callbackOptions.toolUseID,\n              rawSource: \"claude.sdk.permission\",\n              rawMethod: \"canUseTool/ExitPlanMode\",\n              rawPayload: {\n                toolName,\n                input: toolInput,\n              },\n            });\n          }\n\n          return {\n            behavior: \"deny\",\n            message:\n              \"The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.\",\n          } satisfies PermissionResult;\n        }\n\n        const runtimeMode = input.runtimeMode ?? \"full-access\";\n        if (runtimeMode === \"full-access\") {\n          return {\n            behavior: \"allow\",\n            updatedInput: toolInput,\n          } satisfies PermissionResult;\n        }\n\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n        const requestType = classifyRequestType(toolName);\n        const detail = summarizeToolRequest(toolName, toolInput);\n        const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();\n        const pendingApproval: PendingApproval = {\n          requestType,\n          detail,\n          decision: decisionDeferred,\n          ...(callbackOptions.suggestions ? { suggestions: callbackOptions.suggestions } : {}),\n        };\n\n        const requestedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"request.opened\",\n          eventId: requestedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: requestedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: {\n            requestType,\n            detail,\n            args: {\n              toolName,\n              input: toolInput,\n              ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}),\n            },\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/request\",\n            payload: {\n              toolName,\n              input: toolInput,\n            },\n          },\n        });\n\n        pendingApprovals.set(requestId, pendingApproval);\n\n        const onAbort = () => {\n          if (!pendingApprovals.has(requestId)) {\n            return;\n          }\n          pendingApprovals.delete(requestId);\n          runFork(Deferred.succeed(decisionDeferred, \"cancel\"));\n        };\n\n        callbackOptions.signal.addEventListener(\"abort\", onAbort, {\n          once: true,\n        });\n\n        const decision = yield* Deferred.await(decisionDeferred);\n        pendingApprovals.delete(requestId);\n\n        const resolvedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"request.resolved\",\n          eventId: resolvedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: resolvedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: {\n            requestType,\n            decision,\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/decision\",\n            payload: {\n              decision,\n            },\n          },\n        });\n\n        if (decision === \"accept\" || decision === \"acceptForSession\") {\n          return {\n            behavior: \"allow\",\n            updatedInput: toolInput,\n            ...(decision === \"acceptForSession\" && pendingApproval.suggestions\n              ? {\n                  updatedPermissions: [...pendingApproval.suggestions],\n                }\n              : {}),\n          } satisfies PermissionResult;\n        }\n\n        return {\n          behavior: \"deny\",\n          message:\n            decision === \"cancel\"\n              ? \"User cancelled tool execution.\"\n              : \"User declined tool execution.\",\n        } satisfies PermissionResult;\n      });\n\n      const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>\n        runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));\n\n      const claudeBinaryPath = claudeSdkExecutablePath;\n      const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;\n      const modelSelection =\n        input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n      const caps = getClaudeModelCapabilities(modelSelection?.model);\n      const descriptors = getProviderOptionDescriptors({ caps });\n      const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;\n      const initialContextWindow = selectedClaudeContextWindow(modelSelection);\n      const rawEffort = getModelSelectionStringOptionValue(modelSelection, \"effort\");\n      const effort = resolveClaudeEffort(caps, rawEffort) ?? null;\n      const fastModeSupported = descriptors.some(\n        (descriptor) => descriptor.type === \"boolean\" && descriptor.id === \"fastMode\",\n      );\n      const thinkingSupported = descriptors.some(\n        (descriptor) => descriptor.type === \"boolean\" && descriptor.id === \"thinking\",\n      );\n      const fastMode =\n        getModelSelectionBooleanOptionValue(modelSelection, \"fastMode\") === true &&\n        fastModeSupported;\n      const thinking = thinkingSupported\n        ? getModelSelectionBooleanOptionValue(modelSelection, \"thinking\")\n        : undefined;\n      const ultracode = isClaudeUltracodeEffort(effort);\n      const effectiveEffort = getEffectiveClaudeAgentEffort(effort, modelSelection?.model);\n      const runtimeModeToPermission: Record<string, PermissionMode> = {\n        \"auto-accept-edits\": \"acceptEdits\",\n        auto: \"auto\",\n        \"full-access\": \"bypassPermissions\",\n      };\n      const permissionMode = runtimeModeToPermission[input.runtimeMode];\n      const settings = {\n        ...(typeof thinking === \"boolean\" ? { alwaysThinkingEnabled: thinking } : {}),\n        ...(fastMode ? { fastMode: true } : {}),\n        ...(ultracode ? { ultracode: true } : {}),\n      };\n      const queryOptions: ClaudeQueryOptions = {\n        ...(input.cwd ? { cwd: input.cwd } : {}),\n        ...(apiModelId ? { model: apiModelId } : {}),\n        pathToClaudeCodeExecutable: claudeBinaryPath,\n        systemPrompt: { type: \"preset\", preset: \"claude_code\" },\n        settingSources: [...CLAUDE_SETTING_SOURCES],\n        // `ultracode` is a Claude Code setting, not an API effort level. It is\n        // normalized to `xhigh` above and paired with `settings.ultracode`.\n        ...(effectiveEffort\n          ? {\n              effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions[\"effort\"]>,\n            }\n          : {}),\n        ...(permissionMode ? { permissionMode } : {}),\n        ...(permissionMode === \"bypassPermissions\"\n          ? { allowDangerouslySkipPermissions: true }\n          : {}),\n        ...(Object.keys(settings).length > 0 ? { settings } : {}),\n        ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),\n        ...(newSessionId ? { sessionId: newSessionId } : {}),\n        includePartialMessages: true,\n        canUseTool,\n        env: claudeEnvironment,\n        ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),\n        ...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),\n      };\n\n      yield* Effect.annotateCurrentSpan({\n        \"provider.kind\": PROVIDER,\n        \"provider.thread_id\": threadId,\n        \"provider.runtime_mode\": input.runtimeMode,\n        \"claude.resume.source\":\n          existingResumeSessionId !== undefined ? \"resume-session\" : \"generated-session\",\n        \"claude.resume.thread_id\": resumeState?.threadId ?? \"\",\n        \"claude.resume.session_id\": existingResumeSessionId ?? \"\",\n        \"claude.resume.session_at\": resumeState?.resumeSessionAt ?? \"\",\n        \"claude.resume.turn_count\": resumeState?.turnCount ?? -1,\n        \"claude.query.cwd\": input.cwd ?? \"\",\n        \"claude.query.model\": apiModelId ?? \"\",\n        \"claude.query.effort\": effectiveEffort ?? \"\",\n        \"claude.query.permission_mode\": permissionMode ?? \"\",\n        \"claude.query.allow_dangerously_skip_permissions\": permissionMode === \"bypassPermissions\",\n        \"claude.query.resume\": existingResumeSessionId ?? \"\",\n        \"claude.query.session_id\": newSessionId ?? \"\",\n        \"claude.query.include_partial_messages\": true,\n        \"claude.query.additional_directories\": input.cwd ? [input.cwd] : [],\n        \"claude.query.setting_sources\": [...CLAUDE_SETTING_SOURCES],\n        \"claude.query.settings_json\": encodeJsonStringForDiagnostics(settings) ?? \"\",\n        \"claude.query.extra_args_json\": encodeJsonStringForDiagnostics(extraArgs) ?? \"\",\n        \"claude.query.path_to_executable\": claudeBinaryPath,\n      });\n\n      const queryRuntime = yield* Effect.try({\n        try: () =>\n          createQuery({\n            prompt,\n            options: queryOptions,\n          }),\n        catch: (cause) =>\n          new ProviderAdapterProcessError({\n            provider: PROVIDER,\n            threadId,\n            detail: \"Failed to start Claude runtime session.\",\n            cause,\n          }),\n      });\n\n      const session: ProviderSession = {\n        threadId,\n        provider: PROVIDER,\n        providerInstanceId: boundInstanceId,\n        status: \"ready\",\n        runtimeMode: input.runtimeMode,\n        ...(input.cwd ? { cwd: input.cwd } : {}),\n        ...(modelSelection?.model ? { model: modelSelection.model } : {}),\n        ...(threadId ? { threadId } : {}),\n        resumeCursor: {\n          ...(threadId ? { threadId } : {}),\n          ...(sessionId ? { resume: sessionId } : {}),\n          ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),\n          turnCount: resumeState?.turnCount ?? 0,\n        },\n        createdAt: startedAt,\n        updatedAt: startedAt,\n      };\n\n      const context: ClaudeSessionContext = {\n        session,\n        promptQueue,\n        query: queryRuntime,\n        streamFiber: undefined,\n        startedAt,\n        basePermissionMode: permissionMode,\n        currentApiModelId: apiModelId,\n        currentEffort: effectiveEffort ?? undefined,\n        resumeSessionId: sessionId,\n        pendingApprovals,\n        pendingUserInputs,\n        turns: [],\n        inFlightTools,\n        claudeTasks,\n        taskAgents,\n        workflowMemberFingerprints,\n        liveTaskIds,\n        turnState: undefined,\n        lastKnownContextWindow: initialContextWindow,\n        lastKnownTokenUsage: undefined,\n        lastKnownTotalProcessedTokens: undefined,\n        lastAssistantUuid: resumeState?.resumeSessionAt,\n        lastThreadStartedId: undefined,\n        stopped: false,\n      };\n      yield* Ref.set(contextRef, context);\n      sessions.set(threadId, context);\n\n      const sessionStartedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.started\",\n        eventId: sessionStartedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: sessionStartedStamp.createdAt,\n        threadId,\n        payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {},\n        providerRefs: {},\n      });\n\n      const configuredStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.configured\",\n        eventId: configuredStamp.eventId,\n        provider: PROVIDER,\n        createdAt: configuredStamp.createdAt,\n        threadId,\n        payload: {\n          config: {\n            ...(apiModelId ? { model: apiModelId } : {}),\n            ...(input.cwd ? { cwd: input.cwd } : {}),\n            ...(effectiveEffort ? { effort: effectiveEffort } : {}),\n            ...(permissionMode ? { permissionMode } : {}),\n            ...(fastMode ? { fastMode: true } : {}),\n          },\n        },\n        providerRefs: {},\n      });\n\n      const readyStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.state.changed\",\n        eventId: readyStamp.eventId,\n        provider: PROVIDER,\n        createdAt: readyStamp.createdAt,\n        threadId,\n        payload: {\n          state: \"ready\",\n        },\n        providerRefs: {},\n      });\n\n      let streamFiber: Fiber.Fiber<void, never>;\n      streamFiber = runFork(\n        Effect.exit(runSdkStream(context)).pipe(\n          Effect.flatMap((exit) => {\n            if (context.stopped) {\n              return Effect.void;\n            }\n            if (context.streamFiber === streamFiber) {\n              context.streamFiber = undefined;\n            }\n            return handleStreamExit(context, exit).pipe(\n              Effect.catch((cause) =>\n                Effect.logError(\"Failed to close Claude runtime stream.\", { cause }),\n              ),\n            );\n          }),\n        ),\n      );\n      context.streamFiber = streamFiber;\n      streamFiber.addObserver(() => {\n        if (context.streamFiber === streamFiber) {\n          context.streamFiber = undefined;\n        }\n      });\n\n      return {\n        ...session,\n      };\n    },\n  );\n\n  const sendTurn: ClaudeAdapterShape[\"sendTurn\"] = Effect.fn(\"sendTurn\")(function* (input) {\n    const context = yield* requireSession(input.threadId);\n    const modelSelection =\n      input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId\n        ? input.modelSelection\n        : undefined;\n\n    // A sendTurn while a real turn is running is a steer: the message is\n    // queued into the live SDK agent loop and the work continues as the same\n    // turn — no synthetic turn boundary. Stale synthetic turns (from\n    // background agent responses between user prompts) are auto-closed\n    // instead, so they don't block the user's next turn.\n    const steeringTurnState =\n      context.turnState && context.turnState.synthetic !== true ? context.turnState : null;\n    if (context.turnState && steeringTurnState === null) {\n      yield* completeTurn(context, \"completed\");\n    }\n\n    if (modelSelection?.model) {\n      const apiModelId = resolveClaudeApiModelId(modelSelection);\n      if (context.currentApiModelId !== apiModelId) {\n        yield* Effect.tryPromise({\n          try: () => context.query.setModel(apiModelId),\n          catch: (cause) => toRequestError(input.threadId, \"turn/setModel\", cause),\n        });\n        context.currentApiModelId = apiModelId;\n      }\n      context.session = {\n        ...context.session,\n        model: modelSelection.model,\n      };\n      const turnCaps = getClaudeModelCapabilities(modelSelection.model);\n      const turnEffort = resolveClaudeEffort(\n        turnCaps,\n        getModelSelectionStringOptionValue(modelSelection, \"effort\"),\n      );\n      context.currentEffort =\n        getEffectiveClaudeAgentEffort(turnEffort ?? null, modelSelection.model) ?? undefined;\n    }\n\n    // Apply interaction mode by switching the SDK's permission mode.\n    // \"plan\" maps directly to the SDK's \"plan\" permission mode;\n    // \"default\" restores the session's original permission mode.\n    // When interactionMode is absent we leave the current mode unchanged.\n    if (input.interactionMode === \"plan\") {\n      yield* Effect.tryPromise({\n        try: () => context.query.setPermissionMode(\"plan\"),\n        catch: (cause) => toRequestError(input.threadId, \"turn/setPermissionMode\", cause),\n      });\n    } else if (input.interactionMode === \"default\") {\n      yield* Effect.tryPromise({\n        try: () => context.query.setPermissionMode(context.basePermissionMode ?? \"default\"),\n        catch: (cause) => toRequestError(input.threadId, \"turn/setPermissionMode\", cause),\n      });\n    }\n\n    const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);\n    if (steeringTurnState === null) {\n      const turnState: ClaudeTurnState = {\n        turnId,\n        startedAt: yield* nowIso,\n        items: [],\n        assistantTextBlocks: new Map(),\n        assistantTextBlockOrder: [],\n        capturedProposedPlanKeys: new Set(),\n        nextSyntheticAssistantBlockIndex: -1,\n      };\n\n      const updatedAt = yield* nowIso;\n      context.turnState = turnState;\n      context.session = {\n        ...context.session,\n        status: \"running\",\n        activeTurnId: turnId,\n        updatedAt,\n      };\n\n      const turnStartedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"turn.started\",\n        eventId: turnStartedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: turnStartedStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId,\n        payload: modelSelection?.model ? { model: modelSelection.model } : {},\n        providerRefs: {},\n      });\n    }\n\n    const message = yield* buildUserMessageEffect(input, {\n      fileSystem,\n      attachmentsDir: serverConfig.attachmentsDir,\n      boundInstanceId,\n    });\n\n    yield* Queue.offer(context.promptQueue, {\n      type: \"message\",\n      message,\n    }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, \"turn/start\", cause)));\n\n    return {\n      threadId: context.session.threadId,\n      turnId,\n      ...(context.session.resumeCursor !== undefined\n        ? { resumeCursor: context.session.resumeCursor }\n        : {}),\n    };\n  });\n\n  const interruptTurn: ClaudeAdapterShape[\"interruptTurn\"] = Effect.fn(\"interruptTurn\")(\n    function* (threadId, _turnId) {\n      const context = yield* requireSession(threadId);\n      // Stop-everything semantics: users reach for Stop precisely when a\n      // fleet ran away. interrupt() alone only ends the parent turn —\n      // background subagents/shells keep running and keep burning tokens.\n      // Stop every live task first (best-effort per task: one refusal must\n      // not strand the rest or block the turn interrupt), then interrupt.\n      if (context.query.stopTask && context.liveTaskIds.size > 0) {\n        const liveIds = Array.from(context.liveTaskIds);\n        // Bounded: a wedged child's stopTask promise may never settle\n        // (Effect.ignore handles rejection, not non-resolution), and the\n        // parent interrupt below MUST still run — Stop matters most during\n        // runaway fleets (review finding). Per-task timeout keeps one hung\n        // child from consuming the whole budget.\n        yield* Effect.forEach(\n          liveIds,\n          (taskId) =>\n            Effect.tryPromise({\n              // Invoke through the query object: SDK methods rely on `this`.\n              try: () => context.query.stopTask!(taskId),\n              catch: () => undefined,\n            }).pipe(Effect.timeoutOption(\"3 seconds\"), Effect.ignore),\n          { concurrency: 8, discard: true },\n        ).pipe(Effect.timeoutOption(\"10 seconds\"), Effect.ignore);\n      }\n      yield* Effect.tryPromise({\n        try: () => context.query.interrupt(),\n        catch: (cause) => toRequestError(threadId, \"turn/interrupt\", cause),\n      });\n    },\n  );\n\n  const readThread: ClaudeAdapterShape[\"readThread\"] = Effect.fn(\"readThread\")(\n    function* (input) {\n      const context = yield* requireSession(input.threadId);\n      return yield* snapshotThread(context);\n    },\n  );\n\n  const rollbackThread: ClaudeAdapterShape[\"rollbackThread\"] = Effect.fn(\"rollbackThread\")(\n    function* (threadId, numTurns) {\n      const context = yield* requireSession(threadId);\n      const nextLength = Math.max(0, context.turns.length - numTurns);\n      context.turns.splice(nextLength);\n      yield* updateResumeCursor(context);\n      return yield* snapshotThread(context);\n    },\n  );\n\n  const respondToRequest: ClaudeAdapterShape[\"respondToRequest\"] = Effect.fn(\"respondToRequest\")(\n    function* (threadId, requestId, decision) {\n      const context = yield* requireSession(threadId);\n      const pending = context.pendingApprovals.get(requestId);\n      if (!pending) {\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"item/requestApproval/decision\",\n          detail: `Unknown pending approval request: ${requestId}`,\n        });\n      }\n\n      context.pendingApprovals.delete(requestId);\n      yield* Deferred.succeed(pending.decision, decision);\n    },\n  );\n\n  const respondToUserInput: ClaudeAdapterShape[\"respondToUserInput\"] = Effect.fn(\n    \"respondToUserInput\",\n  )(function* (threadId, requestId, answers) {\n    const context = yield* requireSession(threadId);\n    const pending = context.pendingUserInputs.get(requestId);\n    if (!pending) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"item/tool/respondToUserInput\",\n        detail: `Unknown pending user-input request: ${requestId}`,\n      });\n    }\n\n    context.pendingUserInputs.delete(requestId);\n    yield* Deferred.succeed(pending.answers, answers);\n  });\n\n  const stopSession: ClaudeAdapterShape[\"stopSession\"] = Effect.fn(\"stopSession\")(\n    function* (threadId) {\n      const context = yield* requireSession(threadId);\n      yield* stopSessionInternal(context, {\n        emitExitEvent: true,\n      });\n    },\n  );\n\n  const listSessions: ClaudeAdapterShape[\"listSessions\"] = () =>\n    Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session })));\n\n  const hasSession: ClaudeAdapterShape[\"hasSession\"] = (threadId) =>\n    Effect.sync(() => {\n      const context = sessions.get(threadId);\n      return context !== undefined && !context.stopped;\n    });\n\n  const stopAll: ClaudeAdapterShape[\"stopAll\"] = () =>\n    Effect.forEach(\n      sessions,\n      ([, context]) =>\n        stopSessionInternal(context, {\n          emitExitEvent: true,\n        }),\n      { discard: true },\n    );\n\n  yield* Effect.addFinalizer(() =>\n    Effect.forEach(\n      sessions,\n      ([, context]) =>\n        stopSessionInternal(context, {\n          emitExitEvent: false,\n        }),\n      { discard: true },\n    ).pipe(\n      Effect.catch((cause) =>\n        Effect.logError(\"Failed to emit Claude session shutdown event.\", { cause }),\n      ),\n      Effect.tap(() => Queue.shutdown(runtimeEventQueue)),\n      Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),\n    ),\n  );\n\n  return {\n    provider: PROVIDER,\n    capabilities: {\n      sessionModelSwitch: \"in-session\",\n    },\n    startSession,\n    sendTurn,\n    interruptTurn,\n    readThread,\n    rollbackThread,\n    respondToRequest,\n    respondToUserInput,\n    stopSession,\n    listSessions,\n    hasSession,\n    stopAll,\n    get streamEvents() {\n      return Stream.fromQueue(runtimeEventQueue);\n    },\n  } satisfies ClaudeAdapterShape;\n});\n","import {\n  DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,\n  type ServerProvider,\n  ServerSettingsError,\n} from \"@t3tools/contracts\";\nimport { resolveServerBackgroundActivitySettings } from \"@t3tools/shared/backgroundActivitySettings\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nimport * as BackgroundPolicy from \"../background/BackgroundPolicy.ts\";\nimport { ServerSettingsService } from \"../serverSettings.ts\";\nimport type { ServerProviderShape } from \"./Services/ServerProvider.ts\";\n\ninterface ProviderSnapshotState {\n  readonly snapshot: ServerProvider;\n  readonly enrichmentGeneration: number;\n}\n\nexport const makeManagedServerProvider = Effect.fn(\"makeManagedServerProvider\")(function* <\n  Settings,\n>(input: {\n  readonly maintenanceCapabilities: ServerProviderShape[\"maintenanceCapabilities\"];\n  readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;\n  readonly streamSettings: Stream.Stream<Settings>;\n  readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;\n  readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;\n  readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;\n  readonly enrichSnapshot?: (input: {\n    readonly settings: Settings;\n    readonly snapshot: ServerProvider;\n    readonly getSnapshot: Effect.Effect<ServerProvider>;\n    readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;\n  }) => Effect.Effect<void>;\n  readonly refreshInterval?: Duration.Input;\n}): Effect.fn.Return<\n  ServerProviderShape,\n  ServerSettingsError,\n  Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService\n> {\n  const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;\n  const serverSettings = yield* ServerSettingsService;\n  const refreshSemaphore = yield* Semaphore.make(1);\n  const changesPubSub = yield* Effect.acquireRelease(\n    PubSub.unbounded<ServerProvider>(),\n    PubSub.shutdown,\n  );\n  const initialSettings = yield* input.getSettings;\n  const initialSnapshot = yield* input.initialSnapshot(initialSettings);\n  const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({\n    snapshot: initialSnapshot,\n    enrichmentGeneration: 0,\n  });\n  const settingsRef = yield* Ref.make(initialSettings);\n  const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);\n  const scope = yield* Effect.scope;\n\n  const publishEnrichedSnapshot = Effect.fn(\"publishEnrichedSnapshot\")(function* (\n    generation: number,\n    nextSnapshot: ServerProvider,\n  ) {\n    const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {\n      if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {\n        return [null, state] as const;\n      }\n      return [\n        nextSnapshot,\n        {\n          ...state,\n          snapshot: nextSnapshot,\n        },\n      ] as const;\n    });\n    if (snapshotToPublish === null) {\n      return;\n    }\n    yield* PubSub.publish(changesPubSub, snapshotToPublish);\n  });\n\n  const restartSnapshotEnrichment = Effect.fn(\"restartSnapshotEnrichment\")(function* (\n    settings: Settings,\n    snapshot: ServerProvider,\n    generation: number,\n  ) {\n    const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);\n    if (previousFiber) {\n      yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);\n    }\n\n    if (!input.enrichSnapshot) {\n      return;\n    }\n\n    const fiber = yield* input\n      .enrichSnapshot({\n        settings,\n        snapshot,\n        getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),\n        publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),\n      })\n      .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));\n\n    yield* Ref.set(enrichmentFiberRef, fiber);\n  });\n\n  const applySnapshotBase = Effect.fn(\"applySnapshot\")(function* (\n    nextSettings: Settings,\n    options?: { readonly forceRefresh?: boolean },\n  ) {\n    const forceRefresh = options?.forceRefresh === true;\n    const previousSettings = yield* Ref.get(settingsRef);\n    if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {\n      yield* Ref.set(settingsRef, nextSettings);\n      return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));\n    }\n\n    const nextSnapshot = yield* input.checkProvider;\n    const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {\n      const generation = input.enrichSnapshot\n        ? state.enrichmentGeneration + 1\n        : state.enrichmentGeneration;\n      return [\n        generation,\n        {\n          snapshot: nextSnapshot,\n          enrichmentGeneration: generation,\n        },\n      ] as const;\n    });\n    yield* Ref.set(settingsRef, nextSettings);\n    yield* PubSub.publish(changesPubSub, nextSnapshot);\n    yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);\n    return nextSnapshot;\n  });\n  const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>\n    refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));\n\n  const refreshSnapshot = Effect.fn(\"refreshSnapshot\")(function* () {\n    const nextSettings = yield* input.getSettings;\n    return yield* applySnapshot(nextSettings, { forceRefresh: true });\n  });\n\n  const hasProviderStatusDemand = Effect.gen(function* () {\n    const state = yield* Ref.get(snapshotStateRef);\n    const instanceId = state.snapshot.instanceId;\n    const [genericDemand, instanceDemand] = yield* Effect.all([\n      backgroundPolicy.shouldRunScopeWork({ type: \"provider-status\" }),\n      backgroundPolicy.shouldRunScopeWork({ type: \"provider-status\", instanceId }),\n    ]);\n    return genericDemand || instanceDemand;\n  });\n\n  const getRefreshInterval =\n    input.refreshInterval !== undefined\n      ? Effect.succeed(input.refreshInterval)\n      : serverSettings.getSettings.pipe(\n          Effect.map(\n            (settings) =>\n              resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,\n          ),\n          Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),\n        );\n\n  const refreshIntervalChanges = yield* Queue.sliding<void>(1);\n  if (input.refreshInterval === undefined) {\n    const serverSettingsChanges = yield* serverSettings.subscribeChanges;\n    yield* serverSettingsChanges.pipe(\n      Stream.map((settings) =>\n        Duration.toMillis(\n          resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,\n        ),\n      ),\n      Stream.changes,\n      Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),\n      Effect.forkScoped,\n    );\n  }\n\n  yield* Stream.runForEach(input.streamSettings, (nextSettings) =>\n    Effect.asVoid(applySnapshot(nextSettings)),\n  ).pipe(Effect.forkScoped);\n\n  yield* Effect.forever(\n    getRefreshInterval.pipe(\n      Effect.flatMap((refreshInterval) =>\n        Effect.raceFirst(\n          Effect.sleep(\n            Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0\n              ? \"60 seconds\"\n              : refreshInterval,\n          ).pipe(Effect.as(true)),\n          Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),\n        ).pipe(\n          Effect.flatMap((intervalElapsed) =>\n            intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0\n              ? hasProviderStatusDemand.pipe(\n                  Effect.flatMap((shouldRefresh) =>\n                    shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,\n                  ),\n                )\n              : Effect.void,\n          ),\n        ),\n      ),\n      Effect.ignoreCause({ log: true }),\n    ),\n  ).pipe(Effect.forkScoped);\n\n  yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(\n    Effect.ignoreCause({ log: true }),\n    Effect.forkScoped,\n  );\n\n  return {\n    maintenanceCapabilities: input.maintenanceCapabilities,\n    getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),\n    refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n  } satisfies ServerProviderShape;\n});\n","/**\n * ProviderDriver / ProviderInstance — driver SPI as plain values.\n *\n * `ProviderDriver` is a record, not a Context.Service. The thing it produces\n * (`ProviderInstance`) is also a record — three captured closures\n * (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There\n * are intentionally no per-driver Context tags because tags are\n * singleton-per-runtime and we need many instances of the same driver.\n *\n * The only Effect service involved is `ProviderInstanceRegistry`, which\n * owns the live `Map<InstanceId, ProviderInstance>` and is itself a\n * singleton.\n *\n * Driver factories are functions of `(typed config, env)` where:\n *   - `typed config` is decoded once by the registry via `configSchema`,\n *     so drivers never deal with raw `unknown`.\n *   - `env` flows through Effect's R channel. Each driver declares the\n *     subset of infrastructure services it needs (FileSystem,\n *     ChildProcessSpawner, …) on its `create` return type; the registry\n *     layer's R is the union of those, and the runtime layer satisfies it.\n *\n * @module provider/ProviderDriver\n */\nimport type {\n  ProviderDriverKind,\n  ProviderInstanceEnvironment,\n  ProviderInstanceId,\n} from \"@t3tools/contracts\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\n\nimport type * as TextGeneration from \"../textGeneration/TextGeneration.ts\";\nimport type { ProviderAdapterError, ProviderDriverError } from \"./Errors.ts\";\nimport type { ProviderAdapterShape } from \"./Services/ProviderAdapter.ts\";\nimport type { ServerProviderShape } from \"./Services/ServerProvider.ts\";\n\n/**\n * Static metadata advertised by a driver. Used for default presentation\n * and (later) settings UI. Doesn't need to be Effect-typed because nothing\n * about it is dynamic — drivers are registered at startup.\n */\nexport interface ProviderDriverMetadata {\n  /** Human-readable name for the driver itself (e.g. \"Codex\"). */\n  readonly displayName: string;\n  /**\n   * Whether the driver may be instantiated more than once concurrently.\n   * Defaults to `true`. Set to `false` for drivers that wrap a global\n   * resource (e.g. a single desktop app socket) — the registry then\n   * rejects multi-instance configurations with a clear error.\n   */\n  readonly supportsMultipleInstances?: boolean;\n}\n\n/**\n * One materialized provider instance. Held by the registry, looked up by\n * `instanceId`, torn down by closing the scope it was created in.\n *\n * The three \"shape\" fields are captured closures owned by this instance —\n * stopping one instance cannot affect another, and starting a second\n * instance of the same driver does not reach into the first instance's\n * state.\n */\nexport interface ProviderInstance {\n  readonly instanceId: ProviderInstanceId;\n  readonly driverKind: ProviderDriverKind;\n  readonly continuationIdentity: ProviderContinuationIdentity;\n  readonly displayName: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly enabled: boolean;\n  readonly snapshot: ServerProviderShape;\n  readonly adapter: ProviderAdapterShape<ProviderAdapterError>;\n  readonly textGeneration: TextGeneration.TextGeneration[\"Service\"];\n}\n\nexport interface ProviderContinuationIdentity {\n  readonly driverKind: ProviderDriverKind;\n  readonly continuationKey: string;\n}\n\nexport function defaultProviderContinuationIdentity(input: {\n  readonly driverKind: ProviderDriverKind;\n  readonly instanceId: ProviderInstanceId;\n}): ProviderContinuationIdentity {\n  return {\n    driverKind: input.driverKind,\n    continuationKey: `${input.driverKind}:instance:${input.instanceId}`,\n  };\n}\n\n/**\n * Inputs the registry passes to a driver's `create` function.\n *\n * `config` is the typed payload — already decoded by the registry through\n * `driver.configSchema`. Drivers never decode their own raw envelope.\n */\nexport interface ProviderDriverCreateInput<Config> {\n  readonly instanceId: ProviderInstanceId;\n  readonly displayName: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly environment: ProviderInstanceEnvironment;\n  readonly enabled: boolean;\n  readonly config: Config;\n}\n\n/**\n * Driver SPI — registered as a plain value, not a Layer.\n *\n * `Config` is whatever the driver decoded from\n * `ProviderInstanceConfig.config`. `R` is the union of infrastructure\n * services the driver depends on; the registry layer aggregates `R` across\n * all registered drivers and the runtime supplies them.\n *\n * `create` is responsible for *all* per-instance state — process handles,\n * pubsub topics, refs, file watchers — and must release them when its\n * scope closes. Two calls to `create` with different `instanceId` /\n * `config` MUST yield instances with no shared mutable state.\n */\nexport interface ProviderDriver<Config, R = never> {\n  readonly driverKind: ProviderDriverKind;\n  readonly metadata: ProviderDriverMetadata;\n  /**\n   * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The\n   * registry runs this exactly once per (re)load of an instance; a decode\n   * failure is surfaced as `ProviderDriverError` and downgraded to an\n   * unavailable shadow snapshot.\n   *\n   * The `Encoded` parameter is intentionally left as `unknown` (not\n   * `Config`) so schemas with `withDecodingDefault` / transformations — where\n   * the encoded shape differs from the decoded shape — satisfy the SPI\n   * without casts. The registry only ever decodes `unknown` envelopes here,\n   * so the precise encoded type is irrelevant at this boundary.\n   *\n   * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if\n   * we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would\n   * widen `DecodingServices` to `unknown` and poison the R channel of every\n   * caller of `decodeUnknownEffect`.\n   */\n  readonly configSchema: Schema.Codec<Config, unknown>;\n  /**\n   * Default config payload used when the legacy\n   * `ServerSettings.providers.<kind>` entry is empty or when the driver\n   * is auto-bootstrapped without user configuration. Returning a typed\n   * default keeps the migration path simple — no special-casing needed\n   * to construct a \"blank\" instance.\n   */\n  readonly defaultConfig: () => Config;\n  /**\n   * Materialize one instance. The returned effect runs in a scope owned\n   * by the registry; closing that scope releases every resource the\n   * driver opened. Failures become unavailable shadow snapshots — the\n   * driver MUST NOT throw defects.\n   */\n  readonly create: (\n    input: ProviderDriverCreateInput<Config>,\n  ) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;\n}\n\n/**\n * Heterogeneous-array convenience: the registry stores drivers as\n * `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all\n * registered drivers' env requirements.\n */\n// `any` here intentionally erases the per-driver Config; the registry\n// already decoded it before invoking `create`, so downstream code never\n// needs the original `Config` type. Using `unknown` instead would force\n// `create` callers into casts since `unknown` is not assignable to a\n// concrete `Config` from inside the driver body.\nexport type AnyProviderDriver<R = never> = ProviderDriver<any, R>;\n","import type { ProviderInstanceEnvironment } from \"@t3tools/contracts\";\n\nexport function mergeProviderInstanceEnvironment(\n  environment: ProviderInstanceEnvironment | undefined,\n  baseEnv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n  if (!environment || environment.length === 0) {\n    return baseEnv;\n  }\n\n  const next: NodeJS.ProcessEnv = { ...baseEnv };\n  for (const variable of environment) {\n    next[variable.name] = variable.value;\n  }\n  return next;\n}\n","import type { ServerSettings, ServerSettingsError } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Stream from \"effect/Stream\";\n\nimport type * as ServerSettingsModule from \"../serverSettings.ts\";\n\nexport interface ProviderSnapshotSettings<Settings> {\n  readonly provider: Settings;\n  readonly enableProviderUpdateChecks: boolean;\n}\n\nexport function makeProviderSnapshotSettings<Settings>(\n  provider: Settings,\n  settings: ServerSettings,\n): ProviderSnapshotSettings<Settings> {\n  return {\n    provider,\n    enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n  };\n}\n\nexport function haveProviderSnapshotSettingsChanged<Settings>(\n  previous: ProviderSnapshotSettings<Settings>,\n  next: ProviderSnapshotSettings<Settings>,\n): boolean {\n  return !Equal.equals(previous, next);\n}\n\nexport function makeProviderSnapshotSettingsSource<Settings>(\n  provider: Settings,\n  serverSettings: ServerSettingsModule.ServerSettingsService[\"Service\"],\n): {\n  readonly getSettings: Effect.Effect<ProviderSnapshotSettings<Settings>, ServerSettingsError>;\n  readonly streamSettings: Stream.Stream<ProviderSnapshotSettings<Settings>>;\n} {\n  const mapSettings = (settings: ServerSettings) =>\n    makeProviderSnapshotSettings(provider, settings);\n  return {\n    getSettings: serverSettings.getSettings.pipe(Effect.map(mapSettings)),\n    streamSettings: serverSettings.streamChanges.pipe(Stream.map(mapSettings)),\n  };\n}\n","/**\n * ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime.\n *\n * Mirrors `CodexDriver`: a plain value whose `create()` returns one\n * `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration`\n * closures captured over the per-instance `ClaudeSettings`.\n *\n * Unlike Codex, the Claude snapshot probe may invoke a secondary probe\n * (`probeClaudeCapabilities`) to read Anthropic account + slash-command\n * metadata. That probe is per-instance and keyed by binary + resolved HOME so\n * two concurrent Claude instances don't cross-contaminate account metadata.\n *\n * @module provider/Drivers/ClaudeDriver\n */\nimport { ClaudeSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Duration from \"effect/Duration\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { makeClaudeTextGeneration } from \"../../textGeneration/ClaudeTextGeneration.ts\";\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeClaudeAdapter } from \"../Layers/ClaudeAdapter.ts\";\nimport {\n  checkClaudeProviderStatus,\n  makePendingClaudeProvider,\n  probeClaudeCapabilities,\n} from \"../Layers/ClaudeProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport {\n  defaultProviderContinuationIdentity,\n  type ProviderDriver,\n  type ProviderInstance,\n} from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  makePackageManagedProviderMaintenanceResolver,\n  normalizeCommandPath,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nimport { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from \"./ClaudeHome.ts\";\nconst decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"claudeAgent\");\nconst CAPABILITIES_PROBE_TTL = Duration.minutes(5);\n\nfunction isClaudeNativeCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.endsWith(\"/.local/bin/claude\") ||\n    normalized.endsWith(\"/.local/bin/claude.exe\") ||\n    normalized.includes(\"/.local/share/claude/\")\n  );\n}\n\nconst UPDATE = makePackageManagedProviderMaintenanceResolver({\n  provider: DRIVER_KIND,\n  npmPackageName: \"@anthropic-ai/claude-code\",\n  homebrewFormula: \"claude-code\",\n  nativeUpdate: {\n    executable: \"claude\",\n    args: [\"update\"],\n    lockKey: \"claude-native\",\n    isCommandPath: isClaudeNativeCommandPath,\n  },\n});\n\nexport type ClaudeDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"Claude\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: ClaudeSettings,\n  defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n      const fileSystem = yield* FileSystem.FileSystem;\n      const path = yield* Path.Path;\n      const { cwd } = yield* ServerConfig;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const fallbackContinuationIdentity = defaultProviderContinuationIdentity({\n        driverKind: DRIVER_KIND,\n        instanceId,\n      });\n      const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n      const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey,\n      });\n\n      const adapterOptions = {\n        instanceId,\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n      };\n      const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);\n      const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);\n\n      // Per-instance capabilities cache: keyed on binary + resolved HOME so\n      // account-specific probes never share auth metadata across instances.\n      const capabilitiesProbeCache = yield* Cache.make({\n        capacity: 1,\n        timeToLive: CAPABILITIES_PROBE_TTL,\n        lookup: () =>\n          probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(\n            Effect.provideService(Path.Path, path),\n          ),\n      });\n      const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);\n\n      const checkProvider = checkClaudeProviderStatus(\n        effectiveConfig,\n        () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),\n        processEnv,\n        cwd,\n      ).pipe(\n        Effect.map(stampIdentity),\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n        Effect.provideService(FileSystem.FileSystem, fileSystem),\n        Effect.provideService(Path.Path, path),\n      );\n\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({\n        maintenanceCapabilities,\n        getSettings: snapshotSettings.getSettings,\n        streamSettings: snapshotSettings.streamSettings,\n        haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n        initialSnapshot: (settings) =>\n          makePendingClaudeProvider(settings.provider).pipe(Effect.map(stampIdentity)),\n        checkProvider,\n        enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>\n          enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {\n            enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n          }).pipe(\n            Effect.provideService(HttpClient.HttpClient, httpClient),\n            Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),\n          ),\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity: {\n          ...fallbackContinuationIdentity,\n          continuationKey: continuationGroupKey,\n        },\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","import { tokenizeCliArgs } from \"@t3tools/shared/cliArgs\";\n\nexport const T3CODE_CODEX_LAUNCH_ARGS_ENV = \"T3CODE_CODEX_LAUNCH_ARGS\";\n\nexport const resolveCodexLaunchArgs = (\n  launchArgs?: string,\n  environment: NodeJS.ProcessEnv = process.env,\n) => environment[T3CODE_CODEX_LAUNCH_ARGS_ENV]?.trim() || launchArgs?.trim() || \"\";\n\nexport const codexLaunchArgv = (launchArgs?: string): ReadonlyArray<string> =>\n  tokenizeCliArgs(launchArgs);\n\nexport const codexAppServerArgs = (launchArgs?: string) => [\n  \"app-server\",\n  ...codexLaunchArgv(launchArgs),\n];\n\nexport const codexExecLaunchArgs = (launchArgs?: string) => {\n  const args = codexLaunchArgv(launchArgs);\n  const execArgs: Array<string> = [];\n\n  for (let index = 0; index < args.length; index++) {\n    const arg = args[index];\n    if (arg === undefined) continue;\n\n    if (arg === \"--strict-config\" || arg.startsWith(\"--config=\") || arg.startsWith(\"-c=\")) {\n      execArgs.push(arg);\n    } else if (arg === \"--config\" || arg === \"-c\" || arg === \"--enable\" || arg === \"--disable\") {\n      const value = args[index + 1];\n      if (value !== undefined && !value.startsWith(\"-\")) {\n        execArgs.push(arg, value);\n        index++;\n      }\n    } else if (arg.startsWith(\"--enable=\") || arg.startsWith(\"--disable=\")) {\n      execArgs.push(arg);\n    }\n  }\n\n  return execArgs;\n};\n\nexport const codexSessionAppServerArgs = (\n  appServerArgs: ReadonlyArray<string> | undefined,\n  launchArgs: string | undefined,\n) => {\n  const launchAppServerArgs = codexAppServerArgs(launchArgs);\n  return appServerArgs ? [...launchAppServerArgs, ...appServerArgs] : launchAppServerArgs;\n};\n","import type { ModelSelection } from \"@t3tools/contracts\";\nimport {\n  getModelSelectionBooleanOptionValue,\n  getModelSelectionStringOptionValue,\n} from \"@t3tools/shared/model\";\n\nexport function getCodexServiceTierOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n): string | undefined {\n  return (\n    getModelSelectionStringOptionValue(modelSelection, \"serviceTier\") ??\n    (getModelSelectionBooleanOptionValue(modelSelection, \"fastMode\") === true ? \"fast\" : undefined)\n  );\n}\n","import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport {\n  type CodexSettings,\n  DEFAULT_TEXT_GENERATION_REASONING_EFFORT,\n  type ModelSelection,\n  TextGenerationError,\n} from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport { resolveAttachmentPath } from \"../attachmentStore.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { expandHomePath } from \"../pathExpansion.ts\";\nimport { codexExecLaunchArgs, resolveCodexLaunchArgs } from \"../provider/Layers/codexLaunchArgs.ts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  normalizeCliError,\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n  toJsonSchemaObject,\n} from \"./TextGenerationUtils.ts\";\nimport { getModelSelectionStringOptionValue } from \"@t3tools/shared/model\";\nimport { getCodexServiceTierOptionValue } from \"../codexModelOptions.ts\";\n\nconst CODEX_TIMEOUT_MS = 180_000;\nconst encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));\n/**\n * Build a Codex text-generation closure bound to a specific `CodexSettings`\n * payload. See `makeCodexAdapter` for the overall per-instance rationale.\n */\nexport const makeCodexTextGeneration = Effect.fn(\"makeCodexTextGeneration\")(function* (\n  codexConfig: CodexSettings,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);\n  const resolvedEnvironment = environment ?? process.env;\n\n  type MaterializedImageAttachments = {\n    readonly imagePaths: ReadonlyArray<string>;\n  };\n\n  const readStreamAsString = <E>(\n    operation: string,\n    stream: Stream.Stream<Uint8Array, E>,\n  ): Effect.Effect<string, TextGenerationError> =>\n    stream.pipe(\n      Stream.decodeText(),\n      Stream.runFold(\n        () => \"\",\n        (acc, chunk) => acc + chunk,\n      ),\n      Effect.mapError((cause) =>\n        normalizeCliError(\"codex\", operation, cause, \"Failed to collect process output\"),\n      ),\n    );\n\n  const writeTempFile = (\n    operation: string,\n    prefix: string,\n    content: string,\n  ): Effect.Effect<string, TextGenerationError, Scope.Scope> =>\n    fileSystem\n      .makeTempFileScoped({\n        prefix: `t3code-${prefix}-${process.pid}-`,\n      })\n      .pipe(\n        Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),\n        Effect.mapError(\n          (cause) =>\n            new TextGenerationError({\n              operation,\n              detail: `Failed to write temp file`,\n              cause,\n            }),\n        ),\n      );\n\n  const safeUnlink = (filePath: string): Effect.Effect<void, never> =>\n    fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));\n\n  const encodeJsonForOperation = (\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\",\n    value: unknown,\n  ): Effect.Effect<string, TextGenerationError> =>\n    encodeJsonString(value).pipe(\n      Effect.mapError(\n        (cause) =>\n          new TextGenerationError({\n            operation,\n            detail: \"Failed to encode structured output schema.\",\n            cause,\n          }),\n      ),\n    );\n\n  const materializeImageAttachments = Effect.fn(\"materializeImageAttachments\")(function* (\n    _operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\",\n    attachments: TextGeneration.BranchNameGenerationInput[\"attachments\"],\n  ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {\n    if (!attachments || attachments.length === 0) {\n      return { imagePaths: [] };\n    }\n\n    const imagePaths: string[] = [];\n    for (const attachment of attachments) {\n      if (attachment.type !== \"image\") {\n        continue;\n      }\n\n      const resolvedPath = resolveAttachmentPath({\n        attachmentsDir: serverConfig.attachmentsDir,\n        attachment,\n      });\n      if (!resolvedPath || !path.isAbsolute(resolvedPath)) {\n        continue;\n      }\n      const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));\n      if (!fileInfo || fileInfo.type !== \"File\") {\n        continue;\n      }\n      imagePaths.push(resolvedPath);\n    }\n    return { imagePaths };\n  });\n\n  const runCodexJson = Effect.fn(\"runCodexJson\")(function* <S extends Schema.Top>({\n    operation,\n    cwd,\n    prompt,\n    outputSchemaJson,\n    imagePaths = [],\n    cleanupPaths = [],\n    modelSelection,\n  }: {\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n    cwd: string;\n    prompt: string;\n    outputSchemaJson: S;\n    imagePaths?: ReadonlyArray<string>;\n    cleanupPaths?: ReadonlyArray<string>;\n    modelSelection: ModelSelection;\n  }): Effect.fn.Return<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> {\n    const schemaJson = yield* encodeJsonForOperation(\n      operation,\n      toJsonSchemaObject(outputSchemaJson),\n    );\n    const schemaPath = yield* writeTempFile(operation, \"codex-schema\", schemaJson);\n    const outputPath = yield* writeTempFile(operation, \"codex-output\", \"\");\n\n    const runCodexCommand = Effect.fn(\"runCodexJson.runCodexCommand\")(function* () {\n      const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);\n      const reasoningEffort =\n        getModelSelectionStringOptionValue(modelSelection, \"reasoningEffort\") ??\n        DEFAULT_TEXT_GENERATION_REASONING_EFFORT;\n      const serviceTier = getCodexServiceTierOptionValue(modelSelection);\n      const spawnCommand = yield* resolveSpawnCommand(\n        codexConfig.binaryPath || \"codex\",\n        [\n          \"exec\",\n          ...codexExecLaunchArgs(launchArgs),\n          \"--ephemeral\",\n          \"--skip-git-repo-check\",\n          \"-s\",\n          \"read-only\",\n          \"--model\",\n          modelSelection.model,\n          \"--config\",\n          `model_reasoning_effort=\"${reasoningEffort}\"`,\n          ...(serviceTier ? [\"--config\", `service_tier=\"${serviceTier}\"`] : []),\n          \"--output-schema\",\n          schemaPath,\n          \"--output-last-message\",\n          outputPath,\n          ...imagePaths.flatMap((imagePath) => [\"--image\", imagePath]),\n          \"-\",\n        ],\n        { env: resolvedEnvironment },\n      );\n      const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        env: {\n          ...resolvedEnvironment,\n          ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),\n        },\n        cwd,\n        shell: spawnCommand.shell,\n        stdin: {\n          stream: Stream.encodeText(Stream.make(prompt)),\n        },\n      });\n\n      const child = yield* commandSpawner\n        .spawn(command)\n        .pipe(\n          Effect.mapError((cause) =>\n            normalizeCliError(\"codex\", operation, cause, \"Failed to spawn Codex CLI process\"),\n          ),\n        );\n\n      const [stdout, stderr, exitCode] = yield* Effect.all(\n        [\n          readStreamAsString(operation, child.stdout),\n          readStreamAsString(operation, child.stderr),\n          child.exitCode.pipe(\n            Effect.mapError((cause) =>\n              normalizeCliError(\"codex\", operation, cause, \"Failed to read Codex CLI exit code\"),\n            ),\n          ),\n        ],\n        { concurrency: \"unbounded\" },\n      );\n\n      if (exitCode !== 0) {\n        const stderrDetail = stderr.trim();\n        const stdoutDetail = stdout.trim();\n        const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;\n        return yield* new TextGenerationError({\n          operation,\n          detail:\n            detail.length > 0\n              ? `Codex CLI command failed: ${detail}`\n              : `Codex CLI command failed with code ${exitCode}.`,\n        });\n      }\n    });\n\n    const cleanup = Effect.all(\n      [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),\n      {\n        concurrency: \"unbounded\",\n      },\n    ).pipe(Effect.asVoid);\n\n    return yield* Effect.gen(function* () {\n      yield* runCodexCommand().pipe(\n        Effect.scoped,\n        Effect.timeoutOption(CODEX_TIMEOUT_MS),\n        Effect.flatMap(\n          Option.match({\n            onNone: () =>\n              Effect.fail(\n                new TextGenerationError({ operation, detail: \"Codex CLI request timed out.\" }),\n              ),\n            onSome: () => Effect.void,\n          }),\n        ),\n      );\n\n      const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));\n\n      return yield* fileSystem.readFileString(outputPath).pipe(\n        Effect.mapError(\n          (cause) =>\n            new TextGenerationError({\n              operation,\n              detail: \"Failed to read Codex output file.\",\n              cause,\n            }),\n        ),\n        Effect.flatMap(decodeOutput),\n        Effect.catchTags({\n          SchemaError: (cause) =>\n            Effect.fail(\n              new TextGenerationError({\n                operation,\n                detail: \"Codex returned invalid structured output.\",\n                cause,\n              }),\n            ),\n        }),\n      );\n    }).pipe(Effect.ensuring(cleanup));\n  });\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"CodexTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"CodexTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"CodexTextGeneration.generateBranchName\")(function* (input) {\n      const { imagePaths } = yield* materializeImageAttachments(\n        \"generateBranchName\",\n        input.attachments,\n      );\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        imagePaths,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"CodexTextGeneration.generateThreadTitle\")(function* (input) {\n      const { imagePaths } = yield* materializeImageAttachments(\n        \"generateThreadTitle\",\n        input.attachments,\n      );\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        imagePaths,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      } satisfies TextGeneration.ThreadTitleGenerationResult;\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","import * as Schema from \"effect/Schema\";\nimport type * as SchemaIssue from \"effect/SchemaIssue\";\n\nexport const CodexAppServerRequestOperation = Schema.Literals([\n  \"decode-payload\",\n  \"encode-payload\",\n  \"handle-request\",\n  \"receive-response\",\n]);\nexport type CodexAppServerRequestOperation = typeof CodexAppServerRequestOperation.Type;\n\nexport const CodexAppServerSchemaIssueKind = Schema.Literals([\n  \"Filter\",\n  \"Encoding\",\n  \"Pointer\",\n  \"Composite\",\n  \"AnyOf\",\n  \"InvalidType\",\n  \"InvalidValue\",\n  \"MissingKey\",\n  \"UnexpectedKey\",\n  \"Forbidden\",\n  \"OneOf\",\n]);\nexport type CodexAppServerSchemaIssueKind = typeof CodexAppServerSchemaIssueKind.Type;\n\nexport interface CodexAppServerSchemaIssueDiagnostics {\n  readonly issueCount: number;\n  readonly issueKinds: ReadonlyArray<CodexAppServerSchemaIssueKind>;\n  readonly maximumPathDepth: number;\n}\n\nconst schemaIssueDiagnostics = (root: SchemaIssue.Issue): CodexAppServerSchemaIssueDiagnostics => {\n  let issueCount = 0;\n  let maximumPathDepth = 0;\n  const issueKinds = new Set<CodexAppServerSchemaIssueKind>();\n\n  const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {\n    issueCount += 1;\n    issueKinds.add(issue._tag);\n    maximumPathDepth = Math.max(maximumPathDepth, pathDepth);\n    switch (issue._tag) {\n      case \"Filter\":\n      case \"Encoding\":\n        visit(issue.issue, pathDepth);\n        break;\n      case \"Pointer\":\n        visit(issue.issue, pathDepth + issue.path.length);\n        break;\n      case \"Composite\":\n      case \"AnyOf\":\n        for (const child of issue.issues) visit(child, pathDepth);\n        break;\n    }\n  };\n\n  visit(root, 0);\n  return {\n    issueCount,\n    issueKinds: [...issueKinds],\n    maximumPathDepth,\n  };\n};\n\nexport const CodexAppServerPayloadKind = Schema.Literals([\n  \"null\",\n  \"array\",\n  \"string\",\n  \"number\",\n  \"boolean\",\n  \"bigint\",\n  \"object\",\n  \"symbol\",\n  \"function\",\n  \"undefined\",\n]);\nexport type CodexAppServerPayloadKind = typeof CodexAppServerPayloadKind.Type;\n\nconst payloadKind = (payload: unknown): CodexAppServerPayloadKind => {\n  if (payload === null) return \"null\";\n  if (Array.isArray(payload)) return \"array\";\n  return typeof payload;\n};\n\nconst protocolMessageFields = [\"id\", \"method\", \"params\", \"result\", \"error\"] as const;\n\nexport const CodexAppServerProtocolMessageField = Schema.Literals(protocolMessageFields);\nexport type CodexAppServerProtocolMessageField = typeof CodexAppServerProtocolMessageField.Type;\n\nexport interface CodexAppServerRequestDiagnostics {\n  readonly method?: string;\n  readonly requestId?: string;\n  readonly operation?: CodexAppServerRequestOperation;\n  readonly cause?: unknown;\n  readonly issueCount?: number;\n  readonly issueKinds?: ReadonlyArray<CodexAppServerSchemaIssueKind>;\n  readonly maximumPathDepth?: number;\n  readonly payloadKind?: CodexAppServerPayloadKind;\n}\n\nexport const CodexAppServerProtocolParseOperation = Schema.Literals([\n  \"encode-wire-message\",\n  \"decode-wire-message\",\n  \"route-wire-message\",\n  \"decode-notification-payload\",\n  \"decode-request-payload\",\n  \"decode-response-payload\",\n]);\nexport type CodexAppServerProtocolParseOperation = typeof CodexAppServerProtocolParseOperation.Type;\n\nexport const CodexAppServerTransportOperation = Schema.Literals([\n  \"read-input-stream\",\n  \"read-process-exit-status\",\n]);\nexport type CodexAppServerTransportOperation = typeof CodexAppServerTransportOperation.Type;\n\nexport const CodexAppServerIdentifierPurpose = Schema.Literals([\n  \"provider-event\",\n  \"command-approval-request\",\n  \"file-change-approval-request\",\n  \"user-input-request\",\n]);\nexport type CodexAppServerIdentifierPurpose = typeof CodexAppServerIdentifierPurpose.Type;\n\nexport interface CodexAppServerProtocolErrorShape {\n  readonly code: number;\n  readonly message: string;\n  readonly data?: unknown;\n}\n\nexport class CodexAppServerSpawnError extends Schema.TaggedErrorClass<CodexAppServerSpawnError>()(\n  \"CodexAppServerSpawnError\",\n  {\n    command: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return this.command\n      ? `Failed to spawn Codex App Server process for command: ${this.command}`\n      : \"Failed to spawn Codex App Server process\";\n  }\n}\n\nexport class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<CodexAppServerProcessExitedError>()(\n  \"CodexAppServerProcessExitedError\",\n  {\n    code: Schema.optional(Schema.Number),\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return this.code === undefined\n      ? \"Codex App Server process exited\"\n      : `Codex App Server process exited with code ${this.code}`;\n  }\n}\n\nexport class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<CodexAppServerProtocolParseError>()(\n  \"CodexAppServerProtocolParseError\",\n  {\n    operation: CodexAppServerProtocolParseOperation,\n    method: Schema.optionalKey(Schema.String),\n    requestId: Schema.optionalKey(Schema.String),\n    payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),\n    presentFields: Schema.optionalKey(Schema.Array(CodexAppServerProtocolMessageField)),\n    issueCount: Schema.optionalKey(Schema.Number),\n    issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),\n    maximumPathDepth: Schema.optionalKey(Schema.Number),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    const method = this.method === undefined ? \"\" : ` for method '${this.method}'`;\n    return `Codex App Server protocol operation '${this.operation}' failed${method}.`;\n  }\n\n  static fromSchemaError(\n    operation: CodexAppServerProtocolParseOperation,\n    cause: Schema.SchemaError,\n    context: { readonly method?: string; readonly requestId?: string } = {},\n  ) {\n    return new CodexAppServerProtocolParseError({\n      operation,\n      ...context,\n      ...schemaIssueDiagnostics(cause.issue),\n      cause,\n    });\n  }\n\n  static fromRequestError(\n    operation: CodexAppServerProtocolParseOperation,\n    method: string,\n    cause: CodexAppServerRequestError,\n  ) {\n    return new CodexAppServerProtocolParseError({\n      operation,\n      method,\n      ...(cause.issueCount === undefined ? {} : { issueCount: cause.issueCount }),\n      ...(cause.issueKinds === undefined ? {} : { issueKinds: cause.issueKinds }),\n      ...(cause.maximumPathDepth === undefined ? {} : { maximumPathDepth: cause.maximumPathDepth }),\n      cause,\n    });\n  }\n\n  static fromUnroutableMessage(message: unknown) {\n    const diagnostics = { payloadKind: payloadKind(message) };\n    if (typeof message !== \"object\" || message === null || Array.isArray(message)) {\n      return new CodexAppServerProtocolParseError({\n        operation: \"route-wire-message\",\n        ...diagnostics,\n      });\n    }\n\n    const presentFields = protocolMessageFields.filter((field) => field in message);\n    const method =\n      \"method\" in message && typeof message.method === \"string\" ? message.method : undefined;\n    const requestId =\n      \"id\" in message && (typeof message.id === \"string\" || typeof message.id === \"number\")\n        ? String(message.id)\n        : undefined;\n    return new CodexAppServerProtocolParseError({\n      operation: \"route-wire-message\",\n      ...diagnostics,\n      presentFields,\n      ...(method === undefined ? {} : { method }),\n      ...(requestId === undefined ? {} : { requestId }),\n    });\n  }\n}\n\nexport class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(\n  \"CodexAppServerTransportError\",\n  {\n    operation: CodexAppServerTransportOperation,\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Codex App Server transport operation '${this.operation}' failed.`;\n  }\n}\n\nexport class CodexAppServerIdentifierGenerationError extends Schema.TaggedErrorClass<CodexAppServerIdentifierGenerationError>()(\n  \"CodexAppServerIdentifierGenerationError\",\n  {\n    purpose: CodexAppServerIdentifierPurpose,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to generate Codex App Server identifier for ${this.purpose}.`;\n  }\n}\n\nexport class CodexAppServerInputStreamEndedError extends Schema.TaggedErrorClass<CodexAppServerInputStreamEndedError>()(\n  \"CodexAppServerInputStreamEndedError\",\n  {},\n) {\n  override get message() {\n    return \"Codex App Server input stream ended.\";\n  }\n}\n\nexport class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexAppServerRequestError>()(\n  \"CodexAppServerRequestError\",\n  {\n    code: Schema.Number,\n    errorMessage: Schema.String,\n    data: Schema.optional(Schema.Unknown),\n    method: Schema.optionalKey(Schema.String),\n    requestId: Schema.optionalKey(Schema.String),\n    operation: Schema.optionalKey(CodexAppServerRequestOperation),\n    issueCount: Schema.optionalKey(Schema.Number),\n    issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),\n    maximumPathDepth: Schema.optionalKey(Schema.Number),\n    payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),\n    cause: Schema.optionalKey(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return this.errorMessage;\n  }\n\n  static fromProtocolError(\n    error: CodexAppServerProtocolErrorShape,\n    method: string,\n    requestId: string,\n  ) {\n    return new CodexAppServerRequestError({\n      code: error.code,\n      errorMessage: error.message,\n      ...(error.data !== undefined ? { data: error.data } : {}),\n      method,\n      requestId,\n      operation: \"receive-response\",\n      cause: error,\n    });\n  }\n\n  static fromAppServerError(error: CodexAppServerError, method: string) {\n    if (error._tag === \"CodexAppServerRequestError\") {\n      return error;\n    }\n    return CodexAppServerRequestError.internalError(\n      `Codex App Server request handler failed for method '${method}'`,\n      undefined,\n      {\n        method,\n        operation: \"handle-request\",\n        cause: error,\n      },\n    );\n  }\n\n  static parseError(message = \"Parse error\", data?: unknown) {\n    return new CodexAppServerRequestError({\n      code: -32700,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static invalidRequest(message = \"Invalid request\", data?: unknown) {\n    return new CodexAppServerRequestError({\n      code: -32600,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static methodNotFound(method: string) {\n    return new CodexAppServerRequestError({\n      code: -32601,\n      errorMessage: `Method not found: ${method}`,\n    });\n  }\n\n  static invalidParams(\n    message = \"Invalid params\",\n    data?: unknown,\n    diagnostics: CodexAppServerRequestDiagnostics = {},\n  ) {\n    return new CodexAppServerRequestError({\n      code: -32602,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n      ...diagnostics,\n    });\n  }\n\n  static invalidPayload(\n    method: string,\n    operation: \"decode-payload\" | \"encode-payload\",\n    cause: Schema.SchemaError,\n  ) {\n    const diagnostics = schemaIssueDiagnostics(cause.issue);\n    return new CodexAppServerRequestError({\n      code: -32602,\n      errorMessage: `Invalid payload for method '${method}' during '${operation}'`,\n      data: diagnostics,\n      method,\n      operation,\n      ...diagnostics,\n      cause,\n    });\n  }\n\n  static unexpectedPayload(\n    method: string,\n    operation: \"decode-payload\" | \"encode-payload\",\n    payload: unknown,\n  ) {\n    const diagnostics = { payloadKind: payloadKind(payload) };\n    return new CodexAppServerRequestError({\n      code: -32602,\n      errorMessage: `Method '${method}' does not accept a payload during '${operation}'`,\n      data: diagnostics,\n      method,\n      operation,\n      ...diagnostics,\n    });\n  }\n\n  static internalError(\n    message = \"Internal error\",\n    data?: unknown,\n    diagnostics: CodexAppServerRequestDiagnostics = {},\n  ) {\n    return new CodexAppServerRequestError({\n      code: -32603,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n      ...diagnostics,\n    });\n  }\n\n  static overloaded(message = \"Server overloaded; retry later.\", data?: unknown) {\n    return new CodexAppServerRequestError({\n      code: -32001,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  toProtocolError(): CodexAppServerProtocolErrorShape {\n    return {\n      code: this.code,\n      message: this.errorMessage,\n      ...(this.data !== undefined ? { data: this.data } : {}),\n    };\n  }\n}\n\nexport const CodexAppServerError = Schema.Union([\n  CodexAppServerRequestError,\n  CodexAppServerSpawnError,\n  CodexAppServerProcessExitedError,\n  CodexAppServerProtocolParseError,\n  CodexAppServerTransportError,\n  CodexAppServerIdentifierGenerationError,\n  CodexAppServerInputStreamEndedError,\n]);\n\nexport type CodexAppServerError = typeof CodexAppServerError.Type;\n","// This file is generated by the effect-codex-app-server package. Do not edit manually.\n// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461\n\nimport * as Schema from \"effect/Schema\";\n\nexport type ApplyPatchApprovalParams__FileChange =\n  | { readonly content: string; readonly type: \"add\" }\n  | { readonly content: string; readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\"; readonly unified_diff: string };\nexport const ApplyPatchApprovalParams__FileChange = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"add\").annotate({ title: \"AddFileChangeType\" }),\n    }).annotate({ title: \"AddFileChange\" }),\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeleteFileChangeType\" }),\n    }).annotate({ title: \"DeleteFileChange\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdateFileChangeType\" }),\n      unified_diff: Schema.String,\n    }).annotate({ title: \"UpdateFileChange\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ApplyPatchApprovalParams__ThreadId = string;\nexport const ApplyPatchApprovalParams__ThreadId = Schema.String;\n\nexport type ApplyPatchApprovalResponse__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const ApplyPatchApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason = \"unauthorized\";\nexport const ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason =\n  Schema.Literal(\"unauthorized\");\n\nexport type ClientRequest__AbsolutePathBuf = string;\nexport const ClientRequest__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type ClientRequest__AddCreditsNudgeCreditType = \"credits\" | \"usage_limit\";\nexport const ClientRequest__AddCreditsNudgeCreditType = Schema.Literals([\"credits\", \"usage_limit\"]);\n\nexport type ClientRequest__AdditionalContextKind = \"untrusted\" | \"application\";\nexport const ClientRequest__AdditionalContextKind = Schema.Literals([\"untrusted\", \"application\"]);\n\nexport type ClientRequest__AgentMessageInputContent =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const ClientRequest__AgentMessageInputContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"InputTextAgentMessageInputContent\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"EncryptedContentAgentMessageInputContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const ClientRequest__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type ClientRequest__AppsInstalledParams = {\n  readonly forceRefresh?: boolean;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__AppsInstalledParams = Schema.Struct({\n  forceRefresh: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true and Apps are permitted, refresh and publish the hosted connector runtime tool snapshot first.\",\n    }),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional loaded thread id used to evaluate effective app configuration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Read the committed installed connector runtime snapshot.\" });\n\nexport type ClientRequest__AppsListParams = {\n  readonly cursor?: string | null;\n  readonly forceRefetch?: boolean;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__AppsListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  forceRefetch: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass app caches and fetch the latest data from sources.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional thread id used to evaluate app feature gating from that thread's config.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - list available apps/connectors.\" });\n\nexport type ClientRequest__AppsReadParams = {\n  readonly appIds: ReadonlyArray<string>;\n  readonly includeTools?: boolean;\n};\nexport const ClientRequest__AppsReadParams = Schema.Struct({\n  appIds: Schema.Array(Schema.String).annotate({\n    description:\n      \"App ids to read. The server accepts at most 100 ids and deduplicates repeated ids while preserving their first-request order.\",\n  }),\n  includeTools: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, include display-only public tool summaries in the returned metadata.\",\n    }),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - read metadata for specific apps/connectors.\" });\n\nexport type ClientRequest__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const ClientRequest__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__CancelLoginAccountParams = { readonly loginId: string };\nexport const ClientRequest__CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String });\n\nexport type ClientRequest__ClientInfo = {\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n};\nexport const ClientRequest__ClientInfo = Schema.Struct({\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  version: Schema.String,\n});\n\nexport type ClientRequest__CommandExecResizeParams = {\n  readonly processId: string;\n  readonly size: { readonly cols: number; readonly rows: number };\n};\nexport const ClientRequest__CommandExecResizeParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  size: Schema.Struct({\n    cols: Schema.Number.annotate({\n      description: \"Terminal width in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    rows: Schema.Number.annotate({\n      description: \"Terminal height in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" }),\n}).annotate({ description: \"Resize a running PTY-backed `command/exec` session.\" });\n\nexport type ClientRequest__CommandExecTerminalSize = {\n  readonly cols: number;\n  readonly rows: number;\n};\nexport const ClientRequest__CommandExecTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" });\n\nexport type ClientRequest__CommandExecTerminateParams = { readonly processId: string };\nexport const ClientRequest__CommandExecTerminateParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({ description: \"Terminate a running `command/exec` session.\" });\n\nexport type ClientRequest__CommandExecWriteParams = {\n  readonly closeStdin?: boolean;\n  readonly deltaBase64?: string | null;\n  readonly processId: string;\n};\nexport const ClientRequest__CommandExecWriteParams = Schema.Struct({\n  closeStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Close stdin after writing `deltaBase64`, if present.\",\n    }),\n  ),\n  deltaBase64: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional base64-encoded stdin bytes to write.\" }),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({\n  description: \"Write stdin bytes to a running `command/exec` session, close stdin, or both.\",\n});\n\nexport type ClientRequest__CommandMigration = { readonly name: string };\nexport const ClientRequest__CommandMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__ConfigReadParams = {\n  readonly cwd?: string | null;\n  readonly includeLayers?: boolean;\n};\nexport const ClientRequest__ConfigReadParams = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeLayers: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type ClientRequest__ConsumeAccountRateLimitResetCreditParams = {\n  readonly creditId?: string | null;\n  readonly idempotencyKey: string;\n};\nexport const ClientRequest__ConsumeAccountRateLimitResetCreditParams = Schema.Struct({\n  creditId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque reset-credit identifier to redeem. When omitted, the backend selects the next available credit.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  idempotencyKey: Schema.String.annotate({\n    description:\n      \"Identifies one logical reset attempt. A UUID is recommended; reuse the same value when retrying that attempt.\",\n  }),\n});\n\nexport type ClientRequest__ConversationTextRole = \"user\" | \"developer\" | \"assistant\";\nexport const ClientRequest__ConversationTextRole = Schema.Literals([\n  \"user\",\n  \"developer\",\n  \"assistant\",\n]);\n\nexport type ClientRequest__DynamicToolNamespaceTool = {\n  readonly deferLoading?: boolean;\n  readonly description: string;\n  readonly inputSchema: unknown;\n  readonly name: string;\n  readonly type: \"function\";\n};\nexport const ClientRequest__DynamicToolNamespaceTool = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolNamespaceToolType\" }),\n    }).annotate({ title: \"FunctionDynamicToolNamespaceTool\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ExperimentalFeatureEnablementSetParams = {\n  readonly enablement: { readonly [x: string]: boolean };\n};\nexport const ClientRequest__ExperimentalFeatureEnablementSetParams = Schema.Struct({\n  enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({\n    description:\n      \"Process-wide runtime feature enablement keyed by canonical feature name.\\n\\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op.\",\n  }),\n});\n\nexport type ClientRequest__ExperimentalFeatureListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__ExperimentalFeatureListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional loaded thread id. Pass this when showing feature state for an existing thread so enablement is computed from that thread's refreshed config, including project-local config for the thread's cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ExternalAgentConfigDetectParams = {\n  readonly cwds?: ReadonlyArray<string> | null;\n  readonly includeHome?: boolean;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const ClientRequest__ExternalAgentConfigDetectParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Zero or more working directories to include for repo-scoped detection.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHome: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"If true, include detection under the user's home directory.\",\n    }),\n  ),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional migration-source selector. Missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Deprecated field retained for compatibility. This field is ignored; use `migrationSource` to select the migration source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const ClientRequest__ExternalAgentConfigMigrationItemType = Schema.Literals([\n  \"AGENTS_MD\",\n  \"CONFIG\",\n  \"SKILLS\",\n  \"PLUGINS\",\n  \"MCP_SERVER_CONFIG\",\n  \"SUBAGENTS\",\n  \"HOOKS\",\n  \"COMMANDS\",\n  \"MEMORY\",\n  \"SESSIONS\",\n]);\n\nexport type ClientRequest__FeedbackUploadParams = {\n  readonly classification: string;\n  readonly extraLogFiles?: ReadonlyArray<string> | null;\n  readonly includeLogs?: boolean;\n  readonly reason?: string | null;\n  readonly tags?: { readonly [x: string]: string } | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__FeedbackUploadParams = Schema.Struct({\n  classification: Schema.String,\n  extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  includeLogs: Schema.optionalKey(Schema.Boolean),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tags: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__FsCopyParams = {\n  readonly destinationPath: string;\n  readonly recursive?: boolean;\n  readonly sourcePath: string;\n};\nexport const ClientRequest__FsCopyParams = Schema.Struct({\n  destinationPath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Required for directory copies; ignored for file copies.\",\n    }),\n  ),\n  sourcePath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Copy a file or directory tree on the host filesystem.\" });\n\nexport type ClientRequest__FsCreateDirectoryParams = {\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const ClientRequest__FsCreateDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether parent directories should also be created. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Create a directory on the host filesystem.\" });\n\nexport type ClientRequest__FsGetMetadataParams = { readonly path: string };\nexport const ClientRequest__FsGetMetadataParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Request metadata for an absolute path.\" });\n\nexport type ClientRequest__FsReadDirectoryParams = { readonly path: string };\nexport const ClientRequest__FsReadDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"List direct child names for a directory.\" });\n\nexport type ClientRequest__FsReadFileParams = { readonly path: string };\nexport const ClientRequest__FsReadFileParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Read a file from the host filesystem.\" });\n\nexport type ClientRequest__FsRemoveParams = {\n  readonly force?: boolean | null;\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const ClientRequest__FsRemoveParams = Schema.Struct({\n  force: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether missing paths should be ignored. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether directory removal should recurse. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Remove a file or directory tree from the host filesystem.\" });\n\nexport type ClientRequest__FsUnwatchParams = { readonly watchId: string };\nexport const ClientRequest__FsUnwatchParams = Schema.Struct({\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({ description: \"Stop filesystem watch notifications for a prior `fs/watch`.\" });\n\nexport type ClientRequest__FsWatchParams = { readonly path: string; readonly watchId: string };\nexport const ClientRequest__FsWatchParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.\",\n  }),\n}).annotate({ description: \"Start filesystem watch notifications for an absolute path.\" });\n\nexport type ClientRequest__FsWriteFileParams = {\n  readonly dataBase64: string;\n  readonly path: string;\n};\nexport const ClientRequest__FsWriteFileParams = Schema.Struct({\n  dataBase64: Schema.String.annotate({ description: \"File contents encoded as base64.\" }),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Write a file on the host filesystem.\" });\n\nexport type ClientRequest__FuzzyFileSearchParams = {\n  readonly cancellationToken?: string | null;\n  readonly query: string;\n  readonly roots: ReadonlyArray<string>;\n};\nexport const ClientRequest__FuzzyFileSearchParams = Schema.Struct({\n  cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  query: Schema.String,\n  roots: Schema.Array(Schema.String),\n});\n\nexport type ClientRequest__GetAccountParams = { readonly refreshToken?: boolean };\nexport const ClientRequest__GetAccountParams = Schema.Struct({\n  refreshToken: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When `true`, requests a proactive token refresh before returning.\\n\\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__HookMigration = { readonly name: string };\nexport const ClientRequest__HookMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__HooksListParams = { readonly cwds?: ReadonlyArray<string> };\nexport const ClientRequest__HooksListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const ClientRequest__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type ClientRequest__InitializeCapabilities = {\n  readonly experimentalApi?: boolean;\n  readonly mcpServerOpenaiFormElicitation?: boolean;\n  readonly optOutNotificationMethods?: ReadonlyArray<string> | null;\n  readonly requestAttestation?: boolean;\n};\nexport const ClientRequest__InitializeCapabilities = Schema.Struct({\n  experimentalApi: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into receiving experimental API methods and fields.\",\n      default: false,\n    }),\n  ),\n  mcpServerOpenaiFormElicitation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Allow downstream MCP servers to request OpenAI extended form elicitations.\",\n    }),\n  ),\n  optOutNotificationMethods: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Exact notification method names that should be suppressed for this connection (for example `thread/started`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  requestAttestation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into `attestation/generate` requests for upstream `x-oai-attestation`.\",\n      default: false,\n    }),\n  ),\n}).annotate({ description: \"Client-declared capabilities negotiated during initialize.\" });\n\nexport type ClientRequest__InternalChatMessageMetadataPassthrough = {\n  readonly turn_id?: string | null;\n};\nexport const ClientRequest__InternalChatMessageMetadataPassthrough = Schema.Struct({\n  turn_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({\n  description:\n    \"Internal Responses API passthrough metadata copied into underlying chat messages.\\n\\nResponses API strongly types this payload. Do not modify it without first getting API approval and making the corresponding Responses API change.\",\n});\n\nexport type ClientRequest__LegacyAppPathString = string;\nexport const ClientRequest__LegacyAppPathString = Schema.String;\n\nexport type ClientRequest__LocalShellAction = {\n  readonly command: ReadonlyArray<string>;\n  readonly env?: { readonly [x: string]: string } | null;\n  readonly timeout_ms?: number | null;\n  readonly type: \"exec\";\n  readonly user?: string | null;\n  readonly working_directory?: string | null;\n};\nexport const ClientRequest__LocalShellAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.Array(Schema.String),\n      env: Schema.optionalKey(\n        Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n      ),\n      timeout_ms: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"exec\").annotate({ title: \"ExecLocalShellActionType\" }),\n      user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"ExecLocalShellAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__LocalShellStatus = \"completed\" | \"in_progress\" | \"incomplete\";\nexport const ClientRequest__LocalShellStatus = Schema.Literals([\n  \"completed\",\n  \"in_progress\",\n  \"incomplete\",\n]);\n\nexport type ClientRequest__LoginAppBrand = \"codex\" | \"chatgpt\";\nexport const ClientRequest__LoginAppBrand = Schema.Literals([\"codex\", \"chatgpt\"]);\n\nexport type ClientRequest__MarketplaceAddParams = {\n  readonly refName?: string | null;\n  readonly source: string;\n  readonly sparsePaths?: ReadonlyArray<string> | null;\n};\nexport const ClientRequest__MarketplaceAddParams = Schema.Struct({\n  refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  source: Schema.String,\n  sparsePaths: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n});\n\nexport type ClientRequest__MarketplaceRemoveParams = { readonly marketplaceName: string };\nexport const ClientRequest__MarketplaceRemoveParams = Schema.Struct({\n  marketplaceName: Schema.String,\n});\n\nexport type ClientRequest__MarketplaceUpgradeParams = { readonly marketplaceName?: string | null };\nexport const ClientRequest__MarketplaceUpgradeParams = Schema.Struct({\n  marketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__McpResourceReadParams = {\n  readonly server: string;\n  readonly threadId?: string | null;\n  readonly uri: string;\n};\nexport const ClientRequest__McpResourceReadParams = Schema.Struct({\n  server: Schema.String,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n});\n\nexport type ClientRequest__McpServerMigration = { readonly name: string };\nexport const ClientRequest__McpServerMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__McpServerOauthLoginParams = {\n  readonly name: string;\n  readonly scopes?: ReadonlyArray<string> | null;\n  readonly threadId?: string | null;\n  readonly timeoutSecs?: number | null;\n};\nexport const ClientRequest__McpServerOauthLoginParams = Schema.Struct({\n  name: Schema.String,\n  scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timeoutSecs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type ClientRequest__McpServerStatusDetail = \"full\" | \"toolsAndAuthOnly\";\nexport const ClientRequest__McpServerStatusDetail = Schema.Literals([\"full\", \"toolsAndAuthOnly\"]);\n\nexport type ClientRequest__McpServerToolCallParams = {\n  readonly _meta?: unknown;\n  readonly arguments?: unknown;\n  readonly server: string;\n  readonly threadId: string;\n  readonly tool: string;\n};\nexport const ClientRequest__McpServerToolCallParams = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  arguments: Schema.optionalKey(Schema.Unknown),\n  server: Schema.String,\n  threadId: Schema.String,\n  tool: Schema.String,\n});\n\nexport type ClientRequest__MergeStrategy = \"replace\" | \"upsert\";\nexport const ClientRequest__MergeStrategy = Schema.Literals([\"replace\", \"upsert\"]);\n\nexport type ClientRequest__MessagePhase = \"commentary\" | \"final_answer\";\nexport const ClientRequest__MessagePhase = Schema.Literals([\"commentary\", \"final_answer\"]).annotate(\n  {\n    description:\n      'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n  },\n);\n\nexport type ClientRequest__ModeKind = \"plan\" | \"default\";\nexport const ClientRequest__ModeKind = Schema.Literals([\"plan\", \"default\"]).annotate({\n  description: \"Initial collaboration mode to use when the TUI starts.\",\n});\n\nexport type ClientRequest__ModelListParams = {\n  readonly cursor?: string | null;\n  readonly includeHidden?: boolean | null;\n  readonly limit?: number | null;\n};\nexport const ClientRequest__ModelListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHidden: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"When true, include models that are hidden from the default picker list.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ModelProviderCapabilitiesReadParams = {};\nexport const ClientRequest__ModelProviderCapabilitiesReadParams = Schema.Struct({});\n\nexport type ClientRequest__PermissionProfileListParams = {\n  readonly cursor?: string | null;\n  readonly cwd?: string | null;\n  readonly limit?: number | null;\n};\nexport const ClientRequest__PermissionProfileListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory to resolve project config layers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to the full result set.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const ClientRequest__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type ClientRequest__PluginListMarketplaceKind =\n  | \"local\"\n  | \"vertical\"\n  | \"workspace-directory\"\n  | \"shared-with-me\"\n  | \"created-by-me-remote\";\nexport const ClientRequest__PluginListMarketplaceKind = Schema.Literals([\n  \"local\",\n  \"vertical\",\n  \"workspace-directory\",\n  \"shared-with-me\",\n  \"created-by-me-remote\",\n]);\n\nexport type ClientRequest__PluginShareCheckoutParams = { readonly remotePluginId: string };\nexport const ClientRequest__PluginShareCheckoutParams = Schema.Struct({\n  remotePluginId: Schema.String,\n});\n\nexport type ClientRequest__PluginShareDeleteParams = { readonly remotePluginId: string };\nexport const ClientRequest__PluginShareDeleteParams = Schema.Struct({\n  remotePluginId: Schema.String,\n});\n\nexport type ClientRequest__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const ClientRequest__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type ClientRequest__PluginShareListParams = {};\nexport const ClientRequest__PluginShareListParams = Schema.Struct({});\n\nexport type ClientRequest__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const ClientRequest__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type ClientRequest__PluginShareTargetRole = \"reader\" | \"editor\";\nexport const ClientRequest__PluginShareTargetRole = Schema.Literals([\"reader\", \"editor\"]);\n\nexport type ClientRequest__PluginShareUpdateDiscoverability = \"UNLISTED\" | \"PRIVATE\" | \"LISTED\";\nexport const ClientRequest__PluginShareUpdateDiscoverability = Schema.Literals([\n  \"UNLISTED\",\n  \"PRIVATE\",\n  \"LISTED\",\n]);\n\nexport type ClientRequest__PluginSkillReadParams = {\n  readonly remoteMarketplaceName: string;\n  readonly remotePluginId: string;\n  readonly skillName: string;\n};\nexport const ClientRequest__PluginSkillReadParams = Schema.Struct({\n  remoteMarketplaceName: Schema.String,\n  remotePluginId: Schema.String,\n  skillName: Schema.String,\n});\n\nexport type ClientRequest__PluginUninstallParams = { readonly pluginId: string };\nexport const ClientRequest__PluginUninstallParams = Schema.Struct({ pluginId: Schema.String });\n\nexport type ClientRequest__PluginsMigration = {\n  readonly marketplaceName: string;\n  readonly pluginNames: ReadonlyArray<string>;\n};\nexport const ClientRequest__PluginsMigration = Schema.Struct({\n  marketplaceName: Schema.String,\n  pluginNames: Schema.Array(Schema.String),\n});\n\nexport type ClientRequest__ReasoningEffort = string;\nexport const ClientRequest__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type ClientRequest__ReasoningItemContent =\n  | { readonly text: string; readonly type: \"reasoning_text\" }\n  | { readonly text: string; readonly type: \"text\" };\nexport const ClientRequest__ReasoningItemContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"reasoning_text\").annotate({\n        title: \"ReasoningTextReasoningItemContentType\",\n      }),\n    }).annotate({ title: \"ReasoningTextReasoningItemContent\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"text\").annotate({ title: \"TextReasoningItemContentType\" }),\n    }).annotate({ title: \"TextReasoningItemContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ReasoningItemReasoningSummary = {\n  readonly text: string;\n  readonly type: \"summary_text\";\n};\nexport const ClientRequest__ReasoningItemReasoningSummary = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"summary_text\").annotate({\n        title: \"SummaryTextReasoningItemReasoningSummaryType\",\n      }),\n    }).annotate({ title: \"SummaryTextReasoningItemReasoningSummary\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const ClientRequest__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type ClientRequest__RequestId = string | number;\nexport const ClientRequest__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type ClientRequest__ResponsesApiWebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"open_page\"; readonly url?: string | null }\n  | {\n      readonly pattern?: string | null;\n      readonly type: \"find_in_page\";\n      readonly url?: string | null;\n    }\n  | { readonly type: \"other\" };\nexport const ClientRequest__ResponsesApiWebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"SearchResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"open_page\").annotate({\n        title: \"OpenPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"find_in_page\").annotate({\n        title: \"FindInPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"OtherResponsesApiWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ReviewDelivery = \"inline\" | \"detached\";\nexport const ClientRequest__ReviewDelivery = Schema.Literals([\"inline\", \"detached\"]);\n\nexport type ClientRequest__ReviewTarget =\n  | { readonly type: \"uncommittedChanges\" }\n  | { readonly branch: string; readonly type: \"baseBranch\" }\n  | { readonly sha: string; readonly title?: string | null; readonly type: \"commit\" }\n  | { readonly instructions: string; readonly type: \"custom\" };\nexport const ClientRequest__ReviewTarget = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"uncommittedChanges\").annotate({\n        title: \"UncommittedChangesReviewTargetType\",\n      }),\n    }).annotate({\n      title: \"UncommittedChangesReviewTarget\",\n      description: \"Review the working tree: staged, unstaged, and untracked files.\",\n    }),\n    Schema.Struct({\n      branch: Schema.String,\n      type: Schema.Literal(\"baseBranch\").annotate({ title: \"BaseBranchReviewTargetType\" }),\n    }).annotate({\n      title: \"BaseBranchReviewTarget\",\n      description: \"Review changes between the current branch and the given base branch.\",\n    }),\n    Schema.Struct({\n      sha: Schema.String,\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Optional human-readable label (e.g., commit subject) for UIs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"commit\").annotate({ title: \"CommitReviewTargetType\" }),\n    }).annotate({\n      title: \"CommitReviewTarget\",\n      description: \"Review the changes introduced by a specific commit.\",\n    }),\n    Schema.Struct({\n      instructions: Schema.String,\n      type: Schema.Literal(\"custom\").annotate({ title: \"CustomReviewTargetType\" }),\n    }).annotate({\n      title: \"CustomReviewTarget\",\n      description: \"Arbitrary instructions, equivalent to the old free-form prompt.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__SandboxMode = \"read-only\" | \"workspace-write\" | \"danger-full-access\";\nexport const ClientRequest__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type ClientRequest__SessionMigration = {\n  readonly cwd: string;\n  readonly path: string;\n  readonly title?: string | null;\n};\nexport const ClientRequest__SessionMigration = Schema.Struct({\n  cwd: Schema.String,\n  path: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__SkillMigration = { readonly name: string };\nexport const ClientRequest__SkillMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__SkillsListParams = {\n  readonly cwds?: ReadonlyArray<string>;\n  readonly forceReload?: boolean;\n};\nexport const ClientRequest__SkillsListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n  forceReload: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass the skills cache and re-scan skills from disk.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__SortDirection = \"asc\" | \"desc\";\nexport const ClientRequest__SortDirection = Schema.Literals([\"asc\", \"desc\"]);\n\nexport type ClientRequest__SubagentMigration = { readonly name: string };\nexport const ClientRequest__SubagentMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const ClientRequest__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ThreadApproveGuardianDeniedActionParams = {\n  readonly event: unknown;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadApproveGuardianDeniedActionParams = Schema.Struct({\n  event: Schema.Unknown.annotate({\n    description: \"Serialized `codex_protocol::protocol::GuardianAssessmentEvent`.\",\n  }),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadArchiveParams = { readonly threadId: string };\nexport const ClientRequest__ThreadArchiveParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadCompactStartParams = { readonly threadId: string };\nexport const ClientRequest__ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadDeleteParams = { readonly threadId: string };\nexport const ClientRequest__ThreadDeleteParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadGoalClearParams = { readonly threadId: string };\nexport const ClientRequest__ThreadGoalClearParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadGoalGetParams = { readonly threadId: string };\nexport const ClientRequest__ThreadGoalGetParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const ClientRequest__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type ClientRequest__ThreadInjectItemsParams = {\n  readonly items: ReadonlyArray<unknown>;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadInjectItemsParams = Schema.Struct({\n  items: Schema.Array(Schema.Unknown).annotate({\n    description: \"Raw Responses API items to append to the thread's model-visible history.\",\n  }),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadListCwdFilter = string | ReadonlyArray<string>;\nexport const ClientRequest__ThreadListCwdFilter = Schema.Union([\n  Schema.String,\n  Schema.Array(Schema.String),\n]);\n\nexport type ClientRequest__ThreadLoadedListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n};\nexport const ClientRequest__ThreadLoadedListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to no limit.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ThreadMetadataGitInfoUpdateParams = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const ClientRequest__ThreadMetadataGitInfoUpdateParams = Schema.Struct({\n  branch: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  originUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sha: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ThreadReadParams = {\n  readonly includeTurns?: boolean;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadReadParams = Schema.Struct({\n  includeTurns: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, include turns and their items from rollout history.\",\n    }),\n  ),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadRollbackParams = {\n  readonly numTurns: number;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadRollbackParams = Schema.Struct({\n  numTurns: Schema.Number.annotate({\n    description:\n      \"The number of turns to drop from the end of the thread. Must be >= 1.\\n\\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.\",\n    format: \"uint32\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  threadId: Schema.String,\n}).annotate({ description: \"DEPRECATED: `thread/rollback` will be removed soon.\" });\n\nexport type ClientRequest__ThreadSetNameParams = {\n  readonly name: string;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadSetNameParams = Schema.Struct({\n  name: Schema.String,\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadShellCommandParams = {\n  readonly command: string;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadShellCommandParams = Schema.Struct({\n  command: Schema.String.annotate({\n    description:\n      \"Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy.\",\n  }),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadSortKey = \"created_at\" | \"updated_at\" | \"recency_at\";\nexport const ClientRequest__ThreadSortKey = Schema.Literals([\n  \"created_at\",\n  \"updated_at\",\n  \"recency_at\",\n]);\n\nexport type ClientRequest__ThreadSource = string;\nexport const ClientRequest__ThreadSource = Schema.String;\n\nexport type ClientRequest__ThreadSourceKind =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"subAgent\"\n  | \"subAgentReview\"\n  | \"subAgentCompact\"\n  | \"subAgentThreadSpawn\"\n  | \"subAgentOther\"\n  | \"unknown\";\nexport const ClientRequest__ThreadSourceKind = Schema.Literals([\n  \"cli\",\n  \"vscode\",\n  \"exec\",\n  \"appServer\",\n  \"subAgent\",\n  \"subAgentReview\",\n  \"subAgentCompact\",\n  \"subAgentThreadSpawn\",\n  \"subAgentOther\",\n  \"unknown\",\n]);\n\nexport type ClientRequest__ThreadStartSource = \"startup\" | \"clear\";\nexport const ClientRequest__ThreadStartSource = Schema.Literals([\"startup\", \"clear\"]);\n\nexport type ClientRequest__ThreadUnarchiveParams = { readonly threadId: string };\nexport const ClientRequest__ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadUnsubscribeParams = { readonly threadId: string };\nexport const ClientRequest__ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__TurnInterruptParams = {\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ClientRequest__TurnInterruptParams = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ClientRequest__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const ClientRequest__TurnItemsView = Schema.Literals([\"notLoaded\", \"summary\", \"full\"]);\n\nexport type ClientRequest__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const ClientRequest__WindowsSandboxSetupMode = Schema.Literals([\"elevated\", \"unelevated\"]);\n\nexport type CommandExecutionRequestApprovalParams__AbsolutePathBuf = string;\nexport const CommandExecutionRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type CommandExecutionRequestApprovalParams__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const CommandExecutionRequestApprovalParams__FileSystemAccessMode = Schema.Literals([\n  \"read\",\n  \"write\",\n  \"deny\",\n]);\n\nexport type CommandExecutionRequestApprovalParams__LegacyAppPathString = string;\nexport const CommandExecutionRequestApprovalParams__LegacyAppPathString = Schema.String;\n\nexport type CommandExecutionRequestApprovalParams__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const CommandExecutionRequestApprovalParams__NetworkApprovalProtocol = Schema.Literals([\n  \"http\",\n  \"https\",\n  \"socks5Tcp\",\n  \"socks5Udp\",\n]);\n\nexport type CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type DynamicToolCallResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const DynamicToolCallResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ExecCommandApprovalParams__ParsedCommand =\n  | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: \"read\" }\n  | { readonly cmd: string; readonly path?: string | null; readonly type: \"list_files\" }\n  | {\n      readonly cmd: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly cmd: string; readonly type: \"unknown\" };\nexport const ExecCommandApprovalParams__ParsedCommand = Schema.Union(\n  [\n    Schema.Struct({\n      cmd: Schema.String,\n      name: Schema.String,\n      path: Schema.String.annotate({\n        description:\n          \"(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.\",\n      }),\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadParsedCommandType\" }),\n    }).annotate({ title: \"ReadParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"list_files\").annotate({ title: \"ListFilesParsedCommandType\" }),\n    }).annotate({ title: \"ListFilesParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchParsedCommandType\" }),\n    }).annotate({ title: \"SearchParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownParsedCommandType\" }),\n    }).annotate({ title: \"UnknownParsedCommand\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ExecCommandApprovalParams__ThreadId = string;\nexport const ExecCommandApprovalParams__ThreadId = Schema.String;\n\nexport type ExecCommandApprovalResponse__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const ExecCommandApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type FileChangeRequestApprovalResponse__FileChangeApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | \"decline\"\n  | \"cancel\";\nexport const FileChangeRequestApprovalResponse__FileChangeApprovalDecision = Schema.Literals([\n  \"accept\",\n  \"acceptForSession\",\n  \"decline\",\n  \"cancel\",\n]);\n\nexport type FuzzyFileSearchResponse__FuzzyFileSearchMatchType = \"file\" | \"directory\";\nexport const FuzzyFileSearchResponse__FuzzyFileSearchMatchType = Schema.Literals([\n  \"file\",\n  \"directory\",\n]);\n\nexport type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType =\n  | \"file\"\n  | \"directory\";\nexport const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType = Schema.Literals([\n  \"file\",\n  \"directory\",\n]);\n\nexport type JSONRPCError__JSONRPCErrorError = {\n  readonly code: number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const JSONRPCError__JSONRPCErrorError = Schema.Struct({\n  code: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  data: Schema.optionalKey(Schema.Unknown),\n  message: Schema.String,\n});\n\nexport type JSONRPCError__RequestId = string | number;\nexport const JSONRPCError__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type JSONRPCMessage__JSONRPCErrorError = {\n  readonly code: number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const JSONRPCMessage__JSONRPCErrorError = Schema.Struct({\n  code: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  data: Schema.optionalKey(Schema.Unknown),\n  message: Schema.String,\n});\n\nexport type JSONRPCMessage__JSONRPCNotification = {\n  readonly method: string;\n  readonly params?: unknown;\n};\nexport const JSONRPCMessage__JSONRPCNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n}).annotate({ description: \"A notification which does not expect a response.\" });\n\nexport type JSONRPCMessage__RequestId = string | number;\nexport const JSONRPCMessage__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type JSONRPCMessage__W3cTraceContext = {\n  readonly traceparent?: string | null;\n  readonly tracestate?: string | null;\n};\nexport const JSONRPCMessage__W3cTraceContext = Schema.Struct({\n  traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type JSONRPCRequest__RequestId = string | number;\nexport const JSONRPCRequest__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type JSONRPCRequest__W3cTraceContext = {\n  readonly traceparent?: string | null;\n  readonly tracestate?: string | null;\n};\nexport const JSONRPCRequest__W3cTraceContext = Schema.Struct({\n  traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type JSONRPCResponse__RequestId = string | number;\nexport const JSONRPCResponse__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type McpServerElicitationRequestParams__McpElicitationArrayType = \"array\";\nexport const McpServerElicitationRequestParams__McpElicitationArrayType = Schema.Literal(\"array\");\n\nexport type McpServerElicitationRequestParams__McpElicitationBooleanType = \"boolean\";\nexport const McpServerElicitationRequestParams__McpElicitationBooleanType =\n  Schema.Literal(\"boolean\");\n\nexport type McpServerElicitationRequestParams__McpElicitationConstOption = {\n  readonly const: string;\n  readonly title: string;\n};\nexport const McpServerElicitationRequestParams__McpElicitationConstOption = Schema.Struct({\n  const: Schema.String,\n  title: Schema.String,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationNumberType = \"number\" | \"integer\";\nexport const McpServerElicitationRequestParams__McpElicitationNumberType = Schema.Literals([\n  \"number\",\n  \"integer\",\n]);\n\nexport type McpServerElicitationRequestParams__McpElicitationObjectType = \"object\";\nexport const McpServerElicitationRequestParams__McpElicitationObjectType = Schema.Literal(\"object\");\n\nexport type McpServerElicitationRequestParams__McpElicitationStringFormat =\n  | \"email\"\n  | \"uri\"\n  | \"date\"\n  | \"date-time\";\nexport const McpServerElicitationRequestParams__McpElicitationStringFormat = Schema.Literals([\n  \"email\",\n  \"uri\",\n  \"date\",\n  \"date-time\",\n]);\n\nexport type McpServerElicitationRequestParams__McpElicitationStringType = \"string\";\nexport const McpServerElicitationRequestParams__McpElicitationStringType = Schema.Literal(\"string\");\n\nexport type McpServerElicitationRequestResponse__McpServerElicitationAction =\n  | \"accept\"\n  | \"decline\"\n  | \"cancel\";\nexport const McpServerElicitationRequestResponse__McpServerElicitationAction = Schema.Literals([\n  \"accept\",\n  \"decline\",\n  \"cancel\",\n]);\n\nexport type PermissionsRequestApprovalParams__AbsolutePathBuf = string;\nexport const PermissionsRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type PermissionsRequestApprovalParams__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const PermissionsRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type PermissionsRequestApprovalParams__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const PermissionsRequestApprovalParams__FileSystemAccessMode = Schema.Literals([\n  \"read\",\n  \"write\",\n  \"deny\",\n]);\n\nexport type PermissionsRequestApprovalParams__LegacyAppPathString = string;\nexport const PermissionsRequestApprovalParams__LegacyAppPathString = Schema.String;\n\nexport type PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type PermissionsRequestApprovalResponse__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const PermissionsRequestApprovalResponse__FileSystemAccessMode = Schema.Literals([\n  \"read\",\n  \"write\",\n  \"deny\",\n]);\n\nexport type PermissionsRequestApprovalResponse__LegacyAppPathString = string;\nexport const PermissionsRequestApprovalResponse__LegacyAppPathString = Schema.String;\n\nexport type ServerNotification__AbsolutePathBuf = string;\nexport const ServerNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type ServerNotification__AccountLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly loginId?: string | null;\n  readonly success: boolean;\n};\nexport const ServerNotification__AccountLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  success: Schema.Boolean,\n});\n\nexport type ServerNotification__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const ServerNotification__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type ServerNotification__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const ServerNotification__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type ServerNotification__AgentMessageDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__AgentMessageDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__AgentPath = string;\nexport const ServerNotification__AgentPath = Schema.String;\n\nexport type ServerNotification__AppBranding = {\n  readonly category?: string | null;\n  readonly developer?: string | null;\n  readonly isDiscoverableApp: boolean;\n  readonly privacyPolicy?: string | null;\n  readonly termsOfService?: string | null;\n  readonly website?: string | null;\n};\nexport const ServerNotification__AppBranding = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isDiscoverableApp: Schema.Boolean,\n  privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type ServerNotification__AppReview = { readonly status: string };\nexport const ServerNotification__AppReview = Schema.Struct({ status: Schema.String });\n\nexport type ServerNotification__AppScreenshot = {\n  readonly fileId?: string | null;\n  readonly url?: string | null;\n  readonly userPrompt: string;\n};\nexport const ServerNotification__AppScreenshot = Schema.Struct({\n  fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  userPrompt: Schema.String,\n});\n\nexport type ServerNotification__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const ServerNotification__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type ServerNotification__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const ServerNotification__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__AuthMode =\n  | \"apikey\"\n  | \"chatgpt\"\n  | \"chatgptAuthTokens\"\n  | \"headers\"\n  | \"agentIdentity\"\n  | \"personalAccessToken\"\n  | \"bedrockApiKey\";\nexport const ServerNotification__AuthMode = Schema.Literals([\n  \"apikey\",\n  \"chatgpt\",\n  \"chatgptAuthTokens\",\n  \"headers\",\n  \"agentIdentity\",\n  \"personalAccessToken\",\n  \"bedrockApiKey\",\n]).annotate({ description: \"Authentication mode for OpenAI-backed providers.\" });\n\nexport type ServerNotification__AutoReviewDecisionSource = \"agent\";\nexport const ServerNotification__AutoReviewDecisionSource = Schema.Literal(\"agent\").annotate({\n  description: \"[UNSTABLE] Source that produced a terminal approval auto-review decision.\",\n});\n\nexport type ServerNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const ServerNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type ServerNotification__CommandExecOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processId: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const ServerNotification__CommandExecOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `command/exec/outputDelta` notifications.\",\n  }),\n}).annotate({\n  description:\n    \"Base64-encoded output chunk emitted for a streaming `command/exec` request.\\n\\nThese notifications are connection-scoped. If the originating connection closes, the server terminates the process.\",\n});\n\nexport type ServerNotification__CommandExecutionOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__CommandExecutionOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const ServerNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type ServerNotification__ContextCompactedNotification = {\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ContextCompactedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ description: \"Deprecated: Use `ContextCompaction` item type instead.\" });\n\nexport type ServerNotification__CreditsSnapshot = {\n  readonly balance?: string | null;\n  readonly hasCredits: boolean;\n  readonly unlimited: boolean;\n};\nexport const ServerNotification__CreditsSnapshot = Schema.Struct({\n  balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hasCredits: Schema.Boolean,\n  unlimited: Schema.Boolean,\n});\n\nexport type ServerNotification__DeprecationNoticeNotification = {\n  readonly details?: string | null;\n  readonly summary: string;\n};\nexport const ServerNotification__DeprecationNoticeNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional extra guidance, such as migration steps or rationale.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of what is deprecated.\" }),\n});\n\nexport type ServerNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const ServerNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const ServerNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type ServerNotification__EnvironmentConnectionNotification = {\n  readonly environmentId: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__EnvironmentConnectionNotification = Schema.Struct({\n  environmentId: Schema.String,\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const ServerNotification__ExternalAgentConfigMigrationItemType = Schema.Literals([\n  \"AGENTS_MD\",\n  \"CONFIG\",\n  \"SKILLS\",\n  \"PLUGINS\",\n  \"MCP_SERVER_CONFIG\",\n  \"SUBAGENTS\",\n  \"HOOKS\",\n  \"COMMANDS\",\n  \"MEMORY\",\n  \"SESSIONS\",\n]);\n\nexport type ServerNotification__FileChangeOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__FileChangeOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"Deprecated legacy notification for `apply_patch` textual output.\\n\\nThe server no longer emits this notification.\",\n});\n\nexport type ServerNotification__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const ServerNotification__FileSystemAccessMode = Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type ServerNotification__FuzzyFileSearchMatchType = \"file\" | \"directory\";\nexport const ServerNotification__FuzzyFileSearchMatchType = Schema.Literals([\"file\", \"directory\"]);\n\nexport type ServerNotification__FuzzyFileSearchSessionCompletedNotification = {\n  readonly sessionId: string;\n};\nexport const ServerNotification__FuzzyFileSearchSessionCompletedNotification = Schema.Struct({\n  sessionId: Schema.String,\n});\n\nexport type ServerNotification__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const ServerNotification__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__GuardianApprovalReviewStatus =\n  | \"inProgress\"\n  | \"approved\"\n  | \"denied\"\n  | \"timedOut\"\n  | \"aborted\";\nexport const ServerNotification__GuardianApprovalReviewStatus = Schema.Literals([\n  \"inProgress\",\n  \"approved\",\n  \"denied\",\n  \"timedOut\",\n  \"aborted\",\n]).annotate({ description: \"[UNSTABLE] Lifecycle state for an approval auto-review.\" });\n\nexport type ServerNotification__GuardianCommandSource = \"shell\" | \"unifiedExec\";\nexport const ServerNotification__GuardianCommandSource = Schema.Literals([\"shell\", \"unifiedExec\"]);\n\nexport type ServerNotification__GuardianRiskLevel = \"low\" | \"medium\" | \"high\" | \"critical\";\nexport const ServerNotification__GuardianRiskLevel = Schema.Literals([\n  \"low\",\n  \"medium\",\n  \"high\",\n  \"critical\",\n]).annotate({ description: \"[UNSTABLE] Risk level assigned by approval auto-review.\" });\n\nexport type ServerNotification__GuardianUserAuthorization = \"unknown\" | \"low\" | \"medium\" | \"high\";\nexport const ServerNotification__GuardianUserAuthorization = Schema.Literals([\n  \"unknown\",\n  \"low\",\n  \"medium\",\n  \"high\",\n]).annotate({ description: \"[UNSTABLE] Authorization level assigned by approval auto-review.\" });\n\nexport type ServerNotification__GuardianWarningNotification = {\n  readonly message: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__GuardianWarningNotification = Schema.Struct({\n  message: Schema.String.annotate({\n    description: \"Concise guardian warning message for the user.\",\n  }),\n  threadId: Schema.String.annotate({ description: \"Thread target for the guardian warning.\" }),\n});\n\nexport type ServerNotification__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const ServerNotification__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type ServerNotification__HookExecutionMode = \"sync\" | \"async\";\nexport const ServerNotification__HookExecutionMode = Schema.Literals([\"sync\", \"async\"]);\n\nexport type ServerNotification__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const ServerNotification__HookHandlerType = Schema.Literals([\"command\", \"prompt\", \"agent\"]);\n\nexport type ServerNotification__HookOutputEntryKind =\n  | \"warning\"\n  | \"stop\"\n  | \"feedback\"\n  | \"context\"\n  | \"error\";\nexport const ServerNotification__HookOutputEntryKind = Schema.Literals([\n  \"warning\",\n  \"stop\",\n  \"feedback\",\n  \"context\",\n  \"error\",\n]);\n\nexport type ServerNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const ServerNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type ServerNotification__HookRunStatus =\n  | \"running\"\n  | \"completed\"\n  | \"failed\"\n  | \"blocked\"\n  | \"stopped\";\nexport const ServerNotification__HookRunStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"failed\",\n  \"blocked\",\n  \"stopped\",\n]);\n\nexport type ServerNotification__HookScope = \"thread\" | \"turn\";\nexport const ServerNotification__HookScope = Schema.Literals([\"thread\", \"turn\"]);\n\nexport type ServerNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const ServerNotification__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type ServerNotification__LegacyAppPathString = string;\nexport const ServerNotification__LegacyAppPathString = Schema.String;\n\nexport type ServerNotification__McpServerOauthLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly name: string;\n  readonly success: boolean;\n  readonly threadId?: string | null;\n};\nexport const ServerNotification__McpServerOauthLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  success: Schema.Boolean,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__McpServerStartupFailureReason = \"reauthenticationRequired\";\nexport const ServerNotification__McpServerStartupFailureReason = Schema.Literal(\n  \"reauthenticationRequired\",\n);\n\nexport type ServerNotification__McpServerStartupState =\n  | \"starting\"\n  | \"ready\"\n  | \"failed\"\n  | \"cancelled\";\nexport const ServerNotification__McpServerStartupState = Schema.Literals([\n  \"starting\",\n  \"ready\",\n  \"failed\",\n  \"cancelled\",\n]);\n\nexport type ServerNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const ServerNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__McpToolCallError = { readonly message: string };\nexport const ServerNotification__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type ServerNotification__McpToolCallProgressNotification = {\n  readonly itemId: string;\n  readonly message: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__McpToolCallProgressNotification = Schema.Struct({\n  itemId: Schema.String,\n  message: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const ServerNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type ServerNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const ServerNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type ServerNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const ServerNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type ServerNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const ServerNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type ServerNotification__ModeKind = \"plan\" | \"default\";\nexport const ServerNotification__ModeKind = Schema.Literals([\"plan\", \"default\"]).annotate({\n  description: \"Initial collaboration mode to use when the TUI starts.\",\n});\n\nexport type ServerNotification__ModelRerouteReason = \"highRiskCyberActivity\";\nexport const ServerNotification__ModelRerouteReason = Schema.Literal(\"highRiskCyberActivity\");\n\nexport type ServerNotification__ModelSafetyBufferingUpdatedNotification = {\n  readonly fasterModel?: string | null;\n  readonly model: string;\n  readonly reasons: ReadonlyArray<string>;\n  readonly showBufferingUi: boolean;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly useCases: ReadonlyArray<string>;\n};\nexport const ServerNotification__ModelSafetyBufferingUpdatedNotification = Schema.Struct({\n  fasterModel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasons: Schema.Array(Schema.String),\n  showBufferingUi: Schema.Boolean,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  useCases: Schema.Array(Schema.String),\n});\n\nexport type ServerNotification__ModelVerification = \"trustedAccessForCyber\";\nexport const ServerNotification__ModelVerification = Schema.Literal(\"trustedAccessForCyber\");\n\nexport type ServerNotification__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const ServerNotification__NetworkApprovalProtocol = Schema.Literals([\n  \"http\",\n  \"https\",\n  \"socks5Tcp\",\n  \"socks5Udp\",\n]);\n\nexport type ServerNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const ServerNotification__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type ServerNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const ServerNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type ServerNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const ServerNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const ServerNotification__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type ServerNotification__PlanDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__PlanDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.\",\n});\n\nexport type ServerNotification__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const ServerNotification__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type ServerNotification__ProcessExitedNotification = {\n  readonly exitCode: number;\n  readonly processHandle: string;\n  readonly stderr: string;\n  readonly stderrCapReached: boolean;\n  readonly stdout: string;\n  readonly stdoutCapReached: boolean;\n};\nexport const ServerNotification__ProcessExitedNotification = Schema.Struct({\n  exitCode: Schema.Number.annotate({ description: \"Process exit code.\", format: \"int32\" }).check(\n    Schema.isInt(),\n  ),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stderr: Schema.String.annotate({\n    description:\n      \"Buffered stderr capture.\\n\\nEmpty when stderr was streamed via `process/outputDelta`.\",\n  }),\n  stderrCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stderr reached `outputBytesCap`.\\n\\nIn streaming mode, stderr is empty and cap state is also reported on the final stderr `process/outputDelta` notification.\",\n  }),\n  stdout: Schema.String.annotate({\n    description:\n      \"Buffered stdout capture.\\n\\nEmpty when stdout was streamed via `process/outputDelta`.\",\n  }),\n  stdoutCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stdout reached `outputBytesCap`.\\n\\nIn streaming mode, stdout is empty and cap state is also reported on the final stdout `process/outputDelta` notification.\",\n  }),\n}).annotate({ description: \"Final process exit notification for `process/spawn`.\" });\n\nexport type ServerNotification__ProcessOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processHandle: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const ServerNotification__ProcessOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"True on the final streamed chunk for this stream when output was truncated by `outputBytesCap`.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `process/outputDelta` notifications.\",\n  }),\n}).annotate({\n  description: \"Base64-encoded output chunk emitted for a streaming `process/spawn` request.\",\n});\n\nexport type ServerNotification__RateLimitReachedType =\n  | \"rate_limit_reached\"\n  | \"workspace_owner_credits_depleted\"\n  | \"workspace_member_credits_depleted\"\n  | \"workspace_owner_usage_limit_reached\"\n  | \"workspace_member_usage_limit_reached\";\nexport const ServerNotification__RateLimitReachedType = Schema.Literals([\n  \"rate_limit_reached\",\n  \"workspace_owner_credits_depleted\",\n  \"workspace_member_credits_depleted\",\n  \"workspace_owner_usage_limit_reached\",\n  \"workspace_member_usage_limit_reached\",\n]);\n\nexport type ServerNotification__RateLimitWindow = {\n  readonly resetsAt?: number | null;\n  readonly usedPercent: number;\n  readonly windowDurationMins?: number | null;\n};\nexport const ServerNotification__RateLimitWindow = Schema.Struct({\n  resetsAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  usedPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  windowDurationMins: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type ServerNotification__RealtimeConversationVersion = \"v1\" | \"v2\" | \"v3\";\nexport const ServerNotification__RealtimeConversationVersion = Schema.Literals([\"v1\", \"v2\", \"v3\"]);\n\nexport type ServerNotification__ReasoningEffort = string;\nexport const ServerNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type ServerNotification__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const ServerNotification__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type ServerNotification__ReasoningSummaryPartAddedNotification = {\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ReasoningSummaryPartAddedNotification = Schema.Struct({\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ReasoningSummaryTextDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ReasoningSummaryTextDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ReasoningTextDeltaNotification = {\n  readonly contentIndex: number;\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ReasoningTextDeltaNotification = Schema.Struct({\n  contentIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__RemoteControlConnectionStatus =\n  | \"disabled\"\n  | \"connecting\"\n  | \"connected\"\n  | \"errored\";\nexport const ServerNotification__RemoteControlConnectionStatus = Schema.Literals([\n  \"disabled\",\n  \"connecting\",\n  \"connected\",\n  \"errored\",\n]);\n\nexport type ServerNotification__RequestId = string | number;\nexport const ServerNotification__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type ServerNotification__SkillsChangedNotification = {};\nexport const ServerNotification__SkillsChangedNotification = Schema.Struct({}).annotate({\n  description:\n    \"Notification emitted when watched local skill files change.\\n\\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.\",\n});\n\nexport type ServerNotification__SpendControlLimitSnapshot = {\n  readonly limit: string;\n  readonly remainingPercent: number;\n  readonly resetsAt: number;\n  readonly used: string;\n};\nexport const ServerNotification__SpendControlLimitSnapshot = Schema.Struct({\n  limit: Schema.String,\n  remainingPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  resetsAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  used: Schema.String,\n});\n\nexport type ServerNotification__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const ServerNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type ServerNotification__TerminalInteractionNotification = {\n  readonly itemId: string;\n  readonly processId: string;\n  readonly stdin: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TerminalInteractionNotification = Schema.Struct({\n  itemId: Schema.String,\n  processId: Schema.String,\n  stdin: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const ServerNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__TextPosition = { readonly column: number; readonly line: number };\nexport const ServerNotification__TextPosition = Schema.Struct({\n  column: Schema.Number.annotate({\n    description: \"1-based column number (in Unicode scalar values).\",\n    format: \"uint\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  line: Schema.Number.annotate({ description: \"1-based line number.\", format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type ServerNotification__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const ServerNotification__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type ServerNotification__ThreadArchivedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadArchivedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadClosedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadClosedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadDeletedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadDeletedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadGoalClearedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadGoalClearedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const ServerNotification__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type ServerNotification__ThreadId = string;\nexport const ServerNotification__ThreadId = Schema.String;\n\nexport type ServerNotification__ThreadNameUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadName?: string | null;\n};\nexport const ServerNotification__ThreadNameUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__ThreadRealtimeAudioChunk = {\n  readonly data: string;\n  readonly itemId?: string | null;\n  readonly numChannels: number;\n  readonly sampleRate: number;\n  readonly samplesPerChannel?: number | null;\n};\nexport const ServerNotification__ThreadRealtimeAudioChunk = Schema.Struct({\n  data: Schema.String,\n  itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  numChannels: Schema.Number.annotate({ format: \"uint16\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  sampleRate: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  samplesPerChannel: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - thread realtime audio chunk.\" });\n\nexport type ServerNotification__ThreadRealtimeClosedNotification = {\n  readonly reason?: string | null;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeClosedNotification = Schema.Struct({\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - emitted when thread realtime transport closes.\" });\n\nexport type ServerNotification__ThreadRealtimeErrorNotification = {\n  readonly message: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeErrorNotification = Schema.Struct({\n  message: Schema.String,\n  threadId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - emitted when thread realtime encounters an error.\" });\n\nexport type ServerNotification__ThreadRealtimeItemAddedNotification = {\n  readonly item: unknown;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeItemAddedNotification = Schema.Struct({\n  item: Schema.Unknown,\n  threadId: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.\",\n});\n\nexport type ServerNotification__ThreadRealtimeSdpNotification = {\n  readonly sdp: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeSdpNotification = Schema.Struct({\n  sdp: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.\",\n});\n\nexport type ServerNotification__ThreadRealtimeTranscriptDeltaNotification = {\n  readonly delta: string;\n  readonly role: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeTranscriptDeltaNotification = Schema.Struct({\n  delta: Schema.String.annotate({ description: \"Live transcript delta from the realtime event.\" }),\n  role: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  description:\n    \"EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.\",\n});\n\nexport type ServerNotification__ThreadRealtimeTranscriptDoneNotification = {\n  readonly role: string;\n  readonly text: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeTranscriptDoneNotification = Schema.Struct({\n  role: Schema.String,\n  text: Schema.String.annotate({ description: \"Final complete text for the transcript part.\" }),\n  threadId: Schema.String,\n}).annotate({\n  description:\n    \"EXPERIMENTAL - final transcript text emitted when realtime completes a transcript part.\",\n});\n\nexport type ServerNotification__ThreadSource = string;\nexport const ServerNotification__ThreadSource = Schema.String;\n\nexport type ServerNotification__ThreadUnarchivedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadUnarchivedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__TokenUsageBreakdown = {\n  readonly cacheWriteInputTokens?: number;\n  readonly cachedInputTokens: number;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly reasoningOutputTokens: number;\n  readonly totalTokens: number;\n};\nexport const ServerNotification__TokenUsageBreakdown = Schema.Struct({\n  cacheWriteInputTokens: Schema.optionalKey(\n    Schema.Number.annotate({ default: 0, format: \"int64\" }).check(Schema.isInt()),\n  ),\n  cachedInputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  inputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  outputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  reasoningOutputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  totalTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type ServerNotification__TurnDiffUpdatedNotification = {\n  readonly diff: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TurnDiffUpdatedNotification = Schema.Struct({\n  diff: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.\",\n});\n\nexport type ServerNotification__TurnModerationMetadataNotification = {\n  readonly metadata: unknown;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TurnModerationMetadataNotification = Schema.Struct({\n  metadata: Schema.Unknown,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__TurnPlanStepStatus = \"pending\" | \"inProgress\" | \"completed\";\nexport const ServerNotification__TurnPlanStepStatus = Schema.Literals([\n  \"pending\",\n  \"inProgress\",\n  \"completed\",\n]);\n\nexport type ServerNotification__TurnStatus = \"completed\" | \"interrupted\" | \"failed\" | \"inProgress\";\nexport const ServerNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type ServerNotification__WarningNotification = {\n  readonly message: string;\n  readonly threadId?: string | null;\n};\nexport const ServerNotification__WarningNotification = Schema.Struct({\n  message: Schema.String.annotate({ description: \"Concise warning message for the user.\" }),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional thread target when the warning applies to a specific thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const ServerNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const ServerNotification__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type ServerNotification__WindowsWorldWritableWarningNotification = {\n  readonly extraCount: number;\n  readonly failedScan: boolean;\n  readonly samplePaths: ReadonlyArray<string>;\n};\nexport const ServerNotification__WindowsWorldWritableWarningNotification = Schema.Struct({\n  extraCount: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  failedScan: Schema.Boolean,\n  samplePaths: Schema.Array(Schema.String),\n});\n\nexport type ServerRequest__AbsolutePathBuf = string;\nexport const ServerRequest__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type ServerRequest__AdditionalNetworkPermissions = { readonly enabled?: boolean | null };\nexport const ServerRequest__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type ServerRequest__AttestationGenerateParams = {};\nexport const ServerRequest__AttestationGenerateParams = Schema.Struct({});\n\nexport type ServerRequest__ChatgptAuthTokensRefreshReason = \"unauthorized\";\nexport const ServerRequest__ChatgptAuthTokensRefreshReason = Schema.Literal(\"unauthorized\");\n\nexport type ServerRequest__DynamicToolCallParams = {\n  readonly arguments: unknown;\n  readonly callId: string;\n  readonly namespace?: string | null;\n  readonly threadId: string;\n  readonly tool: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__DynamicToolCallParams = Schema.Struct({\n  arguments: Schema.Unknown,\n  callId: Schema.String,\n  namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  tool: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__FileChange =\n  | { readonly content: string; readonly type: \"add\" }\n  | { readonly content: string; readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\"; readonly unified_diff: string };\nexport const ServerRequest__FileChange = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"add\").annotate({ title: \"AddFileChangeType\" }),\n    }).annotate({ title: \"AddFileChange\" }),\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeleteFileChangeType\" }),\n    }).annotate({ title: \"DeleteFileChange\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdateFileChangeType\" }),\n      unified_diff: Schema.String,\n    }).annotate({ title: \"UpdateFileChange\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__FileChangeRequestApprovalParams = {\n  readonly grantRoot?: string | null;\n  readonly itemId: string;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__FileChangeRequestApprovalParams = Schema.Struct({\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const ServerRequest__FileSystemAccessMode = Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type ServerRequest__LegacyAppPathString = string;\nexport const ServerRequest__LegacyAppPathString = Schema.String;\n\nexport type ServerRequest__McpElicitationArrayType = \"array\";\nexport const ServerRequest__McpElicitationArrayType = Schema.Literal(\"array\");\n\nexport type ServerRequest__McpElicitationBooleanType = \"boolean\";\nexport const ServerRequest__McpElicitationBooleanType = Schema.Literal(\"boolean\");\n\nexport type ServerRequest__McpElicitationConstOption = {\n  readonly const: string;\n  readonly title: string;\n};\nexport const ServerRequest__McpElicitationConstOption = Schema.Struct({\n  const: Schema.String,\n  title: Schema.String,\n});\n\nexport type ServerRequest__McpElicitationNumberType = \"number\" | \"integer\";\nexport const ServerRequest__McpElicitationNumberType = Schema.Literals([\"number\", \"integer\"]);\n\nexport type ServerRequest__McpElicitationObjectType = \"object\";\nexport const ServerRequest__McpElicitationObjectType = Schema.Literal(\"object\");\n\nexport type ServerRequest__McpElicitationStringFormat = \"email\" | \"uri\" | \"date\" | \"date-time\";\nexport const ServerRequest__McpElicitationStringFormat = Schema.Literals([\n  \"email\",\n  \"uri\",\n  \"date\",\n  \"date-time\",\n]);\n\nexport type ServerRequest__McpElicitationStringType = \"string\";\nexport const ServerRequest__McpElicitationStringType = Schema.Literal(\"string\");\n\nexport type ServerRequest__NetworkApprovalProtocol = \"http\" | \"https\" | \"socks5Tcp\" | \"socks5Udp\";\nexport const ServerRequest__NetworkApprovalProtocol = Schema.Literals([\n  \"http\",\n  \"https\",\n  \"socks5Tcp\",\n  \"socks5Udp\",\n]);\n\nexport type ServerRequest__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const ServerRequest__NetworkPolicyRuleAction = Schema.Literals([\"allow\", \"deny\"]);\n\nexport type ServerRequest__ParsedCommand =\n  | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: \"read\" }\n  | { readonly cmd: string; readonly path?: string | null; readonly type: \"list_files\" }\n  | {\n      readonly cmd: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly cmd: string; readonly type: \"unknown\" };\nexport const ServerRequest__ParsedCommand = Schema.Union(\n  [\n    Schema.Struct({\n      cmd: Schema.String,\n      name: Schema.String,\n      path: Schema.String.annotate({\n        description:\n          \"(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.\",\n      }),\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadParsedCommandType\" }),\n    }).annotate({ title: \"ReadParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"list_files\").annotate({ title: \"ListFilesParsedCommandType\" }),\n    }).annotate({ title: \"ListFilesParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchParsedCommandType\" }),\n    }).annotate({ title: \"SearchParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownParsedCommandType\" }),\n    }).annotate({ title: \"UnknownParsedCommand\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__RequestId = string | number;\nexport const ServerRequest__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type ServerRequest__ThreadId = string;\nexport const ServerRequest__ThreadId = Schema.String;\n\nexport type ServerRequest__ToolRequestUserInputOption = {\n  readonly description: string;\n  readonly label: string;\n};\nexport const ServerRequest__ToolRequestUserInputOption = Schema.Struct({\n  description: Schema.String,\n  label: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Defines a single selectable option for request_user_input.\",\n});\n\nexport type ToolRequestUserInputParams__ToolRequestUserInputOption = {\n  readonly description: string;\n  readonly label: string;\n};\nexport const ToolRequestUserInputParams__ToolRequestUserInputOption = Schema.Struct({\n  description: Schema.String,\n  label: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Defines a single selectable option for request_user_input.\",\n});\n\nexport type ToolRequestUserInputResponse__ToolRequestUserInputAnswer = {\n  readonly answers: ReadonlyArray<string>;\n};\nexport const ToolRequestUserInputResponse__ToolRequestUserInputAnswer = Schema.Struct({\n  answers: Schema.Array(Schema.String),\n}).annotate({\n  description: \"EXPERIMENTAL. Captures a user's answer to a request_user_input question.\",\n});\n\nexport type V1InitializeParams__ClientInfo = {\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n};\nexport const V1InitializeParams__ClientInfo = Schema.Struct({\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  version: Schema.String,\n});\n\nexport type V1InitializeParams__InitializeCapabilities = {\n  readonly experimentalApi?: boolean;\n  readonly mcpServerOpenaiFormElicitation?: boolean;\n  readonly optOutNotificationMethods?: ReadonlyArray<string> | null;\n  readonly requestAttestation?: boolean;\n};\nexport const V1InitializeParams__InitializeCapabilities = Schema.Struct({\n  experimentalApi: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into receiving experimental API methods and fields.\",\n      default: false,\n    }),\n  ),\n  mcpServerOpenaiFormElicitation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Allow downstream MCP servers to request OpenAI extended form elicitations.\",\n    }),\n  ),\n  optOutNotificationMethods: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Exact notification method names that should be suppressed for this connection (for example `thread/started`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  requestAttestation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into `attestation/generate` requests for upstream `x-oai-attestation`.\",\n      default: false,\n    }),\n  ),\n}).annotate({ description: \"Client-declared capabilities negotiated during initialize.\" });\n\nexport type V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = {\n  readonly balance?: string | null;\n  readonly hasCredits: boolean;\n  readonly unlimited: boolean;\n};\nexport const V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = Schema.Struct({\n  balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hasCredits: Schema.Boolean,\n  unlimited: Schema.Boolean,\n});\n\nexport type V2AccountRateLimitsUpdatedNotification__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2AccountRateLimitsUpdatedNotification__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2AccountRateLimitsUpdatedNotification__RateLimitReachedType =\n  | \"rate_limit_reached\"\n  | \"workspace_owner_credits_depleted\"\n  | \"workspace_member_credits_depleted\"\n  | \"workspace_owner_usage_limit_reached\"\n  | \"workspace_member_usage_limit_reached\";\nexport const V2AccountRateLimitsUpdatedNotification__RateLimitReachedType = Schema.Literals([\n  \"rate_limit_reached\",\n  \"workspace_owner_credits_depleted\",\n  \"workspace_member_credits_depleted\",\n  \"workspace_owner_usage_limit_reached\",\n  \"workspace_member_usage_limit_reached\",\n]);\n\nexport type V2AccountRateLimitsUpdatedNotification__RateLimitWindow = {\n  readonly resetsAt?: number | null;\n  readonly usedPercent: number;\n  readonly windowDurationMins?: number | null;\n};\nexport const V2AccountRateLimitsUpdatedNotification__RateLimitWindow = Schema.Struct({\n  resetsAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  usedPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  windowDurationMins: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot = {\n  readonly limit: string;\n  readonly remainingPercent: number;\n  readonly resetsAt: number;\n  readonly used: string;\n};\nexport const V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot = Schema.Struct({\n  limit: Schema.String,\n  remainingPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  resetsAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  used: Schema.String,\n});\n\nexport type V2AccountUpdatedNotification__AuthMode =\n  | \"apikey\"\n  | \"chatgpt\"\n  | \"chatgptAuthTokens\"\n  | \"headers\"\n  | \"agentIdentity\"\n  | \"personalAccessToken\"\n  | \"bedrockApiKey\";\nexport const V2AccountUpdatedNotification__AuthMode = Schema.Literals([\n  \"apikey\",\n  \"chatgpt\",\n  \"chatgptAuthTokens\",\n  \"headers\",\n  \"agentIdentity\",\n  \"personalAccessToken\",\n  \"bedrockApiKey\",\n]).annotate({ description: \"Authentication mode for OpenAI-backed providers.\" });\n\nexport type V2AccountUpdatedNotification__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2AccountUpdatedNotification__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2AppListUpdatedNotification__AppBranding = {\n  readonly category?: string | null;\n  readonly developer?: string | null;\n  readonly isDiscoverableApp: boolean;\n  readonly privacyPolicy?: string | null;\n  readonly termsOfService?: string | null;\n  readonly website?: string | null;\n};\nexport const V2AppListUpdatedNotification__AppBranding = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isDiscoverableApp: Schema.Boolean,\n  privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2AppListUpdatedNotification__AppReview = { readonly status: string };\nexport const V2AppListUpdatedNotification__AppReview = Schema.Struct({ status: Schema.String });\n\nexport type V2AppListUpdatedNotification__AppScreenshot = {\n  readonly fileId?: string | null;\n  readonly url?: string | null;\n  readonly userPrompt: string;\n};\nexport const V2AppListUpdatedNotification__AppScreenshot = Schema.Struct({\n  fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  userPrompt: Schema.String,\n});\n\nexport type V2AppsInstalledResponse__InstalledApp = {\n  readonly callable: boolean;\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly runtimeName?: string | null;\n};\nexport const V2AppsInstalledResponse__InstalledApp = Schema.Struct({\n  callable: Schema.Boolean.annotate({\n    description:\n      \"Whether the connector is enabled and has a non-synthetic, model-visible tool allowed by effective MCP and app/tool policy in the committed runtime snapshot.\",\n  }),\n  enabled: Schema.Boolean.annotate({\n    description:\n      \"Effective enabled state after applying global, workspace, local, and managed configuration at read time.\",\n  }),\n  id: Schema.String,\n  runtimeName: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Best-effort name carried by the runtime tool catalog. Canonical app metadata remains owned by `app/read`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Installed connector runtime state.\" });\n\nexport type V2AppsListResponse__AppBranding = {\n  readonly category?: string | null;\n  readonly developer?: string | null;\n  readonly isDiscoverableApp: boolean;\n  readonly privacyPolicy?: string | null;\n  readonly termsOfService?: string | null;\n  readonly website?: string | null;\n};\nexport const V2AppsListResponse__AppBranding = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isDiscoverableApp: Schema.Boolean,\n  privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2AppsListResponse__AppReview = { readonly status: string };\nexport const V2AppsListResponse__AppReview = Schema.Struct({ status: Schema.String });\n\nexport type V2AppsListResponse__AppScreenshot = {\n  readonly fileId?: string | null;\n  readonly url?: string | null;\n  readonly userPrompt: string;\n};\nexport const V2AppsListResponse__AppScreenshot = Schema.Struct({\n  fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  userPrompt: Schema.String,\n});\n\nexport type V2AppsReadResponse__AppToolSummary = {\n  readonly description: string;\n  readonly name: string;\n  readonly title?: string | null;\n};\nexport const V2AppsReadResponse__AppToolSummary = Schema.Struct({\n  description: Schema.String,\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - metadata returned by app/read.\" });\n\nexport type V2CancelLoginAccountResponse__CancelLoginAccountStatus = \"canceled\" | \"notFound\";\nexport const V2CancelLoginAccountResponse__CancelLoginAccountStatus = Schema.Literals([\n  \"canceled\",\n  \"notFound\",\n]);\n\nexport type V2CommandExecParams__AbsolutePathBuf = string;\nexport const V2CommandExecParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2CommandExecParams__CommandExecTerminalSize = {\n  readonly cols: number;\n  readonly rows: number;\n};\nexport const V2CommandExecParams__CommandExecTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" });\n\nexport type V2ConfigBatchWriteParams__MergeStrategy = \"replace\" | \"upsert\";\nexport const V2ConfigBatchWriteParams__MergeStrategy = Schema.Literals([\"replace\", \"upsert\"]);\n\nexport type V2ConfigReadResponse__AbsolutePathBuf = string;\nexport const V2ConfigReadResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ConfigReadResponse__AnalyticsConfig = {\n  readonly enabled?: boolean | null;\n  readonly [x: string]: unknown;\n};\nexport const V2ConfigReadResponse__AnalyticsConfig = Schema.StructWithRest(\n  Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) }),\n  [Schema.Record(Schema.String, Schema.Unknown)],\n);\n\nexport type V2ConfigReadResponse__AppToolApproval = \"auto\" | \"prompt\" | \"writes\" | \"approve\";\nexport const V2ConfigReadResponse__AppToolApproval = Schema.Literals([\n  \"auto\",\n  \"prompt\",\n  \"writes\",\n  \"approve\",\n]);\n\nexport type V2ConfigReadResponse__AppToolsConfig = {};\nexport const V2ConfigReadResponse__AppToolsConfig = Schema.Struct({});\n\nexport type V2ConfigReadResponse__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ConfigReadResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ConfigReadResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ConfigReadResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigReadResponse__AutoCompactTokenLimitScope = \"total\" | \"body_after_prefix\";\nexport const V2ConfigReadResponse__AutoCompactTokenLimitScope = Schema.Literals([\n  \"total\",\n  \"body_after_prefix\",\n]).annotate({\n  description:\n    \"Selects which part of the active context is charged against `model_auto_compact_token_limit`.\",\n});\n\nexport type V2ConfigReadResponse__ForcedChatgptWorkspaceIds = string | ReadonlyArray<string>;\nexport const V2ConfigReadResponse__ForcedChatgptWorkspaceIds = Schema.Union([\n  Schema.String,\n  Schema.Array(Schema.String),\n]).annotate({\n  description: \"Backward-compatible API shape for ChatGPT workspace login restrictions.\",\n});\n\nexport type V2ConfigReadResponse__ForcedLoginMethod = \"chatgpt\" | \"api\";\nexport const V2ConfigReadResponse__ForcedLoginMethod = Schema.Literals([\"chatgpt\", \"api\"]);\n\nexport type V2ConfigReadResponse__ReasoningEffort = string;\nexport const V2ConfigReadResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ConfigReadResponse__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const V2ConfigReadResponse__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type V2ConfigReadResponse__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ConfigReadResponse__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ConfigReadResponse__SandboxWorkspaceWrite = {\n  readonly exclude_slash_tmp?: boolean;\n  readonly exclude_tmpdir_env_var?: boolean;\n  readonly network_access?: boolean;\n  readonly writable_roots?: ReadonlyArray<string>;\n};\nexport const V2ConfigReadResponse__SandboxWorkspaceWrite = Schema.Struct({\n  exclude_slash_tmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  exclude_tmpdir_env_var: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  network_access: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  writable_roots: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n});\n\nexport type V2ConfigReadResponse__Verbosity = \"low\" | \"medium\" | \"high\";\nexport const V2ConfigReadResponse__Verbosity = Schema.Literals([\"low\", \"medium\", \"high\"]).annotate({\n  description:\n    \"Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.\",\n});\n\nexport type V2ConfigReadResponse__WebSearchContextSize = \"low\" | \"medium\" | \"high\";\nexport const V2ConfigReadResponse__WebSearchContextSize = Schema.Literals([\n  \"low\",\n  \"medium\",\n  \"high\",\n]);\n\nexport type V2ConfigReadResponse__WebSearchLocation = {\n  readonly city?: string | null;\n  readonly country?: string | null;\n  readonly region?: string | null;\n  readonly timezone?: string | null;\n};\nexport const V2ConfigReadResponse__WebSearchLocation = Schema.Struct({\n  city: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  country: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  region: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timezone: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigReadResponse__WebSearchMode = \"disabled\" | \"cached\" | \"indexed\" | \"live\";\nexport const V2ConfigReadResponse__WebSearchMode = Schema.Literals([\n  \"disabled\",\n  \"cached\",\n  \"indexed\",\n  \"live\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ConfigRequirementsReadResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigRequirementsReadResponse__ComputerUseRequirements = {\n  readonly allowLockedComputerUse?: boolean | null;\n};\nexport const V2ConfigRequirementsReadResponse__ComputerUseRequirements = Schema.Struct({\n  allowLockedComputerUse: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse__ConfiguredHookHandler =\n  | {\n      readonly async: boolean;\n      readonly command: string;\n      readonly commandWindows?: string | null;\n      readonly statusMessage?: string | null;\n      readonly timeoutSec?: number | null;\n      readonly type: \"command\";\n    }\n  | { readonly type: \"prompt\" }\n  | { readonly type: \"agent\" };\nexport const V2ConfigRequirementsReadResponse__ConfiguredHookHandler = Schema.Union(\n  [\n    Schema.Struct({\n      async: Schema.Boolean,\n      command: Schema.String,\n      commandWindows: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      timeoutSec: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"command\").annotate({ title: \"CommandConfiguredHookHandlerType\" }),\n    }).annotate({ title: \"CommandConfiguredHookHandler\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"prompt\").annotate({ title: \"PromptConfiguredHookHandlerType\" }),\n    }).annotate({ title: \"PromptConfiguredHookHandler\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"agent\").annotate({ title: \"AgentConfiguredHookHandlerType\" }),\n    }).annotate({ title: \"AgentConfiguredHookHandler\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigRequirementsReadResponse__NetworkDomainPermission = \"allow\" | \"deny\";\nexport const V2ConfigRequirementsReadResponse__NetworkDomainPermission = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = \"allow\" | \"deny\";\nexport const V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__ReasoningEffort = string;\nexport const V2ConfigRequirementsReadResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ConfigRequirementsReadResponse__ResidencyRequirement = \"us\";\nexport const V2ConfigRequirementsReadResponse__ResidencyRequirement = Schema.Literal(\"us\");\n\nexport type V2ConfigRequirementsReadResponse__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ConfigRequirementsReadResponse__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__WebSearchMode =\n  | \"disabled\"\n  | \"cached\"\n  | \"indexed\"\n  | \"live\";\nexport const V2ConfigRequirementsReadResponse__WebSearchMode = Schema.Literals([\n  \"disabled\",\n  \"cached\",\n  \"indexed\",\n  \"live\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type V2ConfigValueWriteParams__MergeStrategy = \"replace\" | \"upsert\";\nexport const V2ConfigValueWriteParams__MergeStrategy = Schema.Literals([\"replace\", \"upsert\"]);\n\nexport type V2ConfigWarningNotification__TextPosition = {\n  readonly column: number;\n  readonly line: number;\n};\nexport const V2ConfigWarningNotification__TextPosition = Schema.Struct({\n  column: Schema.Number.annotate({\n    description: \"1-based column number (in Unicode scalar values).\",\n    format: \"uint\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  line: Schema.Number.annotate({ description: \"1-based line number.\", format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ConfigWriteResponse__AbsolutePathBuf = string;\nexport const V2ConfigWriteResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ConfigWriteResponse__WriteStatus = \"ok\" | \"okOverridden\";\nexport const V2ConfigWriteResponse__WriteStatus = Schema.Literals([\"ok\", \"okOverridden\"]);\n\nexport type V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome =\n  \"reset\" | \"nothingToReset\" | \"noCredit\" | \"alreadyRedeemed\";\nexport const V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome =\n  Schema.Literals([\"reset\", \"nothingToReset\", \"noCredit\", \"alreadyRedeemed\"]);\n\nexport type V2ErrorNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ErrorNotification__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ExperimentalFeatureListResponse__ExperimentalFeature = {\n  readonly announcement?: string | null;\n  readonly defaultEnabled: boolean;\n  readonly description?: string | null;\n  readonly displayName?: string | null;\n  readonly enabled: boolean;\n  readonly name: string;\n  readonly stage: \"beta\" | \"underDevelopment\" | \"stable\" | \"deprecated\" | \"removed\";\n};\nexport const V2ExperimentalFeatureListResponse__ExperimentalFeature = Schema.Struct({\n  announcement: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  defaultEnabled: Schema.Boolean.annotate({\n    description: \"Whether this feature is enabled by default.\",\n  }),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Short summary describing what the feature does. Null when this feature is not in beta.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  displayName: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"User-facing display name shown in the experimental features UI. Null when this feature is not in beta.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  enabled: Schema.Boolean.annotate({\n    description: \"Whether this feature is currently enabled in the loaded config.\",\n  }),\n  name: Schema.String.annotate({\n    description: \"Stable key used in config.toml and CLI flag toggles.\",\n  }),\n  stage: Schema.Literals([\"beta\", \"underDevelopment\", \"stable\", \"deprecated\", \"removed\"]).annotate({\n    description: \"Lifecycle stage of this feature flag.\",\n  }),\n});\n\nexport type V2ExternalAgentConfigDetectResponse__CommandMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__CommandMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigDetectResponse__HookMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__HookMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__McpServerMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__McpServerMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__PluginsMigration = {\n  readonly marketplaceName: string;\n  readonly pluginNames: ReadonlyArray<string>;\n};\nexport const V2ExternalAgentConfigDetectResponse__PluginsMigration = Schema.Struct({\n  marketplaceName: Schema.String,\n  pluginNames: Schema.Array(Schema.String),\n});\n\nexport type V2ExternalAgentConfigDetectResponse__SessionMigration = {\n  readonly cwd: string;\n  readonly path: string;\n  readonly title?: string | null;\n};\nexport const V2ExternalAgentConfigDetectResponse__SessionMigration = Schema.Struct({\n  cwd: Schema.String,\n  path: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ExternalAgentConfigDetectResponse__SkillMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__SkillMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__SubagentMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__SubagentMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType =\n    | \"AGENTS_MD\"\n    | \"CONFIG\"\n    | \"SKILLS\"\n    | \"PLUGINS\"\n    | \"MCP_SERVER_CONFIG\"\n    | \"SUBAGENTS\"\n    | \"HOOKS\"\n    | \"COMMANDS\"\n    | \"MEMORY\"\n    | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType =\n    | \"AGENTS_MD\"\n    | \"CONFIG\"\n    | \"SKILLS\"\n    | \"PLUGINS\"\n    | \"MCP_SERVER_CONFIG\"\n    | \"SUBAGENTS\"\n    | \"HOOKS\"\n    | \"COMMANDS\"\n    | \"MEMORY\"\n    | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource =\n  \"remoteMcpServersConfig\";\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource =\n  Schema.Literal(\"remoteMcpServersConfig\");\n\nexport type V2ExternalAgentConfigImportParams__CommandMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__CommandMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigImportParams__HookMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__HookMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__McpServerMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__McpServerMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__PluginsMigration = {\n  readonly marketplaceName: string;\n  readonly pluginNames: ReadonlyArray<string>;\n};\nexport const V2ExternalAgentConfigImportParams__PluginsMigration = Schema.Struct({\n  marketplaceName: Schema.String,\n  pluginNames: Schema.Array(Schema.String),\n});\n\nexport type V2ExternalAgentConfigImportParams__SessionMigration = {\n  readonly cwd: string;\n  readonly path: string;\n  readonly title?: string | null;\n};\nexport const V2ExternalAgentConfigImportParams__SessionMigration = Schema.Struct({\n  cwd: Schema.String,\n  path: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ExternalAgentConfigImportParams__SkillMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__SkillMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__SubagentMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__SubagentMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2FileChangePatchUpdatedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2FileChangePatchUpdatedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2FsChangedNotification__AbsolutePathBuf = string;\nexport const V2FsChangedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsReadDirectoryResponse__FsReadDirectoryEntry = {\n  readonly fileName: string;\n  readonly isDirectory: boolean;\n  readonly isFile: boolean;\n};\nexport const V2FsReadDirectoryResponse__FsReadDirectoryEntry = Schema.Struct({\n  fileName: Schema.String.annotate({\n    description: \"Direct child entry name only, not an absolute or relative path.\",\n  }),\n  isDirectory: Schema.Boolean.annotate({\n    description: \"Whether this entry resolves to a directory.\",\n  }),\n  isFile: Schema.Boolean.annotate({\n    description: \"Whether this entry resolves to a regular file.\",\n  }),\n}).annotate({ description: \"A directory entry returned by `fs/readDirectory`.\" });\n\nexport type V2GetAccountRateLimitsResponse__CreditsSnapshot = {\n  readonly balance?: string | null;\n  readonly hasCredits: boolean;\n  readonly unlimited: boolean;\n};\nexport const V2GetAccountRateLimitsResponse__CreditsSnapshot = Schema.Struct({\n  balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hasCredits: Schema.Boolean,\n  unlimited: Schema.Boolean,\n});\n\nexport type V2GetAccountRateLimitsResponse__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2GetAccountRateLimitsResponse__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitReachedType =\n  | \"rate_limit_reached\"\n  | \"workspace_owner_credits_depleted\"\n  | \"workspace_member_credits_depleted\"\n  | \"workspace_owner_usage_limit_reached\"\n  | \"workspace_member_usage_limit_reached\";\nexport const V2GetAccountRateLimitsResponse__RateLimitReachedType = Schema.Literals([\n  \"rate_limit_reached\",\n  \"workspace_owner_credits_depleted\",\n  \"workspace_member_credits_depleted\",\n  \"workspace_owner_usage_limit_reached\",\n  \"workspace_member_usage_limit_reached\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus =\n  | \"available\"\n  | \"redeeming\"\n  | \"redeemed\"\n  | \"unknown\";\nexport const V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus = Schema.Literals([\n  \"available\",\n  \"redeeming\",\n  \"redeemed\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetType = \"codexRateLimits\" | \"unknown\";\nexport const V2GetAccountRateLimitsResponse__RateLimitResetType = Schema.Literals([\n  \"codexRateLimits\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitWindow = {\n  readonly resetsAt?: number | null;\n  readonly usedPercent: number;\n  readonly windowDurationMins?: number | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitWindow = Schema.Struct({\n  resetsAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  usedPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  windowDurationMins: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot = {\n  readonly limit: string;\n  readonly remainingPercent: number;\n  readonly resetsAt: number;\n  readonly used: string;\n};\nexport const V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot = Schema.Struct({\n  limit: Schema.String,\n  remainingPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  resetsAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  used: Schema.String,\n});\n\nexport type V2GetAccountResponse__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2GetAccountResponse__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket = {\n  readonly startDate: string;\n  readonly tokens: number;\n};\nexport const V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket = Schema.Struct({\n  startDate: Schema.String,\n  tokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2GetAccountTokenUsageResponse__AccountTokenUsageSummary = {\n  readonly currentStreakDays?: number | null;\n  readonly lifetimeTokens?: number | null;\n  readonly longestRunningTurnSec?: number | null;\n  readonly longestStreakDays?: number | null;\n  readonly peakDailyTokens?: number | null;\n};\nexport const V2GetAccountTokenUsageResponse__AccountTokenUsageSummary = Schema.Struct({\n  currentStreakDays: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  lifetimeTokens: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  longestRunningTurnSec: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  longestStreakDays: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  peakDailyTokens: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type V2GetWorkspaceMessagesResponse__WorkspaceMessageType =\n  | \"headline\"\n  | \"announcement\"\n  | \"unknown\";\nexport const V2GetWorkspaceMessagesResponse__WorkspaceMessageType = Schema.Literals([\n  \"headline\",\n  \"announcement\",\n  \"unknown\",\n]);\n\nexport type V2HookCompletedNotification__AbsolutePathBuf = string;\nexport const V2HookCompletedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2HookCompletedNotification__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2HookCompletedNotification__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2HookCompletedNotification__HookExecutionMode = \"sync\" | \"async\";\nexport const V2HookCompletedNotification__HookExecutionMode = Schema.Literals([\"sync\", \"async\"]);\n\nexport type V2HookCompletedNotification__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const V2HookCompletedNotification__HookHandlerType = Schema.Literals([\n  \"command\",\n  \"prompt\",\n  \"agent\",\n]);\n\nexport type V2HookCompletedNotification__HookOutputEntryKind =\n  | \"warning\"\n  | \"stop\"\n  | \"feedback\"\n  | \"context\"\n  | \"error\";\nexport const V2HookCompletedNotification__HookOutputEntryKind = Schema.Literals([\n  \"warning\",\n  \"stop\",\n  \"feedback\",\n  \"context\",\n  \"error\",\n]);\n\nexport type V2HookCompletedNotification__HookRunStatus =\n  | \"running\"\n  | \"completed\"\n  | \"failed\"\n  | \"blocked\"\n  | \"stopped\";\nexport const V2HookCompletedNotification__HookRunStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"failed\",\n  \"blocked\",\n  \"stopped\",\n]);\n\nexport type V2HookCompletedNotification__HookScope = \"thread\" | \"turn\";\nexport const V2HookCompletedNotification__HookScope = Schema.Literals([\"thread\", \"turn\"]);\n\nexport type V2HooksListResponse__AbsolutePathBuf = string;\nexport const V2HooksListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2HooksListResponse__HookErrorInfo = {\n  readonly message: string;\n  readonly path: string;\n};\nexport const V2HooksListResponse__HookErrorInfo = Schema.Struct({\n  message: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2HooksListResponse__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2HooksListResponse__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2HooksListResponse__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const V2HooksListResponse__HookHandlerType = Schema.Literals([\"command\", \"prompt\", \"agent\"]);\n\nexport type V2HooksListResponse__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const V2HooksListResponse__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type V2HooksListResponse__HookTrustStatus = \"managed\" | \"untrusted\" | \"trusted\" | \"modified\";\nexport const V2HooksListResponse__HookTrustStatus = Schema.Literals([\n  \"managed\",\n  \"untrusted\",\n  \"trusted\",\n  \"modified\",\n]);\n\nexport type V2HookStartedNotification__AbsolutePathBuf = string;\nexport const V2HookStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2HookStartedNotification__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2HookStartedNotification__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2HookStartedNotification__HookExecutionMode = \"sync\" | \"async\";\nexport const V2HookStartedNotification__HookExecutionMode = Schema.Literals([\"sync\", \"async\"]);\n\nexport type V2HookStartedNotification__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const V2HookStartedNotification__HookHandlerType = Schema.Literals([\n  \"command\",\n  \"prompt\",\n  \"agent\",\n]);\n\nexport type V2HookStartedNotification__HookOutputEntryKind =\n  | \"warning\"\n  | \"stop\"\n  | \"feedback\"\n  | \"context\"\n  | \"error\";\nexport const V2HookStartedNotification__HookOutputEntryKind = Schema.Literals([\n  \"warning\",\n  \"stop\",\n  \"feedback\",\n  \"context\",\n  \"error\",\n]);\n\nexport type V2HookStartedNotification__HookRunStatus =\n  | \"running\"\n  | \"completed\"\n  | \"failed\"\n  | \"blocked\"\n  | \"stopped\";\nexport const V2HookStartedNotification__HookRunStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"failed\",\n  \"blocked\",\n  \"stopped\",\n]);\n\nexport type V2HookStartedNotification__HookScope = \"thread\" | \"turn\";\nexport const V2HookStartedNotification__HookScope = Schema.Literals([\"thread\", \"turn\"]);\n\nexport type V2ItemCompletedNotification__AbsolutePathBuf = string;\nexport const V2ItemCompletedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ItemCompletedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ItemCompletedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ItemCompletedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemCompletedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemCompletedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ItemCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemCompletedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemCompletedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemCompletedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ItemCompletedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ItemCompletedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ItemCompletedNotification__LegacyAppPathString = string;\nexport const V2ItemCompletedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemCompletedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ItemCompletedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ItemCompletedNotification__McpToolCallError = { readonly message: string };\nexport const V2ItemCompletedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ItemCompletedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ItemCompletedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ItemCompletedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemCompletedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ItemCompletedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ItemCompletedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ItemCompletedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemCompletedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemCompletedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ItemCompletedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemCompletedNotification__ReasoningEffort = string;\nexport const V2ItemCompletedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ItemCompletedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ItemCompletedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ItemCompletedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ItemCompletedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ItemCompletedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ItemCompletedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf = string;\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf =\n  Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions =\n  Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = \"agent\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource =\n  Schema.Literal(\"agent\").annotate({\n    description: \"[UNSTABLE] Source that produced a terminal approval auto-review decision.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode =\n  | \"read\"\n  | \"write\"\n  | \"deny\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode =\n  Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =\n  | \"inProgress\"\n  | \"approved\"\n  | \"denied\"\n  | \"timedOut\"\n  | \"aborted\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =\n  Schema.Literals([\"inProgress\", \"approved\", \"denied\", \"timedOut\", \"aborted\"]).annotate({\n    description: \"[UNSTABLE] Lifecycle state for an approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =\n  | \"shell\"\n  | \"unifiedExec\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =\n  Schema.Literals([\"shell\", \"unifiedExec\"]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel =\n  | \"low\"\n  | \"medium\"\n  | \"high\"\n  | \"critical\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = Schema.Literals(\n  [\"low\", \"medium\", \"high\", \"critical\"],\n).annotate({ description: \"[UNSTABLE] Risk level assigned by approval auto-review.\" });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =\n  | \"unknown\"\n  | \"low\"\n  | \"medium\"\n  | \"high\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =\n  Schema.Literals([\"unknown\", \"low\", \"medium\", \"high\"]).annotate({\n    description: \"[UNSTABLE] Authorization level assigned by approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString = string;\nexport const V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =\n  Schema.Literals([\"http\", \"https\", \"socks5Tcp\", \"socks5Udp\"]);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf = string;\nexport const V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf =\n  Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions =\n  Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode =\n  | \"read\"\n  | \"write\"\n  | \"deny\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode =\n  Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =\n  | \"inProgress\"\n  | \"approved\"\n  | \"denied\"\n  | \"timedOut\"\n  | \"aborted\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =\n  Schema.Literals([\"inProgress\", \"approved\", \"denied\", \"timedOut\", \"aborted\"]).annotate({\n    description: \"[UNSTABLE] Lifecycle state for an approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =\n  | \"shell\"\n  | \"unifiedExec\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =\n  Schema.Literals([\"shell\", \"unifiedExec\"]);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel =\n  | \"low\"\n  | \"medium\"\n  | \"high\"\n  | \"critical\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel = Schema.Literals([\n  \"low\",\n  \"medium\",\n  \"high\",\n  \"critical\",\n]).annotate({ description: \"[UNSTABLE] Risk level assigned by approval auto-review.\" });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =\n  | \"unknown\"\n  | \"low\"\n  | \"medium\"\n  | \"high\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =\n  Schema.Literals([\"unknown\", \"low\", \"medium\", \"high\"]).annotate({\n    description: \"[UNSTABLE] Authorization level assigned by approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString = string;\nexport const V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =\n  Schema.Literals([\"http\", \"https\", \"socks5Tcp\", \"socks5Udp\"]);\n\nexport type V2ItemStartedNotification__AbsolutePathBuf = string;\nexport const V2ItemStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ItemStartedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ItemStartedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ItemStartedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemStartedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemStartedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ItemStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemStartedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemStartedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ItemStartedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ItemStartedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ItemStartedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ItemStartedNotification__LegacyAppPathString = string;\nexport const V2ItemStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemStartedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ItemStartedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ItemStartedNotification__McpToolCallError = { readonly message: string };\nexport const V2ItemStartedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ItemStartedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ItemStartedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ItemStartedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ItemStartedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemStartedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ItemStartedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ItemStartedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ItemStartedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ItemStartedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemStartedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemStartedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ItemStartedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__ReasoningEffort = string;\nexport const V2ItemStartedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ItemStartedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ItemStartedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ItemStartedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ItemStartedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ItemStartedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ItemStartedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ListMcpServerStatusParams__McpServerStatusDetail = \"full\" | \"toolsAndAuthOnly\";\nexport const V2ListMcpServerStatusParams__McpServerStatusDetail = Schema.Literals([\n  \"full\",\n  \"toolsAndAuthOnly\",\n]);\n\nexport type V2ListMcpServerStatusResponse__McpAuthStatus =\n  | \"unsupported\"\n  | \"notLoggedIn\"\n  | \"bearerToken\"\n  | \"oAuth\";\nexport const V2ListMcpServerStatusResponse__McpAuthStatus = Schema.Literals([\n  \"unsupported\",\n  \"notLoggedIn\",\n  \"bearerToken\",\n  \"oAuth\",\n]);\n\nexport type V2ListMcpServerStatusResponse__McpServerInfo = {\n  readonly description?: string | null;\n  readonly icons?: ReadonlyArray<unknown> | null;\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n  readonly websiteUrl?: string | null;\n};\nexport const V2ListMcpServerStatusResponse__McpServerInfo = Schema.Struct({\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  version: Schema.String,\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"Presentation metadata advertised by an initialized MCP server.\" });\n\nexport type V2ListMcpServerStatusResponse__Resource = {\n  readonly _meta?: unknown;\n  readonly annotations?: unknown;\n  readonly description?: string | null;\n  readonly icons?: ReadonlyArray<unknown> | null;\n  readonly mimeType?: string | null;\n  readonly name: string;\n  readonly size?: number | null;\n  readonly title?: string | null;\n  readonly uri: string;\n};\nexport const V2ListMcpServerStatusResponse__Resource = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  annotations: Schema.optionalKey(Schema.Unknown),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  size: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({ description: \"A known resource that the server is capable of reading.\" });\n\nexport type V2ListMcpServerStatusResponse__ResourceTemplate = {\n  readonly annotations?: unknown;\n  readonly description?: string | null;\n  readonly mimeType?: string | null;\n  readonly name: string;\n  readonly title?: string | null;\n  readonly uriTemplate: string;\n};\nexport const V2ListMcpServerStatusResponse__ResourceTemplate = Schema.Struct({\n  annotations: Schema.optionalKey(Schema.Unknown),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uriTemplate: Schema.String,\n}).annotate({ description: \"A template description for resources available on the server.\" });\n\nexport type V2ListMcpServerStatusResponse__Tool = {\n  readonly _meta?: unknown;\n  readonly annotations?: unknown;\n  readonly description?: string | null;\n  readonly icons?: ReadonlyArray<unknown> | null;\n  readonly inputSchema: unknown;\n  readonly name: string;\n  readonly outputSchema?: unknown;\n  readonly title?: string | null;\n};\nexport const V2ListMcpServerStatusResponse__Tool = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  annotations: Schema.optionalKey(Schema.Unknown),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),\n  inputSchema: Schema.Unknown,\n  name: Schema.String,\n  outputSchema: Schema.optionalKey(Schema.Unknown),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"Definition for a tool the client can call.\" });\n\nexport type V2LoginAccountParams__LoginAppBrand = \"codex\" | \"chatgpt\";\nexport const V2LoginAccountParams__LoginAppBrand = Schema.Literals([\"codex\", \"chatgpt\"]);\n\nexport type V2MarketplaceAddResponse__AbsolutePathBuf = string;\nexport const V2MarketplaceAddResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2MarketplaceRemoveResponse__AbsolutePathBuf = string;\nexport const V2MarketplaceRemoveResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2MarketplaceUpgradeResponse__AbsolutePathBuf = string;\nexport const V2MarketplaceUpgradeResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo = {\n  readonly marketplaceName: string;\n  readonly message: string;\n};\nexport const V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo = Schema.Struct({\n  marketplaceName: Schema.String,\n  message: Schema.String,\n});\n\nexport type V2McpResourceReadResponse__ResourceContent =\n  | {\n      readonly _meta?: unknown;\n      readonly mimeType?: string | null;\n      readonly text: string;\n      readonly uri: string;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly blob: string;\n      readonly mimeType?: string | null;\n      readonly uri: string;\n    };\nexport const V2McpResourceReadResponse__ResourceContent = Schema.Union([\n  Schema.Struct({\n    _meta: Schema.optionalKey(Schema.Unknown),\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    text: Schema.String,\n    uri: Schema.String.annotate({ description: \"The URI of this resource.\" }),\n  }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(Schema.Unknown),\n    blob: Schema.String,\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    uri: Schema.String.annotate({ description: \"The URI of this resource.\" }),\n  }),\n]).annotate({ description: \"Contents returned when reading a resource from an MCP server.\" });\n\nexport type V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason =\n  \"reauthenticationRequired\";\nexport const V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason = Schema.Literal(\n  \"reauthenticationRequired\",\n);\n\nexport type V2McpServerStatusUpdatedNotification__McpServerStartupState =\n  | \"starting\"\n  | \"ready\"\n  | \"failed\"\n  | \"cancelled\";\nexport const V2McpServerStatusUpdatedNotification__McpServerStartupState = Schema.Literals([\n  \"starting\",\n  \"ready\",\n  \"failed\",\n  \"cancelled\",\n]);\n\nexport type V2ModelListResponse__InputModality = \"text\" | \"image\" | \"audio\";\nexport const V2ModelListResponse__InputModality = Schema.Literals([\n  \"text\",\n  \"image\",\n  \"audio\",\n]).annotate({ description: \"Canonical user-input modality tags advertised by a model.\" });\n\nexport type V2ModelListResponse__ModelAvailabilityNux = { readonly message: string };\nexport const V2ModelListResponse__ModelAvailabilityNux = Schema.Struct({ message: Schema.String });\n\nexport type V2ModelListResponse__ModelServiceTier = {\n  readonly description: string;\n  readonly id: string;\n  readonly name: string;\n};\nexport const V2ModelListResponse__ModelServiceTier = Schema.Struct({\n  description: Schema.String,\n  id: Schema.String,\n  name: Schema.String,\n});\n\nexport type V2ModelListResponse__ModelUpgradeInfo = {\n  readonly migrationMarkdown?: string | null;\n  readonly model: string;\n  readonly modelLink?: string | null;\n  readonly upgradeCopy?: string | null;\n};\nexport const V2ModelListResponse__ModelUpgradeInfo = Schema.Struct({\n  migrationMarkdown: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  modelLink: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  upgradeCopy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ModelListResponse__ReasoningEffort = string;\nexport const V2ModelListResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ModelReroutedNotification__ModelRerouteReason = \"highRiskCyberActivity\";\nexport const V2ModelReroutedNotification__ModelRerouteReason =\n  Schema.Literal(\"highRiskCyberActivity\");\n\nexport type V2ModelVerificationNotification__ModelVerification = \"trustedAccessForCyber\";\nexport const V2ModelVerificationNotification__ModelVerification =\n  Schema.Literal(\"trustedAccessForCyber\");\n\nexport type V2PermissionProfileListResponse__PermissionProfileSummary = {\n  readonly allowed: boolean;\n  readonly description?: string | null;\n  readonly id: string;\n};\nexport const V2PermissionProfileListResponse__PermissionProfileSummary = Schema.Struct({\n  allowed: Schema.Boolean.annotate({\n    description: \"Whether the effective requirements allow selecting this profile.\",\n  }),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional user-facing description for display in clients.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({ description: \"Available permission profile identifier.\" }),\n});\n\nexport type V2PluginInstalledParams__AbsolutePathBuf = string;\nexport const V2PluginInstalledParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginInstalledResponse__AbsolutePathBuf = string;\nexport const V2PluginInstalledResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginInstalledResponse__MarketplaceInterface = {\n  readonly displayName?: string | null;\n};\nexport const V2PluginInstalledResponse__MarketplaceInterface = Schema.Struct({\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginInstalledResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginInstalledResponse__PluginAuthPolicy = Schema.Literals([\n  \"ON_INSTALL\",\n  \"ON_USE\",\n]);\n\nexport type V2PluginInstalledResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginInstalledResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginInstalledResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginInstalledResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginInstalledResponse__PluginShareDiscoverability =\n  | \"LISTED\"\n  | \"UNLISTED\"\n  | \"PRIVATE\";\nexport const V2PluginInstalledResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginInstalledResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginInstalledResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginInstalledResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginInstalledResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginInstallParams__AbsolutePathBuf = string;\nexport const V2PluginInstallParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginInstallResponse__AppSummary = {\n  readonly category?: string | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly name: string;\n};\nexport const V2PluginInstallResponse__AppSummary = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - app metadata summary for plugin responses.\" });\n\nexport type V2PluginInstallResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginInstallResponse__PluginAuthPolicy = Schema.Literals([\"ON_INSTALL\", \"ON_USE\"]);\n\nexport type V2PluginListParams__AbsolutePathBuf = string;\nexport const V2PluginListParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginListParams__PluginListMarketplaceKind =\n  | \"local\"\n  | \"vertical\"\n  | \"workspace-directory\"\n  | \"shared-with-me\"\n  | \"created-by-me-remote\";\nexport const V2PluginListParams__PluginListMarketplaceKind = Schema.Literals([\n  \"local\",\n  \"vertical\",\n  \"workspace-directory\",\n  \"shared-with-me\",\n  \"created-by-me-remote\",\n]);\n\nexport type V2PluginListResponse__AbsolutePathBuf = string;\nexport const V2PluginListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginListResponse__MarketplaceInterface = { readonly displayName?: string | null };\nexport const V2PluginListResponse__MarketplaceInterface = Schema.Struct({\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginListResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginListResponse__PluginAuthPolicy = Schema.Literals([\"ON_INSTALL\", \"ON_USE\"]);\n\nexport type V2PluginListResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginListResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginListResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginListResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginListResponse__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const V2PluginListResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginListResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginListResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginListResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginListResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginReadParams__AbsolutePathBuf = string;\nexport const V2PluginReadParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginReadResponse__AbsolutePathBuf = string;\nexport const V2PluginReadResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginReadResponse__AppSummary = {\n  readonly category?: string | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly name: string;\n};\nexport const V2PluginReadResponse__AppSummary = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - app metadata summary for plugin responses.\" });\n\nexport type V2PluginReadResponse__AppTemplateUnavailableReason =\n  | \"NOT_CONFIGURED_FOR_WORKSPACE\"\n  | \"NO_ACTIVE_WORKSPACE\";\nexport const V2PluginReadResponse__AppTemplateUnavailableReason = Schema.Literals([\n  \"NOT_CONFIGURED_FOR_WORKSPACE\",\n  \"NO_ACTIVE_WORKSPACE\",\n]);\n\nexport type V2PluginReadResponse__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2PluginReadResponse__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2PluginReadResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginReadResponse__PluginAuthPolicy = Schema.Literals([\"ON_INSTALL\", \"ON_USE\"]);\n\nexport type V2PluginReadResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginReadResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginReadResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginReadResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginReadResponse__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const V2PluginReadResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginReadResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginReadResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginReadResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginReadResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginReadResponse__ScheduledTaskWeekday =\n  | \"MO\"\n  | \"TU\"\n  | \"WE\"\n  | \"TH\"\n  | \"FR\"\n  | \"SA\"\n  | \"SU\";\nexport const V2PluginReadResponse__ScheduledTaskWeekday = Schema.Literals([\n  \"MO\",\n  \"TU\",\n  \"WE\",\n  \"TH\",\n  \"FR\",\n  \"SA\",\n  \"SU\",\n]);\n\nexport type V2PluginShareCheckoutResponse__AbsolutePathBuf = string;\nexport const V2PluginShareCheckoutResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginShareListResponse__AbsolutePathBuf = string;\nexport const V2PluginShareListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginShareListResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginShareListResponse__PluginAuthPolicy = Schema.Literals([\n  \"ON_INSTALL\",\n  \"ON_USE\",\n]);\n\nexport type V2PluginShareListResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginShareListResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginShareListResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginShareListResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginShareListResponse__PluginShareDiscoverability =\n  | \"LISTED\"\n  | \"UNLISTED\"\n  | \"PRIVATE\";\nexport const V2PluginShareListResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginShareListResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginShareListResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginShareListResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginShareListResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginShareSaveParams__AbsolutePathBuf = string;\nexport const V2PluginShareSaveParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginShareSaveParams__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const V2PluginShareSaveParams__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginShareSaveParams__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginShareSaveParams__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginShareSaveParams__PluginShareTargetRole = \"reader\" | \"editor\";\nexport const V2PluginShareSaveParams__PluginShareTargetRole = Schema.Literals([\"reader\", \"editor\"]);\n\nexport type V2PluginShareUpdateTargetsParams__PluginSharePrincipalType =\n  | \"user\"\n  | \"group\"\n  | \"workspace\";\nexport const V2PluginShareUpdateTargetsParams__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginShareUpdateTargetsParams__PluginShareTargetRole = \"reader\" | \"editor\";\nexport const V2PluginShareUpdateTargetsParams__PluginShareTargetRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n]);\n\nexport type V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability =\n  | \"UNLISTED\"\n  | \"PRIVATE\"\n  | \"LISTED\";\nexport const V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability = Schema.Literals([\n  \"UNLISTED\",\n  \"PRIVATE\",\n  \"LISTED\",\n]);\n\nexport type V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability =\n  | \"LISTED\"\n  | \"UNLISTED\"\n  | \"PRIVATE\";\nexport const V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole =\n  | \"reader\"\n  | \"editor\"\n  | \"owner\";\nexport const V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType =\n  | \"user\"\n  | \"group\"\n  | \"workspace\";\nexport const V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2RawResponseCompletedNotification__TokenUsageBreakdown = {\n  readonly cacheWriteInputTokens?: number;\n  readonly cachedInputTokens: number;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly reasoningOutputTokens: number;\n  readonly totalTokens: number;\n};\nexport const V2RawResponseCompletedNotification__TokenUsageBreakdown = Schema.Struct({\n  cacheWriteInputTokens: Schema.optionalKey(\n    Schema.Number.annotate({ default: 0, format: \"int64\" }).check(Schema.isInt()),\n  ),\n  cachedInputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  inputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  outputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  reasoningOutputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  totalTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2RawResponseItemCompletedNotification__AgentMessageInputContent =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2RawResponseItemCompletedNotification__AgentMessageInputContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"InputTextAgentMessageInputContent\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"EncryptedContentAgentMessageInputContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__ImageDetail =\n  | \"auto\"\n  | \"low\"\n  | \"high\"\n  | \"original\";\nexport const V2RawResponseItemCompletedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough = {\n  readonly turn_id?: string | null;\n};\nexport const V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough =\n  Schema.Struct({\n    turn_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  }).annotate({\n    description:\n      \"Internal Responses API passthrough metadata copied into underlying chat messages.\\n\\nResponses API strongly types this payload. Do not modify it without first getting API approval and making the corresponding Responses API change.\",\n  });\n\nexport type V2RawResponseItemCompletedNotification__LocalShellAction = {\n  readonly command: ReadonlyArray<string>;\n  readonly env?: { readonly [x: string]: string } | null;\n  readonly timeout_ms?: number | null;\n  readonly type: \"exec\";\n  readonly user?: string | null;\n  readonly working_directory?: string | null;\n};\nexport const V2RawResponseItemCompletedNotification__LocalShellAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.Array(Schema.String),\n      env: Schema.optionalKey(\n        Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n      ),\n      timeout_ms: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"exec\").annotate({ title: \"ExecLocalShellActionType\" }),\n      user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"ExecLocalShellAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__LocalShellStatus =\n  | \"completed\"\n  | \"in_progress\"\n  | \"incomplete\";\nexport const V2RawResponseItemCompletedNotification__LocalShellStatus = Schema.Literals([\n  \"completed\",\n  \"in_progress\",\n  \"incomplete\",\n]);\n\nexport type V2RawResponseItemCompletedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2RawResponseItemCompletedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2RawResponseItemCompletedNotification__ReasoningItemContent =\n  | { readonly text: string; readonly type: \"reasoning_text\" }\n  | { readonly text: string; readonly type: \"text\" };\nexport const V2RawResponseItemCompletedNotification__ReasoningItemContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"reasoning_text\").annotate({\n        title: \"ReasoningTextReasoningItemContentType\",\n      }),\n    }).annotate({ title: \"ReasoningTextReasoningItemContent\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"text\").annotate({ title: \"TextReasoningItemContentType\" }),\n    }).annotate({ title: \"TextReasoningItemContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = {\n  readonly text: string;\n  readonly type: \"summary_text\";\n};\nexport const V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"summary_text\").annotate({\n        title: \"SummaryTextReasoningItemReasoningSummaryType\",\n      }),\n    }).annotate({ title: \"SummaryTextReasoningItemReasoningSummary\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"open_page\"; readonly url?: string | null }\n  | {\n      readonly pattern?: string | null;\n      readonly type: \"find_in_page\";\n      readonly url?: string | null;\n    }\n  | { readonly type: \"other\" };\nexport const V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"SearchResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"open_page\").annotate({\n        title: \"OpenPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"find_in_page\").annotate({\n        title: \"FindInPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"OtherResponsesApiWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus =\n  | \"disabled\"\n  | \"connecting\"\n  | \"connected\"\n  | \"errored\";\nexport const V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus =\n  Schema.Literals([\"disabled\", \"connecting\", \"connected\", \"errored\"]);\n\nexport type V2ReviewStartParams__ReviewDelivery = \"inline\" | \"detached\";\nexport const V2ReviewStartParams__ReviewDelivery = Schema.Literals([\"inline\", \"detached\"]);\n\nexport type V2ReviewStartParams__ReviewTarget =\n  | { readonly type: \"uncommittedChanges\" }\n  | { readonly branch: string; readonly type: \"baseBranch\" }\n  | { readonly sha: string; readonly title?: string | null; readonly type: \"commit\" }\n  | { readonly instructions: string; readonly type: \"custom\" };\nexport const V2ReviewStartParams__ReviewTarget = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"uncommittedChanges\").annotate({\n        title: \"UncommittedChangesReviewTargetType\",\n      }),\n    }).annotate({\n      title: \"UncommittedChangesReviewTarget\",\n      description: \"Review the working tree: staged, unstaged, and untracked files.\",\n    }),\n    Schema.Struct({\n      branch: Schema.String,\n      type: Schema.Literal(\"baseBranch\").annotate({ title: \"BaseBranchReviewTargetType\" }),\n    }).annotate({\n      title: \"BaseBranchReviewTarget\",\n      description: \"Review changes between the current branch and the given base branch.\",\n    }),\n    Schema.Struct({\n      sha: Schema.String,\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Optional human-readable label (e.g., commit subject) for UIs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"commit\").annotate({ title: \"CommitReviewTargetType\" }),\n    }).annotate({\n      title: \"CommitReviewTarget\",\n      description: \"Review the changes introduced by a specific commit.\",\n    }),\n    Schema.Struct({\n      instructions: Schema.String,\n      type: Schema.Literal(\"custom\").annotate({ title: \"CustomReviewTargetType\" }),\n    }).annotate({\n      title: \"CustomReviewTarget\",\n      description: \"Arbitrary instructions, equivalent to the old free-form prompt.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__AbsolutePathBuf = string;\nexport const V2ReviewStartResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ReviewStartResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ReviewStartResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ReviewStartResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ReviewStartResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ReviewStartResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ReviewStartResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ReviewStartResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ReviewStartResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ReviewStartResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ReviewStartResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ReviewStartResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ReviewStartResponse__LegacyAppPathString = string;\nexport const V2ReviewStartResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ReviewStartResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ReviewStartResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ReviewStartResponse__McpToolCallError = { readonly message: string };\nexport const V2ReviewStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ReviewStartResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ReviewStartResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ReviewStartResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ReviewStartResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ReviewStartResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ReviewStartResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ReviewStartResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ReviewStartResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ReviewStartResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ReviewStartResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ReviewStartResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ReviewStartResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ReviewStartResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ReviewStartResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__ReasoningEffort = string;\nexport const V2ReviewStartResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ReviewStartResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ReviewStartResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ReviewStartResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ReviewStartResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ReviewStartResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ReviewStartResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ReviewStartResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ReviewStartResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType = \"credits\" | \"usage_limit\";\nexport const V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType = Schema.Literals([\n  \"credits\",\n  \"usage_limit\",\n]);\n\nexport type V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus =\n  | \"sent\"\n  | \"cooldown_active\";\nexport const V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus = Schema.Literals([\n  \"sent\",\n  \"cooldown_active\",\n]);\n\nexport type V2ServerRequestResolvedNotification__RequestId = string | number;\nexport const V2ServerRequestResolvedNotification__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type V2SkillsConfigWriteParams__AbsolutePathBuf = string;\nexport const V2SkillsConfigWriteParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2SkillsExtraRootsSetParams__AbsolutePathBuf = string;\nexport const V2SkillsExtraRootsSetParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2SkillsListResponse__AbsolutePathBuf = string;\nexport const V2SkillsListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2SkillsListResponse__SkillErrorInfo = {\n  readonly message: string;\n  readonly path: string;\n};\nexport const V2SkillsListResponse__SkillErrorInfo = Schema.Struct({\n  message: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2SkillsListResponse__SkillScope = \"user\" | \"repo\" | \"system\" | \"admin\";\nexport const V2SkillsListResponse__SkillScope = Schema.Literals([\n  \"user\",\n  \"repo\",\n  \"system\",\n  \"admin\",\n]);\n\nexport type V2SkillsListResponse__SkillToolDependency = {\n  readonly command?: string | null;\n  readonly description?: string | null;\n  readonly transport?: string | null;\n  readonly type: string;\n  readonly url?: string | null;\n  readonly value: string;\n};\nexport const V2SkillsListResponse__SkillToolDependency = Schema.Struct({\n  command: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  transport: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: Schema.String,\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  value: Schema.String,\n});\n\nexport type V2ThreadForkParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadForkParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadForkParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadForkParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkParams__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ThreadForkParams__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ThreadForkParams__ThreadSource = string;\nexport const V2ThreadForkParams__ThreadSource = Schema.String;\n\nexport type V2ThreadForkResponse__AbsolutePathBuf = string;\nexport const V2ThreadForkResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadForkResponse__AgentPath = string;\nexport const V2ThreadForkResponse__AgentPath = Schema.String;\n\nexport type V2ThreadForkResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadForkResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadForkResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadForkResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadForkResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadForkResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadForkResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadForkResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadForkResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadForkResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadForkResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadForkResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadForkResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadForkResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadForkResponse__LegacyAppPathString = string;\nexport const V2ThreadForkResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadForkResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadForkResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadForkResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadForkResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadForkResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadForkResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadForkResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadForkResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadForkResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadForkResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadForkResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadForkResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadForkResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadForkResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadForkResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadForkResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadForkResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadForkResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__ReasoningEffort = string;\nexport const V2ThreadForkResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadForkResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadForkResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadForkResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadForkResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadForkResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadForkResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadForkResponse__ThreadId = string;\nexport const V2ThreadForkResponse__ThreadId = Schema.String;\n\nexport type V2ThreadForkResponse__ThreadSource = string;\nexport const V2ThreadForkResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadForkResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadForkResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadForkResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadForkResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadGoalGetResponse__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalGetResponse__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadGoalSetParams__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalSetParams__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadGoalSetResponse__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalSetResponse__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadGoalUpdatedNotification__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalUpdatedNotification__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadListParams__SortDirection = \"asc\" | \"desc\";\nexport const V2ThreadListParams__SortDirection = Schema.Literals([\"asc\", \"desc\"]);\n\nexport type V2ThreadListParams__ThreadListCwdFilter = string | ReadonlyArray<string>;\nexport const V2ThreadListParams__ThreadListCwdFilter = Schema.Union([\n  Schema.String,\n  Schema.Array(Schema.String),\n]);\n\nexport type V2ThreadListParams__ThreadSortKey = \"created_at\" | \"updated_at\" | \"recency_at\";\nexport const V2ThreadListParams__ThreadSortKey = Schema.Literals([\n  \"created_at\",\n  \"updated_at\",\n  \"recency_at\",\n]);\n\nexport type V2ThreadListParams__ThreadSourceKind =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"subAgent\"\n  | \"subAgentReview\"\n  | \"subAgentCompact\"\n  | \"subAgentThreadSpawn\"\n  | \"subAgentOther\"\n  | \"unknown\";\nexport const V2ThreadListParams__ThreadSourceKind = Schema.Literals([\n  \"cli\",\n  \"vscode\",\n  \"exec\",\n  \"appServer\",\n  \"subAgent\",\n  \"subAgentReview\",\n  \"subAgentCompact\",\n  \"subAgentThreadSpawn\",\n  \"subAgentOther\",\n  \"unknown\",\n]);\n\nexport type V2ThreadListResponse__AbsolutePathBuf = string;\nexport const V2ThreadListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadListResponse__AgentPath = string;\nexport const V2ThreadListResponse__AgentPath = Schema.String;\n\nexport type V2ThreadListResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadListResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadListResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadListResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadListResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadListResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadListResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadListResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadListResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadListResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadListResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadListResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadListResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadListResponse__LegacyAppPathString = string;\nexport const V2ThreadListResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadListResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadListResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadListResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadListResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadListResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadListResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadListResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadListResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadListResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadListResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadListResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadListResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadListResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadListResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadListResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadListResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadListResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadListResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__ReasoningEffort = string;\nexport const V2ThreadListResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadListResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadListResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadListResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadListResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadListResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadListResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadListResponse__ThreadId = string;\nexport const V2ThreadListResponse__ThreadId = Schema.String;\n\nexport type V2ThreadListResponse__ThreadSource = string;\nexport const V2ThreadListResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadListResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadListResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadListResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadListResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = Schema.Struct({\n  branch: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  originUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sha: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadMetadataUpdateResponse__AbsolutePathBuf = string;\nexport const V2ThreadMetadataUpdateResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadMetadataUpdateResponse__AgentPath = string;\nexport const V2ThreadMetadataUpdateResponse__AgentPath = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadMetadataUpdateResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadMetadataUpdateResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadMetadataUpdateResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadMetadataUpdateResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadMetadataUpdateResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadMetadataUpdateResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadMetadataUpdateResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__LegacyAppPathString = string;\nexport const V2ThreadMetadataUpdateResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadMetadataUpdateResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadMetadataUpdateResponse__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadMetadataUpdateResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadMetadataUpdateResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadMetadataUpdateResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadMetadataUpdateResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadMetadataUpdateResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadMetadataUpdateResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__ReasoningEffort = string;\nexport const V2ThreadMetadataUpdateResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadMetadataUpdateResponse__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadMetadataUpdateResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadMetadataUpdateResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadMetadataUpdateResponse__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadMetadataUpdateResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__ThreadId = string;\nexport const V2ThreadMetadataUpdateResponse__ThreadId = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__ThreadSource = string;\nexport const V2ThreadMetadataUpdateResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadMetadataUpdateResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadMetadataUpdateResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__AbsolutePathBuf = string;\nexport const V2ThreadReadResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadReadResponse__AgentPath = string;\nexport const V2ThreadReadResponse__AgentPath = Schema.String;\n\nexport type V2ThreadReadResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadReadResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadReadResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadReadResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadReadResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadReadResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadReadResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadReadResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadReadResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadReadResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadReadResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadReadResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadReadResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadReadResponse__LegacyAppPathString = string;\nexport const V2ThreadReadResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadReadResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadReadResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadReadResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadReadResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadReadResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadReadResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadReadResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadReadResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadReadResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadReadResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadReadResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadReadResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadReadResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadReadResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadReadResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadReadResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadReadResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadReadResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__ReasoningEffort = string;\nexport const V2ThreadReadResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadReadResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadReadResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadReadResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadReadResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadReadResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadReadResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadReadResponse__ThreadId = string;\nexport const V2ThreadReadResponse__ThreadId = Schema.String;\n\nexport type V2ThreadReadResponse__ThreadSource = string;\nexport const V2ThreadReadResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadReadResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadReadResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadReadResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadReadResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = {\n  readonly data: string;\n  readonly itemId?: string | null;\n  readonly numChannels: number;\n  readonly sampleRate: number;\n  readonly samplesPerChannel?: number | null;\n};\nexport const V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = Schema.Struct(\n  {\n    data: Schema.String,\n    itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    numChannels: Schema.Number.annotate({ format: \"uint16\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    sampleRate: Schema.Number.annotate({ format: \"uint32\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    samplesPerChannel: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n  },\n).annotate({ description: \"EXPERIMENTAL - thread realtime audio chunk.\" });\n\nexport type V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = \"v1\" | \"v2\" | \"v3\";\nexport const V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = Schema.Literals([\n  \"v1\",\n  \"v2\",\n  \"v3\",\n]);\n\nexport type V2ThreadResumeParams__AgentMessageInputContent =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2ThreadResumeParams__AgentMessageInputContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"InputTextAgentMessageInputContent\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"EncryptedContentAgentMessageInputContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadResumeParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadResumeParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadResumeParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadResumeParams__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadResumeParams__InternalChatMessageMetadataPassthrough = {\n  readonly turn_id?: string | null;\n};\nexport const V2ThreadResumeParams__InternalChatMessageMetadataPassthrough = Schema.Struct({\n  turn_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({\n  description:\n    \"Internal Responses API passthrough metadata copied into underlying chat messages.\\n\\nResponses API strongly types this payload. Do not modify it without first getting API approval and making the corresponding Responses API change.\",\n});\n\nexport type V2ThreadResumeParams__LocalShellAction = {\n  readonly command: ReadonlyArray<string>;\n  readonly env?: { readonly [x: string]: string } | null;\n  readonly timeout_ms?: number | null;\n  readonly type: \"exec\";\n  readonly user?: string | null;\n  readonly working_directory?: string | null;\n};\nexport const V2ThreadResumeParams__LocalShellAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.Array(Schema.String),\n      env: Schema.optionalKey(\n        Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n      ),\n      timeout_ms: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"exec\").annotate({ title: \"ExecLocalShellActionType\" }),\n      user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"ExecLocalShellAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__LocalShellStatus = \"completed\" | \"in_progress\" | \"incomplete\";\nexport const V2ThreadResumeParams__LocalShellStatus = Schema.Literals([\n  \"completed\",\n  \"in_progress\",\n  \"incomplete\",\n]);\n\nexport type V2ThreadResumeParams__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadResumeParams__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadResumeParams__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2ThreadResumeParams__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type V2ThreadResumeParams__ReasoningItemContent =\n  | { readonly text: string; readonly type: \"reasoning_text\" }\n  | { readonly text: string; readonly type: \"text\" };\nexport const V2ThreadResumeParams__ReasoningItemContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"reasoning_text\").annotate({\n        title: \"ReasoningTextReasoningItemContentType\",\n      }),\n    }).annotate({ title: \"ReasoningTextReasoningItemContent\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"text\").annotate({ title: \"TextReasoningItemContentType\" }),\n    }).annotate({ title: \"TextReasoningItemContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ReasoningItemReasoningSummary = {\n  readonly text: string;\n  readonly type: \"summary_text\";\n};\nexport const V2ThreadResumeParams__ReasoningItemReasoningSummary = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"summary_text\").annotate({\n        title: \"SummaryTextReasoningItemReasoningSummaryType\",\n      }),\n    }).annotate({ title: \"SummaryTextReasoningItemReasoningSummary\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ResponsesApiWebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"open_page\"; readonly url?: string | null }\n  | {\n      readonly pattern?: string | null;\n      readonly type: \"find_in_page\";\n      readonly url?: string | null;\n    }\n  | { readonly type: \"other\" };\nexport const V2ThreadResumeParams__ResponsesApiWebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"SearchResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"open_page\").annotate({\n        title: \"OpenPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"find_in_page\").annotate({\n        title: \"FindInPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"OtherResponsesApiWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ThreadResumeParams__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ThreadResumeParams__SortDirection = \"asc\" | \"desc\";\nexport const V2ThreadResumeParams__SortDirection = Schema.Literals([\"asc\", \"desc\"]);\n\nexport type V2ThreadResumeParams__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadResumeParams__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadResumeResponse__AbsolutePathBuf = string;\nexport const V2ThreadResumeResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadResumeResponse__AgentPath = string;\nexport const V2ThreadResumeResponse__AgentPath = Schema.String;\n\nexport type V2ThreadResumeResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadResumeResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadResumeResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadResumeResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadResumeResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadResumeResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadResumeResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadResumeResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadResumeResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadResumeResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadResumeResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadResumeResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadResumeResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadResumeResponse__LegacyAppPathString = string;\nexport const V2ThreadResumeResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadResumeResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadResumeResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadResumeResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadResumeResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadResumeResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadResumeResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadResumeResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadResumeResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadResumeResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadResumeResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadResumeResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadResumeResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadResumeResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadResumeResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadResumeResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadResumeResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadResumeResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__ReasoningEffort = string;\nexport const V2ThreadResumeResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadResumeResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadResumeResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadResumeResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadResumeResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadResumeResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadResumeResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadResumeResponse__ThreadId = string;\nexport const V2ThreadResumeResponse__ThreadId = Schema.String;\n\nexport type V2ThreadResumeResponse__ThreadSource = string;\nexport const V2ThreadResumeResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadResumeResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadResumeResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadResumeResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadResumeResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__AbsolutePathBuf = string;\nexport const V2ThreadRollbackResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadRollbackResponse__AgentPath = string;\nexport const V2ThreadRollbackResponse__AgentPath = Schema.String;\n\nexport type V2ThreadRollbackResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadRollbackResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadRollbackResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadRollbackResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadRollbackResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadRollbackResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadRollbackResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadRollbackResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadRollbackResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadRollbackResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadRollbackResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadRollbackResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadRollbackResponse__LegacyAppPathString = string;\nexport const V2ThreadRollbackResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadRollbackResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadRollbackResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadRollbackResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadRollbackResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadRollbackResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadRollbackResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadRollbackResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadRollbackResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadRollbackResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadRollbackResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadRollbackResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadRollbackResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadRollbackResponse__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadRollbackResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadRollbackResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadRollbackResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadRollbackResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__ReasoningEffort = string;\nexport const V2ThreadRollbackResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadRollbackResponse__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadRollbackResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadRollbackResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadRollbackResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadRollbackResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadRollbackResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadRollbackResponse__ThreadId = string;\nexport const V2ThreadRollbackResponse__ThreadId = Schema.String;\n\nexport type V2ThreadRollbackResponse__ThreadSource = string;\nexport const V2ThreadRollbackResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadRollbackResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadRollbackResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadRollbackResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadRollbackResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__AbsolutePathBuf = string;\nexport const V2ThreadSettingsUpdatedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadSettingsUpdatedNotification__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadSettingsUpdatedNotification__ApprovalsReviewer =\n  | \"user\"\n  | \"auto_review\"\n  | \"guardian_subagent\";\nexport const V2ThreadSettingsUpdatedNotification__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadSettingsUpdatedNotification__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__ModeKind = \"plan\" | \"default\";\nexport const V2ThreadSettingsUpdatedNotification__ModeKind = Schema.Literals([\n  \"plan\",\n  \"default\",\n]).annotate({ description: \"Initial collaboration mode to use when the TUI starts.\" });\n\nexport type V2ThreadSettingsUpdatedNotification__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2ThreadSettingsUpdatedNotification__Personality = Schema.Literals([\n  \"none\",\n  \"friendly\",\n  \"pragmatic\",\n]);\n\nexport type V2ThreadSettingsUpdatedNotification__ReasoningEffort = string;\nexport const V2ThreadSettingsUpdatedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadSettingsUpdatedNotification__ReasoningSummary =\n  | \"auto\"\n  | \"concise\"\n  | \"detailed\"\n  | \"none\";\nexport const V2ThreadSettingsUpdatedNotification__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type V2ThreadStartedNotification__AbsolutePathBuf = string;\nexport const V2ThreadStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadStartedNotification__AgentPath = string;\nexport const V2ThreadStartedNotification__AgentPath = Schema.String;\n\nexport type V2ThreadStartedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadStartedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadStartedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadStartedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartedNotification__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadStartedNotification__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadStartedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadStartedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadStartedNotification__LegacyAppPathString = string;\nexport const V2ThreadStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadStartedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadStartedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartedNotification__McpToolCallError = { readonly message: string };\nexport const V2ThreadStartedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadStartedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadStartedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadStartedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadStartedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadStartedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadStartedNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadStartedNotification__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadStartedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadStartedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__ReasoningEffort = string;\nexport const V2ThreadStartedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadStartedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadStartedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadStartedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadStartedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadStartedNotification__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadStartedNotification__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadStartedNotification__ThreadId = string;\nexport const V2ThreadStartedNotification__ThreadId = Schema.String;\n\nexport type V2ThreadStartedNotification__ThreadSource = string;\nexport const V2ThreadStartedNotification__ThreadSource = Schema.String;\n\nexport type V2ThreadStartedNotification__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadStartedNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadStartedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadStartedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadStartParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadStartParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadStartParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__DynamicToolNamespaceTool = {\n  readonly deferLoading?: boolean;\n  readonly description: string;\n  readonly inputSchema: unknown;\n  readonly name: string;\n  readonly type: \"function\";\n};\nexport const V2ThreadStartParams__DynamicToolNamespaceTool = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolNamespaceToolType\" }),\n    }).annotate({ title: \"FunctionDynamicToolNamespaceTool\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__LegacyAppPathString = string;\nexport const V2ThreadStartParams__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadStartParams__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2ThreadStartParams__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type V2ThreadStartParams__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ThreadStartParams__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ThreadStartParams__ThreadSource = string;\nexport const V2ThreadStartParams__ThreadSource = Schema.String;\n\nexport type V2ThreadStartParams__ThreadStartSource = \"startup\" | \"clear\";\nexport const V2ThreadStartParams__ThreadStartSource = Schema.Literals([\"startup\", \"clear\"]);\n\nexport type V2ThreadStartResponse__AbsolutePathBuf = string;\nexport const V2ThreadStartResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadStartResponse__AgentPath = string;\nexport const V2ThreadStartResponse__AgentPath = Schema.String;\n\nexport type V2ThreadStartResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadStartResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadStartResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadStartResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadStartResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadStartResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadStartResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadStartResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadStartResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadStartResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadStartResponse__LegacyAppPathString = string;\nexport const V2ThreadStartResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadStartResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadStartResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadStartResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadStartResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadStartResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadStartResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadStartResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadStartResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadStartResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadStartResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadStartResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadStartResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__ReasoningEffort = string;\nexport const V2ThreadStartResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadStartResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadStartResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadStartResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadStartResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadStartResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadStartResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadStartResponse__ThreadId = string;\nexport const V2ThreadStartResponse__ThreadId = Schema.String;\n\nexport type V2ThreadStartResponse__ThreadSource = string;\nexport const V2ThreadStartResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadStartResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadStartResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadStartResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadStartResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStatusChangedNotification__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadStatusChangedNotification__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = {\n  readonly cacheWriteInputTokens?: number;\n  readonly cachedInputTokens: number;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly reasoningOutputTokens: number;\n  readonly totalTokens: number;\n};\nexport const V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = Schema.Struct({\n  cacheWriteInputTokens: Schema.optionalKey(\n    Schema.Number.annotate({ default: 0, format: \"int64\" }).check(Schema.isInt()),\n  ),\n  cachedInputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  inputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  outputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  reasoningOutputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  totalTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadUnarchiveResponse__AbsolutePathBuf = string;\nexport const V2ThreadUnarchiveResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadUnarchiveResponse__AgentPath = string;\nexport const V2ThreadUnarchiveResponse__AgentPath = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadUnarchiveResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadUnarchiveResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadUnarchiveResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadUnarchiveResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadUnarchiveResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadUnarchiveResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadUnarchiveResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadUnarchiveResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadUnarchiveResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadUnarchiveResponse__LegacyAppPathString = string;\nexport const V2ThreadUnarchiveResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadUnarchiveResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadUnarchiveResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadUnarchiveResponse__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadUnarchiveResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadUnarchiveResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadUnarchiveResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadUnarchiveResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadUnarchiveResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadUnarchiveResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadUnarchiveResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadUnarchiveResponse__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadUnarchiveResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadUnarchiveResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadUnarchiveResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadUnarchiveResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__ReasoningEffort = string;\nexport const V2ThreadUnarchiveResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadUnarchiveResponse__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadUnarchiveResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadUnarchiveResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadUnarchiveResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadUnarchiveResponse__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadUnarchiveResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadUnarchiveResponse__ThreadId = string;\nexport const V2ThreadUnarchiveResponse__ThreadId = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__ThreadSource = string;\nexport const V2ThreadUnarchiveResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadUnarchiveResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadUnarchiveResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadUnarchiveResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus =\n  | \"notLoaded\"\n  | \"notSubscribed\"\n  | \"unsubscribed\";\nexport const V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus = Schema.Literals([\n  \"notLoaded\",\n  \"notSubscribed\",\n  \"unsubscribed\",\n]);\n\nexport type V2TurnCompletedNotification__AbsolutePathBuf = string;\nexport const V2TurnCompletedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnCompletedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2TurnCompletedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2TurnCompletedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnCompletedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnCompletedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2TurnCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnCompletedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnCompletedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2TurnCompletedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnCompletedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2TurnCompletedNotification__LegacyAppPathString = string;\nexport const V2TurnCompletedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2TurnCompletedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2TurnCompletedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2TurnCompletedNotification__McpToolCallError = { readonly message: string };\nexport const V2TurnCompletedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2TurnCompletedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2TurnCompletedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnCompletedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnCompletedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2TurnCompletedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2TurnCompletedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2TurnCompletedNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2TurnCompletedNotification__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2TurnCompletedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnCompletedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnCompletedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2TurnCompletedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__ReasoningEffort = string;\nexport const V2TurnCompletedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnCompletedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2TurnCompletedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2TurnCompletedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnCompletedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnCompletedNotification__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2TurnCompletedNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2TurnCompletedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2TurnCompletedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnPlanUpdatedNotification__TurnPlanStepStatus =\n  | \"pending\"\n  | \"inProgress\"\n  | \"completed\";\nexport const V2TurnPlanUpdatedNotification__TurnPlanStepStatus = Schema.Literals([\n  \"pending\",\n  \"inProgress\",\n  \"completed\",\n]);\n\nexport type V2TurnStartedNotification__AbsolutePathBuf = string;\nexport const V2TurnStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnStartedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2TurnStartedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2TurnStartedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2TurnStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnStartedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2TurnStartedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2TurnStartedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnStartedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2TurnStartedNotification__LegacyAppPathString = string;\nexport const V2TurnStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2TurnStartedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2TurnStartedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2TurnStartedNotification__McpToolCallError = { readonly message: string };\nexport const V2TurnStartedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2TurnStartedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2TurnStartedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2TurnStartedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2TurnStartedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2TurnStartedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2TurnStartedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2TurnStartedNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2TurnStartedNotification__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2TurnStartedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2TurnStartedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__ReasoningEffort = string;\nexport const V2TurnStartedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnStartedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2TurnStartedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2TurnStartedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnStartedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartedNotification__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2TurnStartedNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2TurnStartedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2TurnStartedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__AbsolutePathBuf = string;\nexport const V2TurnStartParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnStartParams__AdditionalContextKind = \"untrusted\" | \"application\";\nexport const V2TurnStartParams__AdditionalContextKind = Schema.Literals([\n  \"untrusted\",\n  \"application\",\n]);\n\nexport type V2TurnStartParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2TurnStartParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2TurnStartParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2TurnStartParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnStartParams__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type V2TurnStartParams__LegacyAppPathString = string;\nexport const V2TurnStartParams__LegacyAppPathString = Schema.String;\n\nexport type V2TurnStartParams__ModeKind = \"plan\" | \"default\";\nexport const V2TurnStartParams__ModeKind = Schema.Literals([\"plan\", \"default\"]).annotate({\n  description: \"Initial collaboration mode to use when the TUI starts.\",\n});\n\nexport type V2TurnStartParams__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2TurnStartParams__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type V2TurnStartParams__ReasoningEffort = string;\nexport const V2TurnStartParams__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnStartParams__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const V2TurnStartParams__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type V2TurnStartParams__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnStartParams__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartResponse__AbsolutePathBuf = string;\nexport const V2TurnStartResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnStartResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2TurnStartResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2TurnStartResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2TurnStartResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2TurnStartResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2TurnStartResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnStartResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2TurnStartResponse__LegacyAppPathString = string;\nexport const V2TurnStartResponse__LegacyAppPathString = Schema.String;\n\nexport type V2TurnStartResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2TurnStartResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2TurnStartResponse__McpToolCallError = { readonly message: string };\nexport const V2TurnStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2TurnStartResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2TurnStartResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2TurnStartResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2TurnStartResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2TurnStartResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2TurnStartResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2TurnStartResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2TurnStartResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2TurnStartResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2TurnStartResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__ReasoningEffort = string;\nexport const V2TurnStartResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnStartResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2TurnStartResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2TurnStartResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnStartResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartResponse__TurnStatus = \"completed\" | \"interrupted\" | \"failed\" | \"inProgress\";\nexport const V2TurnStartResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2TurnStartResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2TurnStartResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnSteerParams__AdditionalContextKind = \"untrusted\" | \"application\";\nexport const V2TurnSteerParams__AdditionalContextKind = Schema.Literals([\n  \"untrusted\",\n  \"application\",\n]);\n\nexport type V2TurnSteerParams__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnSteerParams__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type V2TurnSteerParams__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnSteerParams__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness =\n  | \"ready\"\n  | \"notConfigured\"\n  | \"updateRequired\";\nexport const V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness = Schema.Literals([\n  \"ready\",\n  \"notConfigured\",\n  \"updateRequired\",\n]);\n\nexport type V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode =\n  | \"elevated\"\n  | \"unelevated\";\nexport const V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type V2WindowsSandboxSetupStartParams__AbsolutePathBuf = string;\nexport const V2WindowsSandboxSetupStartParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type ApplyPatchApprovalResponse__NetworkPolicyAmendment = {\n  readonly action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const ApplyPatchApprovalResponse__NetworkPolicyAmendment = Schema.Struct({\n  action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type ClientRequest__PluginInstallParams = {\n  readonly marketplacePath?: ClientRequest__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const ClientRequest__PluginInstallParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__PluginInstalledParams = {\n  readonly cwds?: ReadonlyArray<ClientRequest__AbsolutePathBuf> | null;\n  readonly installSuggestionPluginNames?: ReadonlyArray<string> | null;\n};\nexport const ClientRequest__PluginInstalledParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__AbsolutePathBuf).annotate({\n        description: \"Optional working directories used to discover repo marketplaces.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  installSuggestionPluginNames: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Additional uninstalled plugin names that should be returned when present locally. This is used by mention surfaces that intentionally expose install entrypoints.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__PluginReadParams = {\n  readonly marketplacePath?: ClientRequest__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const ClientRequest__PluginReadParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<ClientRequest__AbsolutePathBuf>;\n    };\nexport const ClientRequest__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__SkillsConfigWriteParams = {\n  readonly enabled: boolean;\n  readonly name?: string | null;\n  readonly path?: ClientRequest__AbsolutePathBuf | null;\n};\nexport const ClientRequest__SkillsConfigWriteParams = Schema.Struct({\n  enabled: Schema.Boolean,\n  name: Schema.optionalKey(\n    Schema.Union([Schema.String.annotate({ description: \"Name-based selector.\" }), Schema.Null]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Path-based selector.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__SkillsExtraRootsSetParams = {\n  readonly extraRoots: ReadonlyArray<ClientRequest__AbsolutePathBuf>;\n};\nexport const ClientRequest__SkillsExtraRootsSetParams = Schema.Struct({\n  extraRoots: Schema.Array(ClientRequest__AbsolutePathBuf),\n});\n\nexport type ClientRequest__SendAddCreditsNudgeEmailParams = {\n  readonly creditType: ClientRequest__AddCreditsNudgeCreditType;\n};\nexport const ClientRequest__SendAddCreditsNudgeEmailParams = Schema.Struct({\n  creditType: ClientRequest__AddCreditsNudgeCreditType,\n});\n\nexport type ClientRequest__ContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly text: string; readonly type: \"output_text\" };\nexport const ClientRequest__ContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({ title: \"InputTextContentItemType\" }),\n    }).annotate({ title: \"InputTextContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({ title: \"InputImageContentItemType\" }),\n    }).annotate({ title: \"InputImageContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({ title: \"InputAudioContentItemType\" }),\n    }).annotate({ title: \"InputAudioContentItem\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"output_text\").annotate({ title: \"OutputTextContentItemType\" }),\n    }).annotate({ title: \"OutputTextContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__FunctionCallOutputContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const ClientRequest__FunctionCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({\n        title: \"InputImageFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({\n        title: \"InputAudioFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"EncryptedContentFunctionCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.\",\n});\n\nexport type ClientRequest__InitializeParams = {\n  readonly capabilities?: ClientRequest__InitializeCapabilities | null;\n  readonly clientInfo: ClientRequest__ClientInfo;\n};\nexport const ClientRequest__InitializeParams = Schema.Struct({\n  capabilities: Schema.optionalKey(\n    Schema.Union([ClientRequest__InitializeCapabilities, Schema.Null]),\n  ),\n  clientInfo: ClientRequest__ClientInfo,\n});\n\nexport type ClientRequest__LoginAccountParams =\n  | { readonly apiKey: string; readonly type: \"apiKey\" }\n  | {\n      readonly appBrand?: ClientRequest__LoginAppBrand | null;\n      readonly codexStreamlinedLogin?: boolean;\n      readonly type: \"chatgpt\";\n      readonly useHostedLoginSuccessPage?: boolean;\n    }\n  | { readonly type: \"chatgptDeviceCode\" }\n  | {\n      readonly accessToken: string;\n      readonly chatgptAccountId: string;\n      readonly chatgptPlanType?: string | null;\n      readonly type: \"chatgptAuthTokens\";\n    }\n  | { readonly apiKey: string; readonly region: string; readonly type: \"amazonBedrock\" };\nexport const ClientRequest__LoginAccountParams = Schema.Union(\n  [\n    Schema.Struct({\n      apiKey: Schema.String,\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyLoginAccountParamsType\" }),\n    }).annotate({ title: \"ApiKeyLoginAccountParams\" }),\n    Schema.Struct({\n      appBrand: Schema.optionalKey(Schema.Union([ClientRequest__LoginAppBrand, Schema.Null])),\n      codexStreamlinedLogin: Schema.optionalKey(Schema.Boolean),\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"ChatgptLoginAccountParamsType\" }),\n      useHostedLoginSuccessPage: Schema.optionalKey(Schema.Boolean),\n    }).annotate({ title: \"ChatgptLoginAccountParams\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"chatgptDeviceCode\").annotate({\n        title: \"ChatgptDeviceCodeLoginAccountParamsType\",\n      }),\n    }).annotate({ title: \"ChatgptDeviceCodeLoginAccountParams\" }),\n    Schema.Struct({\n      accessToken: Schema.String.annotate({\n        description:\n          \"Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.\",\n      }),\n      chatgptAccountId: Schema.String.annotate({\n        description: \"Workspace/account identifier supplied by the client.\",\n      }),\n      chatgptPlanType: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional plan type supplied by the client.\\n\\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"chatgptAuthTokens\").annotate({\n        title: \"ChatgptAuthTokensLoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"ChatgptAuthTokensLoginAccountParams\",\n      description:\n        \"[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.\",\n    }),\n    Schema.Struct({\n      apiKey: Schema.String,\n      region: Schema.String,\n      type: Schema.Literal(\"amazonBedrock\").annotate({\n        title: \"AmazonBedrockLoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"AmazonBedrockLoginAccountParams\",\n      description: \"[UNSTABLE] Managed Amazon Bedrock login is experimental.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ListMcpServerStatusParams = {\n  readonly cursor?: string | null;\n  readonly detail?: ClientRequest__McpServerStatusDetail | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__ListMcpServerStatusParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  detail: Schema.optionalKey(\n    Schema.Union([ClientRequest__McpServerStatusDetail, Schema.Null]).annotate({\n      description:\n        \"Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a server-defined value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__ConfigEdit = {\n  readonly keyPath: string;\n  readonly mergeStrategy: ClientRequest__MergeStrategy;\n  readonly value: unknown;\n};\nexport const ClientRequest__ConfigEdit = Schema.Struct({\n  keyPath: Schema.String,\n  mergeStrategy: ClientRequest__MergeStrategy,\n  value: Schema.Unknown,\n});\n\nexport type ClientRequest__ConfigValueWriteParams = {\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly keyPath: string;\n  readonly mergeStrategy: ClientRequest__MergeStrategy;\n  readonly value: unknown;\n};\nexport const ClientRequest__ConfigValueWriteParams = Schema.Struct({\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  keyPath: Schema.String,\n  mergeStrategy: ClientRequest__MergeStrategy,\n  value: Schema.Unknown,\n});\n\nexport type ClientRequest__PluginListParams = {\n  readonly cwds?: ReadonlyArray<ClientRequest__AbsolutePathBuf> | null;\n  readonly marketplaceKinds?: ReadonlyArray<ClientRequest__PluginListMarketplaceKind> | null;\n};\nexport const ClientRequest__PluginListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__AbsolutePathBuf).annotate({\n        description:\n          \"Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  marketplaceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__PluginListMarketplaceKind).annotate({\n        description:\n          \"Optional marketplace kind filter. When omitted, only local marketplaces are queried, plus the default remote catalog when enabled by feature flag.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__PluginShareTarget = {\n  readonly principalId: string;\n  readonly principalType: ClientRequest__PluginSharePrincipalType;\n  readonly role: ClientRequest__PluginShareTargetRole;\n};\nexport const ClientRequest__PluginShareTarget = Schema.Struct({\n  principalId: Schema.String,\n  principalType: ClientRequest__PluginSharePrincipalType,\n  role: ClientRequest__PluginShareTargetRole,\n});\n\nexport type ClientRequest__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: ClientRequest__ReasoningEffort | null;\n};\nexport const ClientRequest__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(Schema.Union([ClientRequest__ReasoningEffort, Schema.Null])),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type ClientRequest__ReviewStartParams = {\n  readonly delivery?: ClientRequest__ReviewDelivery | null;\n  readonly target: ClientRequest__ReviewTarget;\n  readonly threadId: string;\n};\nexport const ClientRequest__ReviewStartParams = Schema.Struct({\n  delivery: Schema.optionalKey(\n    Schema.Union([ClientRequest__ReviewDelivery, Schema.Null]).annotate({\n      description:\n        \"Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).\",\n    }),\n  ),\n  target: ClientRequest__ReviewTarget,\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadResumeParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: ClientRequest__Personality | null;\n  readonly sandbox?: ClientRequest__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadResumeParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the resumed thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({\n  description:\n    \"There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\\n\\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\\n\\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type ClientRequest__MigrationDetails = {\n  readonly commands?: ReadonlyArray<ClientRequest__CommandMigration>;\n  readonly hooks?: ReadonlyArray<ClientRequest__HookMigration>;\n  readonly mcpServers?: ReadonlyArray<ClientRequest__McpServerMigration>;\n  readonly memory?: ReadonlyArray<string>;\n  readonly plugins?: ReadonlyArray<ClientRequest__PluginsMigration>;\n  readonly sessions?: ReadonlyArray<ClientRequest__SessionMigration>;\n  readonly skills?: ReadonlyArray<ClientRequest__SkillMigration>;\n  readonly subagents?: ReadonlyArray<ClientRequest__SubagentMigration>;\n};\nexport const ClientRequest__MigrationDetails = Schema.Struct({\n  commands: Schema.optionalKey(\n    Schema.Array(ClientRequest__CommandMigration).annotate({ default: [] }),\n  ),\n  hooks: Schema.optionalKey(Schema.Array(ClientRequest__HookMigration).annotate({ default: [] })),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(ClientRequest__McpServerMigration).annotate({ default: [] }),\n  ),\n  memory: Schema.optionalKey(Schema.Array(Schema.String)),\n  plugins: Schema.optionalKey(\n    Schema.Array(ClientRequest__PluginsMigration).annotate({ default: [] }),\n  ),\n  sessions: Schema.optionalKey(\n    Schema.Array(ClientRequest__SessionMigration).annotate({ default: [] }),\n  ),\n  skills: Schema.optionalKey(Schema.Array(ClientRequest__SkillMigration).annotate({ default: [] })),\n  subagents: Schema.optionalKey(\n    Schema.Array(ClientRequest__SubagentMigration).annotate({ default: [] }),\n  ),\n});\n\nexport type ClientRequest__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<ClientRequest__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const ClientRequest__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(ClientRequest__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ThreadGoalSetParams = {\n  readonly objective?: string | null;\n  readonly status?: ClientRequest__ThreadGoalStatus | null;\n  readonly threadId: string;\n  readonly tokenBudget?: number | null;\n};\nexport const ClientRequest__ThreadGoalSetParams = Schema.Struct({\n  objective: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: Schema.optionalKey(Schema.Union([ClientRequest__ThreadGoalStatus, Schema.Null])),\n  threadId: Schema.String,\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type ClientRequest__ThreadMetadataUpdateParams = {\n  readonly gitInfo?: ClientRequest__ThreadMetadataGitInfoUpdateParams | null;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadMetadataUpdateParams = Schema.Struct({\n  gitInfo: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadMetadataGitInfoUpdateParams, Schema.Null]).annotate({\n      description:\n        \"Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.\",\n    }),\n  ),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadForkParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean;\n  readonly lastTurnId?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly sandbox?: ClientRequest__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n  readonly threadSource?: ClientRequest__ThreadSource | null;\n};\nexport const ClientRequest__ThreadForkParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n  lastTurnId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional last turn id to fork through, inclusive.\\n\\nWhen specified, turns after `last_turn_id` are omitted from the fork. The referenced turn cannot be in progress.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the forked thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  threadSource: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadSource, Schema.Null]).annotate({\n      description:\n        \"Optional client-supplied analytics source classification for this forked thread.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\\n\\nIf using a non-empty path, the thread_id param will be ignored. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type ClientRequest__ThreadListParams = {\n  readonly archived?: boolean | null;\n  readonly cursor?: string | null;\n  readonly cwd?: ClientRequest__ThreadListCwdFilter | null;\n  readonly limit?: number | null;\n  readonly modelProviders?: ReadonlyArray<string> | null;\n  readonly searchTerm?: string | null;\n  readonly sortDirection?: ClientRequest__SortDirection | null;\n  readonly sortKey?: ClientRequest__ThreadSortKey | null;\n  readonly sourceKinds?: ReadonlyArray<ClientRequest__ThreadSourceKind> | null;\n  readonly useStateDbOnly?: boolean;\n};\nexport const ClientRequest__ThreadListParams = Schema.Struct({\n  archived: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadListCwdFilter, Schema.Null]).annotate({\n      description:\n        \"Optional cwd filter or filters; when set, only threads whose session cwd exactly matches one of these paths are returned.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  modelProviders: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  searchTerm: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional substring filter for the extracted thread title.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([ClientRequest__SortDirection, Schema.Null]).annotate({\n      description: \"Optional sort direction; defaults to descending (newest first).\",\n    }),\n  ),\n  sortKey: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadSortKey, Schema.Null]).annotate({\n      description: \"Optional sort key; defaults to created_at.\",\n    }),\n  ),\n  sourceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__ThreadSourceKind).annotate({\n        description:\n          \"Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  useStateDbOnly: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"If true, return from the state DB without scanning JSONL rollouts to repair thread metadata. Omitted or false preserves scan-and-repair behavior.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__ThreadStartParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: ClientRequest__Personality | null;\n  readonly sandbox?: ClientRequest__SandboxMode | null;\n  readonly serviceName?: string | null;\n  readonly serviceTier?: string | null;\n  readonly sessionStartSource?: ClientRequest__ThreadStartSource | null;\n  readonly threadSource?: ClientRequest__ThreadSource | null;\n};\nexport const ClientRequest__ThreadStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),\n  serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sessionStartSource: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadStartSource, Schema.Null]),\n  ),\n  threadSource: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional client-supplied analytics source classification for this thread.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__WindowsSandboxSetupStartParams = {\n  readonly cwd?: ClientRequest__AbsolutePathBuf | null;\n  readonly mode: ClientRequest__WindowsSandboxSetupMode;\n};\nexport const ClientRequest__WindowsSandboxSetupStartParams = Schema.Struct({\n  cwd: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),\n  mode: ClientRequest__WindowsSandboxSetupMode,\n});\n\nexport type CommandExecutionRequestApprovalParams__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: CommandExecutionRequestApprovalParams__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const CommandExecutionRequestApprovalParams__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: CommandExecutionRequestApprovalParams__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalParams__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: CommandExecutionRequestApprovalParams__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: CommandExecutionRequestApprovalParams__LegacyAppPathString | null;\n    };\nexport const CommandExecutionRequestApprovalParams__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([CommandExecutionRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([CommandExecutionRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalParams__NetworkApprovalContext = {\n  readonly host: string;\n  readonly protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol;\n};\nexport const CommandExecutionRequestApprovalParams__NetworkApprovalContext = Schema.Struct({\n  host: Schema.String,\n  protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol,\n});\n\nexport type CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = {\n  readonly action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = Schema.Struct({\n  action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = {\n  readonly action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = Schema.Struct({\n  action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type ExecCommandApprovalResponse__NetworkPolicyAmendment = {\n  readonly action: ExecCommandApprovalResponse__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const ExecCommandApprovalResponse__NetworkPolicyAmendment = Schema.Struct({\n  action: ExecCommandApprovalResponse__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type FuzzyFileSearchResponse__FuzzyFileSearchResult = {\n  readonly file_name: string;\n  readonly indices?: ReadonlyArray<number> | null;\n  readonly match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType;\n  readonly path: string;\n  readonly root: string;\n  readonly score: number;\n};\nexport const FuzzyFileSearchResponse__FuzzyFileSearchResult = Schema.Struct({\n  file_name: Schema.String,\n  indices: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType,\n  path: Schema.String,\n  root: Schema.String,\n  score: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"Superset of [`codex_file_search::FileMatch`]\" });\n\nexport type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = {\n  readonly file_name: string;\n  readonly indices?: ReadonlyArray<number> | null;\n  readonly match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType;\n  readonly path: string;\n  readonly root: string;\n  readonly score: number;\n};\nexport const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = Schema.Struct({\n  file_name: Schema.String,\n  indices: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType,\n  path: Schema.String,\n  root: Schema.String,\n  score: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"Superset of [`codex_file_search::FileMatch`]\" });\n\nexport type JSONRPCMessage__JSONRPCError = {\n  readonly error: JSONRPCMessage__JSONRPCErrorError;\n  readonly id: JSONRPCMessage__RequestId;\n};\nexport const JSONRPCMessage__JSONRPCError = Schema.Struct({\n  error: JSONRPCMessage__JSONRPCErrorError,\n  id: JSONRPCMessage__RequestId,\n}).annotate({ description: \"A response to a request that indicates an error occurred.\" });\n\nexport type JSONRPCMessage__JSONRPCResponse = {\n  readonly id: JSONRPCMessage__RequestId;\n  readonly result: unknown;\n};\nexport const JSONRPCMessage__JSONRPCResponse = Schema.Struct({\n  id: JSONRPCMessage__RequestId,\n  result: Schema.Unknown,\n}).annotate({ description: \"A successful (non-error) response to a request.\" });\n\nexport type JSONRPCMessage__JSONRPCRequest = {\n  readonly id: JSONRPCMessage__RequestId;\n  readonly method: string;\n  readonly params?: unknown;\n  readonly trace?: JSONRPCMessage__W3cTraceContext | null;\n};\nexport const JSONRPCMessage__JSONRPCRequest = Schema.Struct({\n  id: JSONRPCMessage__RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n  trace: Schema.optionalKey(\n    Schema.Union([JSONRPCMessage__W3cTraceContext, Schema.Null]).annotate({\n      description: \"Optional W3C Trace Context for distributed tracing.\",\n    }),\n  ),\n}).annotate({ description: \"A request that expects a response.\" });\n\nexport type McpServerElicitationRequestParams__McpElicitationBooleanSchema = {\n  readonly default?: boolean | null;\n  readonly description?: string | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationBooleanType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationBooleanSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationBooleanType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationTitledEnumItems = {\n  readonly anyOf: ReadonlyArray<McpServerElicitationRequestParams__McpElicitationConstOption>;\n};\nexport const McpServerElicitationRequestParams__McpElicitationTitledEnumItems = Schema.Struct({\n  anyOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption),\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationNumberSchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationNumberType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationNumberSchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationNumberType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly enumNames?: ReadonlyArray<string> | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    enum: Schema.Array(Schema.String),\n    enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationStringType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationStringSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly format?: McpServerElicitationRequestParams__McpElicitationStringFormat | null;\n  readonly maxLength?: number | null;\n  readonly minLength?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationStringSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  format: Schema.optionalKey(\n    Schema.Union([McpServerElicitationRequestParams__McpElicitationStringFormat, Schema.Null]),\n  ),\n  maxLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationStringType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly oneOf: ReadonlyArray<McpServerElicitationRequestParams__McpElicitationConstOption>;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    oneOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationStringType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = {\n  readonly enum: ReadonlyArray<string>;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = Schema.Struct({\n  enum: Schema.Array(Schema.String),\n  type: McpServerElicitationRequestParams__McpElicitationStringType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    enum: Schema.Array(Schema.String),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationStringType,\n  });\n\nexport type PermissionsRequestApprovalParams__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: PermissionsRequestApprovalParams__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: PermissionsRequestApprovalParams__LegacyAppPathString | null;\n    };\nexport const PermissionsRequestApprovalParams__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type PermissionsRequestApprovalResponse__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: PermissionsRequestApprovalResponse__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: PermissionsRequestApprovalResponse__LegacyAppPathString | null;\n    };\nexport const PermissionsRequestApprovalResponse__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalResponse__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalResponse__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: ServerNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const ServerNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: ServerNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__FsChangedNotification = {\n  readonly changedPaths: ReadonlyArray<ServerNotification__AbsolutePathBuf>;\n  readonly watchId: string;\n};\nexport const ServerNotification__FsChangedNotification = Schema.Struct({\n  changedPaths: Schema.Array(ServerNotification__AbsolutePathBuf).annotate({\n    description: \"File or directory paths associated with this event.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({ description: \"Filesystem watch notification emitted for `fs/watch` subscribers.\" });\n\nexport type ServerNotification__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<ServerNotification__AbsolutePathBuf>;\n    };\nexport const ServerNotification__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(ServerNotification__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__AppMetadata = {\n  readonly categories?: ReadonlyArray<string> | null;\n  readonly developer?: string | null;\n  readonly firstPartyRequiresInstall?: boolean | null;\n  readonly firstPartyType?: string | null;\n  readonly review?: ServerNotification__AppReview | null;\n  readonly screenshots?: ReadonlyArray<ServerNotification__AppScreenshot> | null;\n  readonly seoDescription?: string | null;\n  readonly showInComposerWhenUnlinked?: boolean | null;\n  readonly subCategories?: ReadonlyArray<string> | null;\n  readonly version?: string | null;\n  readonly versionId?: string | null;\n  readonly versionNotes?: string | null;\n};\nexport const ServerNotification__AppMetadata = Schema.Struct({\n  categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  review: Schema.optionalKey(Schema.Union([ServerNotification__AppReview, Schema.Null])),\n  screenshots: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerNotification__AppScreenshot), Schema.Null]),\n  ),\n  seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: ServerNotification__CollabAgentStatus;\n};\nexport const ServerNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: ServerNotification__CollabAgentStatus,\n});\n\nexport type ServerNotification__ExternalAgentConfigImportItemTypeFailure = {\n  readonly cwd?: string | null;\n  readonly errorType?: string | null;\n  readonly failureStage: string;\n  readonly itemType: ServerNotification__ExternalAgentConfigMigrationItemType;\n  readonly message: string;\n  readonly source?: string | null;\n  readonly subErrorType?: string | null;\n};\nexport const ServerNotification__ExternalAgentConfigImportItemTypeFailure = Schema.Struct({\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  failureStage: Schema.String,\n  itemType: ServerNotification__ExternalAgentConfigMigrationItemType,\n  message: Schema.String,\n  source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__ExternalAgentConfigImportItemTypeSuccess = {\n  readonly cwd?: string | null;\n  readonly itemType: ServerNotification__ExternalAgentConfigMigrationItemType;\n  readonly source?: string | null;\n  readonly target?: string | null;\n};\nexport const ServerNotification__ExternalAgentConfigImportItemTypeSuccess = Schema.Struct({\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  itemType: ServerNotification__ExternalAgentConfigMigrationItemType,\n  source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__FuzzyFileSearchResult = {\n  readonly file_name: string;\n  readonly indices?: ReadonlyArray<number> | null;\n  readonly match_type: ServerNotification__FuzzyFileSearchMatchType;\n  readonly path: string;\n  readonly root: string;\n  readonly score: number;\n};\nexport const ServerNotification__FuzzyFileSearchResult = Schema.Struct({\n  file_name: Schema.String,\n  indices: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  match_type: ServerNotification__FuzzyFileSearchMatchType,\n  path: Schema.String,\n  root: Schema.String,\n  score: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"Superset of [`codex_file_search::FileMatch`]\" });\n\nexport type ServerNotification__GuardianApprovalReview = {\n  readonly rationale?: string | null;\n  readonly riskLevel?: ServerNotification__GuardianRiskLevel | null;\n  readonly status: ServerNotification__GuardianApprovalReviewStatus;\n  readonly userAuthorization?: ServerNotification__GuardianUserAuthorization | null;\n};\nexport const ServerNotification__GuardianApprovalReview = Schema.Struct({\n  rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  riskLevel: Schema.optionalKey(Schema.Union([ServerNotification__GuardianRiskLevel, Schema.Null])),\n  status: ServerNotification__GuardianApprovalReviewStatus,\n  userAuthorization: Schema.optionalKey(\n    Schema.Union([ServerNotification__GuardianUserAuthorization, Schema.Null]),\n  ),\n}).annotate({\n  description:\n    \"[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.\",\n});\n\nexport type ServerNotification__HookOutputEntry = {\n  readonly kind: ServerNotification__HookOutputEntryKind;\n  readonly text: string;\n};\nexport const ServerNotification__HookOutputEntry = Schema.Struct({\n  kind: ServerNotification__HookOutputEntryKind,\n  text: Schema.String,\n});\n\nexport type ServerNotification__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: ServerNotification__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: ServerNotification__LegacyAppPathString | null;\n    };\nexport const ServerNotification__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([ServerNotification__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([ServerNotification__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__McpServerStatusUpdatedNotification = {\n  readonly error?: string | null;\n  readonly failureReason?: ServerNotification__McpServerStartupFailureReason | null;\n  readonly name: string;\n  readonly status: ServerNotification__McpServerStartupState;\n  readonly threadId?: string | null;\n};\nexport const ServerNotification__McpServerStatusUpdatedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  failureReason: Schema.optionalKey(\n    Schema.Union([ServerNotification__McpServerStartupFailureReason, Schema.Null]),\n  ),\n  name: Schema.String,\n  status: ServerNotification__McpServerStartupState,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<ServerNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const ServerNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(ServerNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type ServerNotification__ModelReroutedNotification = {\n  readonly fromModel: string;\n  readonly reason: ServerNotification__ModelRerouteReason;\n  readonly threadId: string;\n  readonly toModel: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ModelReroutedNotification = Schema.Struct({\n  fromModel: Schema.String,\n  reason: ServerNotification__ModelRerouteReason,\n  threadId: Schema.String,\n  toModel: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ModelVerificationNotification = {\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly verifications: ReadonlyArray<ServerNotification__ModelVerification>;\n};\nexport const ServerNotification__ModelVerificationNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n  verifications: Schema.Array(ServerNotification__ModelVerification),\n});\n\nexport type ServerNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: ServerNotification__NonSteerableTurnKind;\n      };\n    };\nexport const ServerNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({ turnKind: ServerNotification__NonSteerableTurnKind }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type ServerNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: ServerNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const ServerNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: ServerNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type ServerNotification__AccountUpdatedNotification = {\n  readonly authMode?: ServerNotification__AuthMode | null;\n  readonly planType?: ServerNotification__PlanType | null;\n};\nexport const ServerNotification__AccountUpdatedNotification = Schema.Struct({\n  authMode: Schema.optionalKey(Schema.Union([ServerNotification__AuthMode, Schema.Null])),\n  planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])),\n});\n\nexport type ServerNotification__ThreadRealtimeStartedNotification = {\n  readonly realtimeSessionId?: string | null;\n  readonly threadId: string;\n  readonly version: ServerNotification__RealtimeConversationVersion;\n};\nexport const ServerNotification__ThreadRealtimeStartedNotification = Schema.Struct({\n  realtimeSessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  version: ServerNotification__RealtimeConversationVersion,\n}).annotate({ description: \"EXPERIMENTAL - emitted when thread realtime startup is accepted.\" });\n\nexport type ServerNotification__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: ServerNotification__ReasoningEffort | null;\n};\nexport const ServerNotification__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(\n    Schema.Union([ServerNotification__ReasoningEffort, Schema.Null]),\n  ),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type ServerNotification__RemoteControlStatusChangedNotification = {\n  readonly environmentId?: string | null;\n  readonly installationId: string;\n  readonly serverName: string;\n  readonly status: ServerNotification__RemoteControlConnectionStatus;\n};\nexport const ServerNotification__RemoteControlStatusChangedNotification = Schema.Struct({\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  installationId: Schema.String,\n  serverName: Schema.String,\n  status: ServerNotification__RemoteControlConnectionStatus,\n}).annotate({\n  description: \"Current remote-control connection status and remote identity exposed to clients.\",\n});\n\nexport type ServerNotification__ServerRequestResolvedNotification = {\n  readonly requestId: ServerNotification__RequestId;\n  readonly threadId: string;\n};\nexport const ServerNotification__ServerRequestResolvedNotification = Schema.Struct({\n  requestId: ServerNotification__RequestId,\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__RateLimitSnapshot = {\n  readonly credits?: ServerNotification__CreditsSnapshot | null;\n  readonly individualLimit?: ServerNotification__SpendControlLimitSnapshot | null;\n  readonly limitId?: string | null;\n  readonly limitName?: string | null;\n  readonly planType?: ServerNotification__PlanType | null;\n  readonly primary?: ServerNotification__RateLimitWindow | null;\n  readonly rateLimitReachedType?: ServerNotification__RateLimitReachedType | null;\n  readonly secondary?: ServerNotification__RateLimitWindow | null;\n  readonly spendControlReached?: boolean | null;\n};\nexport const ServerNotification__RateLimitSnapshot = Schema.Struct({\n  credits: Schema.optionalKey(Schema.Union([ServerNotification__CreditsSnapshot, Schema.Null])),\n  individualLimit: Schema.optionalKey(\n    Schema.Union([ServerNotification__SpendControlLimitSnapshot, Schema.Null]),\n  ),\n  limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])),\n  primary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])),\n  rateLimitReachedType: Schema.optionalKey(\n    Schema.Union([ServerNotification__RateLimitReachedType, Schema.Null]),\n  ),\n  secondary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])),\n  spendControlReached: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<ServerNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: ServerNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: ServerNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const ServerNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(ServerNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ServerNotification__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ServerNotification__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__TextRange = {\n  readonly end: ServerNotification__TextPosition;\n  readonly start: ServerNotification__TextPosition;\n};\nexport const ServerNotification__TextRange = Schema.Struct({\n  end: ServerNotification__TextPosition,\n  start: ServerNotification__TextPosition,\n});\n\nexport type ServerNotification__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<ServerNotification__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const ServerNotification__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: ServerNotification__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const ServerNotification__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: ServerNotification__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type ServerNotification__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: ServerNotification__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: ServerNotification__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const ServerNotification__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(Schema.Union([ServerNotification__AgentPath, Schema.Null])),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: ServerNotification__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = {\n  readonly audio: ServerNotification__ThreadRealtimeAudioChunk;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({\n  audio: ServerNotification__ThreadRealtimeAudioChunk,\n  threadId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - streamed output audio emitted by thread realtime.\" });\n\nexport type ServerNotification__ThreadTokenUsage = {\n  readonly last: ServerNotification__TokenUsageBreakdown;\n  readonly modelContextWindow?: number | null;\n  readonly total: ServerNotification__TokenUsageBreakdown;\n};\nexport const ServerNotification__ThreadTokenUsage = Schema.Struct({\n  last: ServerNotification__TokenUsageBreakdown,\n  modelContextWindow: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  total: ServerNotification__TokenUsageBreakdown,\n});\n\nexport type ServerNotification__TurnPlanStep = {\n  readonly status: ServerNotification__TurnPlanStepStatus;\n  readonly step: string;\n};\nexport const ServerNotification__TurnPlanStep = Schema.Struct({\n  status: ServerNotification__TurnPlanStepStatus,\n  step: Schema.String,\n});\n\nexport type ServerNotification__WindowsSandboxSetupCompletedNotification = {\n  readonly error?: string | null;\n  readonly mode: ServerNotification__WindowsSandboxSetupMode;\n  readonly success: boolean;\n};\nexport const ServerNotification__WindowsSandboxSetupCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mode: ServerNotification__WindowsSandboxSetupMode,\n  success: Schema.Boolean,\n});\n\nexport type ServerRequest__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: ServerRequest__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const ServerRequest__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: ServerRequest__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__ChatgptAuthTokensRefreshParams = {\n  readonly previousAccountId?: string | null;\n  readonly reason: ServerRequest__ChatgptAuthTokensRefreshReason;\n};\nexport const ServerRequest__ChatgptAuthTokensRefreshParams = Schema.Struct({\n  previousAccountId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Workspace/account identifier that Codex was previously using.\\n\\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\\n\\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: ServerRequest__ChatgptAuthTokensRefreshReason,\n});\n\nexport type ServerRequest__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | { readonly kind: \"project_roots\"; readonly subpath?: ServerRequest__LegacyAppPathString | null }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: ServerRequest__LegacyAppPathString | null;\n    };\nexport const ServerRequest__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(Schema.Union([ServerRequest__LegacyAppPathString, Schema.Null])),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(Schema.Union([ServerRequest__LegacyAppPathString, Schema.Null])),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__McpElicitationBooleanSchema = {\n  readonly default?: boolean | null;\n  readonly description?: string | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationBooleanType;\n};\nexport const ServerRequest__McpElicitationBooleanSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationBooleanType,\n});\n\nexport type ServerRequest__McpElicitationTitledEnumItems = {\n  readonly anyOf: ReadonlyArray<ServerRequest__McpElicitationConstOption>;\n};\nexport const ServerRequest__McpElicitationTitledEnumItems = Schema.Struct({\n  anyOf: Schema.Array(ServerRequest__McpElicitationConstOption),\n});\n\nexport type ServerRequest__McpElicitationNumberSchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationNumberType;\n};\nexport const ServerRequest__McpElicitationNumberSchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationNumberType,\n});\n\nexport type ServerRequest__McpElicitationLegacyTitledEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly enumNames?: ReadonlyArray<string> | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationLegacyTitledEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  enum: Schema.Array(Schema.String),\n  enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationStringSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly format?: ServerRequest__McpElicitationStringFormat | null;\n  readonly maxLength?: number | null;\n  readonly minLength?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationStringSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  format: Schema.optionalKey(\n    Schema.Union([ServerRequest__McpElicitationStringFormat, Schema.Null]),\n  ),\n  maxLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationTitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly oneOf: ReadonlyArray<ServerRequest__McpElicitationConstOption>;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationTitledSingleSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  oneOf: Schema.Array(ServerRequest__McpElicitationConstOption),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationUntitledEnumItems = {\n  readonly enum: ReadonlyArray<string>;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationUntitledEnumItems = Schema.Struct({\n  enum: Schema.Array(Schema.String),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  enum: Schema.Array(Schema.String),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__NetworkApprovalContext = {\n  readonly host: string;\n  readonly protocol: ServerRequest__NetworkApprovalProtocol;\n};\nexport const ServerRequest__NetworkApprovalContext = Schema.Struct({\n  host: Schema.String,\n  protocol: ServerRequest__NetworkApprovalProtocol,\n});\n\nexport type ServerRequest__NetworkPolicyAmendment = {\n  readonly action: ServerRequest__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const ServerRequest__NetworkPolicyAmendment = Schema.Struct({\n  action: ServerRequest__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type ServerRequest__ApplyPatchApprovalParams = {\n  readonly callId: string;\n  readonly conversationId: ServerRequest__ThreadId;\n  readonly fileChanges: { readonly [x: string]: ServerRequest__FileChange };\n  readonly grantRoot?: string | null;\n  readonly reason?: string | null;\n};\nexport const ServerRequest__ApplyPatchApprovalParams = Schema.Struct({\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].\",\n  }),\n  conversationId: ServerRequest__ThreadId,\n  fileChanges: Schema.Record(Schema.String, ServerRequest__FileChange),\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerRequest__ExecCommandApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly callId: string;\n  readonly command: ReadonlyArray<string>;\n  readonly conversationId: ServerRequest__ThreadId;\n  readonly cwd: string;\n  readonly parsedCmd: ReadonlyArray<ServerRequest__ParsedCommand>;\n  readonly reason?: string | null;\n};\nexport const ServerRequest__ExecCommandApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Identifier for this specific approval callback.\" }),\n      Schema.Null,\n    ]),\n  ),\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].\",\n  }),\n  command: Schema.Array(Schema.String),\n  conversationId: ServerRequest__ThreadId,\n  cwd: Schema.String,\n  parsedCmd: Schema.Array(ServerRequest__ParsedCommand),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerRequest__ToolRequestUserInputQuestion = {\n  readonly header: string;\n  readonly id: string;\n  readonly isOther?: boolean;\n  readonly isSecret?: boolean;\n  readonly options?: ReadonlyArray<ServerRequest__ToolRequestUserInputOption> | null;\n  readonly question: string;\n};\nexport const ServerRequest__ToolRequestUserInputQuestion = Schema.Struct({\n  header: Schema.String,\n  id: Schema.String,\n  isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  options: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerRequest__ToolRequestUserInputOption), Schema.Null]),\n  ),\n  question: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Represents one request_user_input question and its required options.\",\n});\n\nexport type ToolRequestUserInputParams__ToolRequestUserInputQuestion = {\n  readonly header: string;\n  readonly id: string;\n  readonly isOther?: boolean;\n  readonly isSecret?: boolean;\n  readonly options?: ReadonlyArray<ToolRequestUserInputParams__ToolRequestUserInputOption> | null;\n  readonly question: string;\n};\nexport const ToolRequestUserInputParams__ToolRequestUserInputQuestion = Schema.Struct({\n  header: Schema.String,\n  id: Schema.String,\n  isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  options: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputOption),\n      Schema.Null,\n    ]),\n  ),\n  question: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Represents one request_user_input question and its required options.\",\n});\n\nexport type V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = {\n  readonly credits?: V2AccountRateLimitsUpdatedNotification__CreditsSnapshot | null;\n  readonly individualLimit?: V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot | null;\n  readonly limitId?: string | null;\n  readonly limitName?: string | null;\n  readonly planType?: V2AccountRateLimitsUpdatedNotification__PlanType | null;\n  readonly primary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null;\n  readonly rateLimitReachedType?: V2AccountRateLimitsUpdatedNotification__RateLimitReachedType | null;\n  readonly secondary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null;\n  readonly spendControlReached?: boolean | null;\n};\nexport const V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = Schema.Struct({\n  credits: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__CreditsSnapshot, Schema.Null]),\n  ),\n  individualLimit: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot, Schema.Null]),\n  ),\n  limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  planType: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__PlanType, Schema.Null]),\n  ),\n  primary: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]),\n  ),\n  rateLimitReachedType: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitReachedType, Schema.Null]),\n  ),\n  secondary: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]),\n  ),\n  spendControlReached: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2AppListUpdatedNotification__AppMetadata = {\n  readonly categories?: ReadonlyArray<string> | null;\n  readonly developer?: string | null;\n  readonly firstPartyRequiresInstall?: boolean | null;\n  readonly firstPartyType?: string | null;\n  readonly review?: V2AppListUpdatedNotification__AppReview | null;\n  readonly screenshots?: ReadonlyArray<V2AppListUpdatedNotification__AppScreenshot> | null;\n  readonly seoDescription?: string | null;\n  readonly showInComposerWhenUnlinked?: boolean | null;\n  readonly subCategories?: ReadonlyArray<string> | null;\n  readonly version?: string | null;\n  readonly versionId?: string | null;\n  readonly versionNotes?: string | null;\n};\nexport const V2AppListUpdatedNotification__AppMetadata = Schema.Struct({\n  categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  review: Schema.optionalKey(Schema.Union([V2AppListUpdatedNotification__AppReview, Schema.Null])),\n  screenshots: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2AppListUpdatedNotification__AppScreenshot), Schema.Null]),\n  ),\n  seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2AppsListResponse__AppMetadata = {\n  readonly categories?: ReadonlyArray<string> | null;\n  readonly developer?: string | null;\n  readonly firstPartyRequiresInstall?: boolean | null;\n  readonly firstPartyType?: string | null;\n  readonly review?: V2AppsListResponse__AppReview | null;\n  readonly screenshots?: ReadonlyArray<V2AppsListResponse__AppScreenshot> | null;\n  readonly seoDescription?: string | null;\n  readonly showInComposerWhenUnlinked?: boolean | null;\n  readonly subCategories?: ReadonlyArray<string> | null;\n  readonly version?: string | null;\n  readonly versionId?: string | null;\n  readonly versionNotes?: string | null;\n};\nexport const V2AppsListResponse__AppMetadata = Schema.Struct({\n  categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  review: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppReview, Schema.Null])),\n  screenshots: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2AppsListResponse__AppScreenshot), Schema.Null]),\n  ),\n  seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2AppsReadResponse__ConnectorMetadata = {\n  readonly description?: string | null;\n  readonly iconUrl?: string | null;\n  readonly id: string;\n  readonly name: string;\n  readonly toolSummaries?: ReadonlyArray<V2AppsReadResponse__AppToolSummary> | null;\n};\nexport const V2AppsReadResponse__ConnectorMetadata = Schema.Struct({\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: Schema.String,\n  name: Schema.String,\n  toolSummaries: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2AppsReadResponse__AppToolSummary), Schema.Null]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - metadata returned by app/read.\" });\n\nexport type V2CommandExecParams__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2CommandExecParams__AbsolutePathBuf>;\n    };\nexport const V2CommandExecParams__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigBatchWriteParams__ConfigEdit = {\n  readonly keyPath: string;\n  readonly mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy;\n  readonly value: unknown;\n};\nexport const V2ConfigBatchWriteParams__ConfigEdit = Schema.Struct({\n  keyPath: Schema.String,\n  mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy,\n  value: Schema.Unknown,\n});\n\nexport type V2ConfigReadResponse__ConfigLayerSource =\n  | { readonly domain: string; readonly key: string; readonly type: \"mdm\" }\n  | { readonly file: string; readonly type: \"system\" }\n  | { readonly id: string; readonly name: string; readonly type: \"enterpriseManaged\" }\n  | { readonly file: string; readonly profile?: string | null; readonly type: \"user\" }\n  | { readonly dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf; readonly type: \"project\" }\n  | { readonly type: \"sessionFlags\" }\n  | {\n      readonly file: V2ConfigReadResponse__AbsolutePathBuf;\n      readonly type: \"legacyManagedConfigTomlFromFile\";\n    }\n  | { readonly type: \"legacyManagedConfigTomlFromMdm\" };\nexport const V2ConfigReadResponse__ConfigLayerSource = Schema.Union(\n  [\n    Schema.Struct({\n      domain: Schema.String,\n      key: Schema.String,\n      type: Schema.Literal(\"mdm\").annotate({ title: \"MdmConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"MdmConfigLayerSource\",\n      description: \"Managed preferences layer delivered by MDM (macOS only).\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      type: Schema.Literal(\"system\").annotate({ title: \"SystemConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SystemConfigLayerSource\",\n      description: \"Managed config layer from a file (usually `managed_config.toml`).\",\n    }),\n    Schema.Struct({\n      id: Schema.String.annotate({ description: \"Stable identifier for the delivered layer.\" }),\n      name: Schema.String.annotate({\n        description:\n          \"Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.\",\n      }),\n      type: Schema.Literal(\"enterpriseManaged\").annotate({\n        title: \"EnterpriseManagedConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"EnterpriseManagedConfigLayerSource\",\n      description: \"Enterprise-managed config layer delivered by the cloud config bundle.\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      profile: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Name of the selected profile-v2 config layered on top of the base user config, when this layer represents one.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"user\").annotate({ title: \"UserConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"UserConfigLayerSource\",\n      description:\n        \"User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory\",\n    }),\n    Schema.Struct({\n      dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"project\").annotate({ title: \"ProjectConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"ProjectConfigLayerSource\",\n      description:\n        \"Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"sessionFlags\").annotate({ title: \"SessionFlagsConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SessionFlagsConfigLayerSource\",\n      description: \"Session-layer overrides supplied via `-c`/`--config`.\",\n    }),\n    Schema.Struct({\n      file: V2ConfigReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"legacyManagedConfigTomlFromFile\").annotate({\n        title: \"LegacyManagedConfigTomlFromFileConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"LegacyManagedConfigTomlFromFileConfigLayerSource\",\n      description:\n        '`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a \"best effort\" while we phase out `managed_config.toml` in favor of `requirements.toml`.',\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"legacyManagedConfigTomlFromMdm\").annotate({\n        title: \"LegacyManagedConfigTomlFromMdmConfigLayerSourceType\",\n      }),\n    }).annotate({ title: \"LegacyManagedConfigTomlFromMdmConfigLayerSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigReadResponse__AppsDefaultConfig = {\n  readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;\n  readonly default_tools_approval_mode?: V2ConfigReadResponse__AppToolApproval | null;\n  readonly destructive_enabled?: boolean;\n  readonly enabled?: boolean;\n  readonly open_world_enabled?: boolean;\n};\nexport const V2ConfigReadResponse__AppsDefaultConfig = Schema.Struct({\n  approvals_reviewer: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]),\n  ),\n  default_tools_approval_mode: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),\n  ),\n  destructive_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n  enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n  open_world_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n});\n\nexport type V2ConfigReadResponse__WebSearchToolConfig = {\n  readonly allowed_domains?: ReadonlyArray<string> | null;\n  readonly context_size?: V2ConfigReadResponse__WebSearchContextSize | null;\n  readonly location?: V2ConfigReadResponse__WebSearchLocation | null;\n};\nexport const V2ConfigReadResponse__WebSearchToolConfig = Schema.Struct({\n  allowed_domains: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  context_size: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__WebSearchContextSize, Schema.Null]),\n  ),\n  location: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__WebSearchLocation, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup = {\n  readonly hooks: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookHandler>;\n  readonly matcher?: string | null;\n};\nexport const V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup = Schema.Struct({\n  hooks: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookHandler),\n  matcher: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse__NewThreadModelDefaults = {\n  readonly model?: string | null;\n  readonly modelReasoningEffort?: V2ConfigRequirementsReadResponse__ReasoningEffort | null;\n  readonly serviceTier?: string | null;\n};\nexport const V2ConfigRequirementsReadResponse__NewThreadModelDefaults = Schema.Struct({\n  model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  modelReasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ReasoningEffort, Schema.Null]),\n  ),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigWarningNotification__TextRange = {\n  readonly end: V2ConfigWarningNotification__TextPosition;\n  readonly start: V2ConfigWarningNotification__TextPosition;\n};\nexport const V2ConfigWarningNotification__TextRange = Schema.Struct({\n  end: V2ConfigWarningNotification__TextPosition,\n  start: V2ConfigWarningNotification__TextPosition,\n});\n\nexport type V2ConfigWriteResponse__ConfigLayerSource =\n  | { readonly domain: string; readonly key: string; readonly type: \"mdm\" }\n  | { readonly file: string; readonly type: \"system\" }\n  | { readonly id: string; readonly name: string; readonly type: \"enterpriseManaged\" }\n  | { readonly file: string; readonly profile?: string | null; readonly type: \"user\" }\n  | { readonly dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf; readonly type: \"project\" }\n  | { readonly type: \"sessionFlags\" }\n  | {\n      readonly file: V2ConfigWriteResponse__AbsolutePathBuf;\n      readonly type: \"legacyManagedConfigTomlFromFile\";\n    }\n  | { readonly type: \"legacyManagedConfigTomlFromMdm\" };\nexport const V2ConfigWriteResponse__ConfigLayerSource = Schema.Union(\n  [\n    Schema.Struct({\n      domain: Schema.String,\n      key: Schema.String,\n      type: Schema.Literal(\"mdm\").annotate({ title: \"MdmConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"MdmConfigLayerSource\",\n      description: \"Managed preferences layer delivered by MDM (macOS only).\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      type: Schema.Literal(\"system\").annotate({ title: \"SystemConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SystemConfigLayerSource\",\n      description: \"Managed config layer from a file (usually `managed_config.toml`).\",\n    }),\n    Schema.Struct({\n      id: Schema.String.annotate({ description: \"Stable identifier for the delivered layer.\" }),\n      name: Schema.String.annotate({\n        description:\n          \"Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.\",\n      }),\n      type: Schema.Literal(\"enterpriseManaged\").annotate({\n        title: \"EnterpriseManagedConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"EnterpriseManagedConfigLayerSource\",\n      description: \"Enterprise-managed config layer delivered by the cloud config bundle.\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      profile: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Name of the selected profile-v2 config layered on top of the base user config, when this layer represents one.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"user\").annotate({ title: \"UserConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"UserConfigLayerSource\",\n      description:\n        \"User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory\",\n    }),\n    Schema.Struct({\n      dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"project\").annotate({ title: \"ProjectConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"ProjectConfigLayerSource\",\n      description:\n        \"Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"sessionFlags\").annotate({ title: \"SessionFlagsConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SessionFlagsConfigLayerSource\",\n      description: \"Session-layer overrides supplied via `-c`/`--config`.\",\n    }),\n    Schema.Struct({\n      file: V2ConfigWriteResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"legacyManagedConfigTomlFromFile\").annotate({\n        title: \"LegacyManagedConfigTomlFromFileConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"LegacyManagedConfigTomlFromFileConfigLayerSource\",\n      description:\n        '`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a \"best effort\" while we phase out `managed_config.toml` in favor of `requirements.toml`.',\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"legacyManagedConfigTomlFromMdm\").annotate({\n        title: \"LegacyManagedConfigTomlFromMdmConfigLayerSourceType\",\n      }),\n    }).annotate({ title: \"LegacyManagedConfigTomlFromMdmConfigLayerSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ErrorNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ErrorNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2ErrorNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ErrorNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ExternalAgentConfigDetectResponse__MigrationDetails = {\n  readonly commands?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__CommandMigration>;\n  readonly hooks?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__HookMigration>;\n  readonly mcpServers?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__McpServerMigration>;\n  readonly memory?: ReadonlyArray<string>;\n  readonly plugins?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__PluginsMigration>;\n  readonly sessions?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__SessionMigration>;\n  readonly skills?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__SkillMigration>;\n  readonly subagents?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__SubagentMigration>;\n};\nexport const V2ExternalAgentConfigDetectResponse__MigrationDetails = Schema.Struct({\n  commands: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__CommandMigration).annotate({ default: [] }),\n  ),\n  hooks: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__HookMigration).annotate({ default: [] }),\n  ),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__McpServerMigration).annotate({ default: [] }),\n  ),\n  memory: Schema.optionalKey(Schema.Array(Schema.String)),\n  plugins: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__PluginsMigration).annotate({ default: [] }),\n  ),\n  sessions: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__SessionMigration).annotate({ default: [] }),\n  ),\n  skills: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__SkillMigration).annotate({ default: [] }),\n  ),\n  subagents: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__SubagentMigration).annotate({ default: [] }),\n  ),\n});\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure =\n  {\n    readonly cwd?: string | null;\n    readonly errorType?: string | null;\n    readonly failureStage: string;\n    readonly itemType: V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType;\n    readonly message: string;\n    readonly source?: string | null;\n    readonly subErrorType?: string | null;\n  };\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    failureStage: Schema.String,\n    itemType:\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType,\n    message: Schema.String,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess =\n  {\n    readonly cwd?: string | null;\n    readonly itemType: V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType;\n    readonly source?: string | null;\n    readonly target?: string | null;\n  };\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    itemType:\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure =\n  {\n    readonly cwd?: string | null;\n    readonly errorType?: string | null;\n    readonly failureStage: string;\n    readonly itemType: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType;\n    readonly message: string;\n    readonly source?: string | null;\n    readonly subErrorType?: string | null;\n  };\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    failureStage: Schema.String,\n    itemType:\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType,\n    message: Schema.String,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess =\n  {\n    readonly cwd?: string | null;\n    readonly itemType: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType;\n    readonly source?: string | null;\n    readonly target?: string | null;\n  };\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    itemType:\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate =\n  {\n    readonly name: string;\n    readonly sessionCount: number;\n    readonly source: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource;\n  };\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate =\n  Schema.Struct({\n    name: Schema.String,\n    sessionCount: Schema.Number.annotate({ format: \"uint32\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    source: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource,\n  });\n\nexport type V2ExternalAgentConfigImportParams__MigrationDetails = {\n  readonly commands?: ReadonlyArray<V2ExternalAgentConfigImportParams__CommandMigration>;\n  readonly hooks?: ReadonlyArray<V2ExternalAgentConfigImportParams__HookMigration>;\n  readonly mcpServers?: ReadonlyArray<V2ExternalAgentConfigImportParams__McpServerMigration>;\n  readonly memory?: ReadonlyArray<string>;\n  readonly plugins?: ReadonlyArray<V2ExternalAgentConfigImportParams__PluginsMigration>;\n  readonly sessions?: ReadonlyArray<V2ExternalAgentConfigImportParams__SessionMigration>;\n  readonly skills?: ReadonlyArray<V2ExternalAgentConfigImportParams__SkillMigration>;\n  readonly subagents?: ReadonlyArray<V2ExternalAgentConfigImportParams__SubagentMigration>;\n};\nexport const V2ExternalAgentConfigImportParams__MigrationDetails = Schema.Struct({\n  commands: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__CommandMigration).annotate({ default: [] }),\n  ),\n  hooks: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__HookMigration).annotate({ default: [] }),\n  ),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__McpServerMigration).annotate({ default: [] }),\n  ),\n  memory: Schema.optionalKey(Schema.Array(Schema.String)),\n  plugins: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__PluginsMigration).annotate({ default: [] }),\n  ),\n  sessions: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__SessionMigration).annotate({ default: [] }),\n  ),\n  skills: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__SkillMigration).annotate({ default: [] }),\n  ),\n  subagents: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__SubagentMigration).annotate({ default: [] }),\n  ),\n});\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure =\n  {\n    readonly cwd?: string | null;\n    readonly errorType?: string | null;\n    readonly failureStage: string;\n    readonly itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType;\n    readonly message: string;\n    readonly source?: string | null;\n    readonly subErrorType?: string | null;\n  };\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    failureStage: Schema.String,\n    itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType,\n    message: Schema.String,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess =\n  {\n    readonly cwd?: string | null;\n    readonly itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType;\n    readonly source?: string | null;\n    readonly target?: string | null;\n  };\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2FileChangePatchUpdatedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2FileChangePatchUpdatedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2FileChangePatchUpdatedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2FileChangePatchUpdatedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetCredit = {\n  readonly description?: string | null;\n  readonly expiresAt?: number | null;\n  readonly grantedAt: number;\n  readonly id: string;\n  readonly resetType: V2GetAccountRateLimitsResponse__RateLimitResetType;\n  readonly status: V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus;\n  readonly title?: string | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitResetCredit = Schema.Struct({\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Backend-provided display description for this credit, or `null` when unavailable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  expiresAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Unix timestamp in seconds when the credit expires, or `null` if it does not expire.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  grantedAt: Schema.Number.annotate({\n    description: \"Unix timestamp in seconds when the credit was granted.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  id: Schema.String.annotate({ description: \"Opaque backend identifier for this reset credit.\" }),\n  resetType: V2GetAccountRateLimitsResponse__RateLimitResetType,\n  status: V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus,\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Backend-provided display title for this credit, or `null` when unavailable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2GetAccountRateLimitsResponse__RateLimitSnapshot = {\n  readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null;\n  readonly individualLimit?: V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot | null;\n  readonly limitId?: string | null;\n  readonly limitName?: string | null;\n  readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null;\n  readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n  readonly rateLimitReachedType?: V2GetAccountRateLimitsResponse__RateLimitReachedType | null;\n  readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n  readonly spendControlReached?: boolean | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitSnapshot = Schema.Struct({\n  credits: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]),\n  ),\n  individualLimit: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot, Schema.Null]),\n  ),\n  limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  planType: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]),\n  ),\n  primary: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n  ),\n  rateLimitReachedType: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitReachedType, Schema.Null]),\n  ),\n  secondary: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n  ),\n  spendControlReached: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2GetAccountResponse__Account =\n  | { readonly type: \"apiKey\" }\n  | {\n      readonly email: string | null;\n      readonly planType: V2GetAccountResponse__PlanType;\n      readonly type: \"chatgpt\";\n    }\n  | { readonly type: \"amazonBedrock\"; readonly usesCodexManagedCredentials?: boolean };\nexport const V2GetAccountResponse__Account = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyAccountType\" }),\n    }).annotate({ title: \"ApiKeyAccount\" }),\n    Schema.Struct({\n      email: Schema.Union([Schema.String, Schema.Null]),\n      planType: V2GetAccountResponse__PlanType,\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"ChatgptAccountType\" }),\n    }).annotate({ title: \"ChatgptAccount\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"amazonBedrock\").annotate({ title: \"AmazonBedrockAccountType\" }),\n      usesCodexManagedCredentials: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n    }).annotate({ title: \"AmazonBedrockAccount\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2GetWorkspaceMessagesResponse__WorkspaceMessage = {\n  readonly archivedAt?: number | null;\n  readonly createdAt?: number | null;\n  readonly messageBody: string;\n  readonly messageId: string;\n  readonly messageType: V2GetWorkspaceMessagesResponse__WorkspaceMessageType;\n};\nexport const V2GetWorkspaceMessagesResponse__WorkspaceMessage = Schema.Struct({\n  archivedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the message was archived.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  createdAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the message was created.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  messageBody: Schema.String,\n  messageId: Schema.String,\n  messageType: V2GetWorkspaceMessagesResponse__WorkspaceMessageType,\n});\n\nexport type V2HookCompletedNotification__HookOutputEntry = {\n  readonly kind: V2HookCompletedNotification__HookOutputEntryKind;\n  readonly text: string;\n};\nexport const V2HookCompletedNotification__HookOutputEntry = Schema.Struct({\n  kind: V2HookCompletedNotification__HookOutputEntryKind,\n  text: Schema.String,\n});\n\nexport type V2HooksListResponse__HookMetadata = {\n  readonly command?: string | null;\n  readonly currentHash: string;\n  readonly displayOrder: number;\n  readonly enabled: boolean;\n  readonly eventName: V2HooksListResponse__HookEventName;\n  readonly handlerType: V2HooksListResponse__HookHandlerType;\n  readonly isManaged: boolean;\n  readonly key: string;\n  readonly matcher?: string | null;\n  readonly pluginId?: string | null;\n  readonly source: V2HooksListResponse__HookSource;\n  readonly sourcePath: V2HooksListResponse__AbsolutePathBuf;\n  readonly statusMessage?: string | null;\n  readonly timeoutSec: number;\n  readonly trustStatus: V2HooksListResponse__HookTrustStatus;\n};\nexport const V2HooksListResponse__HookMetadata = Schema.Struct({\n  command: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  currentHash: Schema.String,\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  enabled: Schema.Boolean,\n  eventName: V2HooksListResponse__HookEventName,\n  handlerType: V2HooksListResponse__HookHandlerType,\n  isManaged: Schema.Boolean,\n  key: Schema.String,\n  matcher: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  source: V2HooksListResponse__HookSource,\n  sourcePath: V2HooksListResponse__AbsolutePathBuf,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timeoutSec: Schema.Number.annotate({ format: \"uint64\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  trustStatus: V2HooksListResponse__HookTrustStatus,\n});\n\nexport type V2HookStartedNotification__HookOutputEntry = {\n  readonly kind: V2HookStartedNotification__HookOutputEntryKind;\n  readonly text: string;\n};\nexport const V2HookStartedNotification__HookOutputEntry = Schema.Struct({\n  kind: V2HookStartedNotification__HookOutputEntryKind,\n  text: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ItemCompletedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ItemCompletedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ItemCompletedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemCompletedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ItemCompletedNotification__CollabAgentStatus;\n};\nexport const V2ItemCompletedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ItemCompletedNotification__CollabAgentStatus,\n});\n\nexport type V2ItemCompletedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ItemCompletedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ItemCompletedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ItemCompletedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ItemCompletedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ItemCompletedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ItemCompletedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ItemCompletedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ItemCompletedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ItemCompletedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ItemCompletedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ItemCompletedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ItemCompletedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview = {\n  readonly rationale?: string | null;\n  readonly riskLevel?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel | null;\n  readonly status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus;\n  readonly userAuthorization?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview =\n  Schema.Struct({\n    rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    riskLevel: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel,\n        Schema.Null,\n      ]),\n    ),\n    status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus,\n    userAuthorization: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization,\n        Schema.Null,\n      ]),\n    ),\n  }).annotate({\n    description:\n      \"[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString | null;\n    };\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath =\n  Schema.Union(\n    [\n      Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n        title: \"RootFileSystemSpecialPath\",\n      }),\n      Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n        title: \"MinimalFileSystemSpecialPath\",\n      }),\n      Schema.Struct({\n        kind: Schema.Literal(\"project_roots\"),\n        subpath: Schema.optionalKey(\n          Schema.Union([\n            V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n      Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n        title: \"TmpdirFileSystemSpecialPath\",\n      }),\n      Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n        title: \"SlashTmpFileSystemSpecialPath\",\n      }),\n      Schema.Struct({\n        kind: Schema.Literal(\"unknown\"),\n        path: Schema.String,\n        subpath: Schema.optionalKey(\n          Schema.Union([\n            V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n            Schema.Null,\n          ]),\n        ),\n      }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview = {\n  readonly rationale?: string | null;\n  readonly riskLevel?: V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel | null;\n  readonly status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus;\n  readonly userAuthorization?: V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview =\n  Schema.Struct({\n    rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    riskLevel: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel,\n        Schema.Null,\n      ]),\n    ),\n    status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus,\n    userAuthorization: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization,\n        Schema.Null,\n      ]),\n    ),\n  }).annotate({\n    description:\n      \"[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString | null;\n    };\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([\n          V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString,\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([\n          V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString,\n          Schema.Null,\n        ]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ItemStartedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ItemStartedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ItemStartedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ItemStartedNotification__CollabAgentStatus;\n};\nexport const V2ItemStartedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ItemStartedNotification__CollabAgentStatus,\n});\n\nexport type V2ItemStartedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ItemStartedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ItemStartedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ItemStartedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ItemStartedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ItemStartedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ItemStartedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ItemStartedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ItemStartedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ItemStartedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ItemStartedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ItemStartedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ItemStartedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ItemStartedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ListMcpServerStatusResponse__McpServerStatus = {\n  readonly authStatus: V2ListMcpServerStatusResponse__McpAuthStatus;\n  readonly name: string;\n  readonly resourceTemplates: ReadonlyArray<V2ListMcpServerStatusResponse__ResourceTemplate>;\n  readonly resources: ReadonlyArray<V2ListMcpServerStatusResponse__Resource>;\n  readonly serverInfo?: V2ListMcpServerStatusResponse__McpServerInfo | null;\n  readonly tools: { readonly [x: string]: V2ListMcpServerStatusResponse__Tool };\n};\nexport const V2ListMcpServerStatusResponse__McpServerStatus = Schema.Struct({\n  authStatus: V2ListMcpServerStatusResponse__McpAuthStatus,\n  name: Schema.String,\n  resourceTemplates: Schema.Array(V2ListMcpServerStatusResponse__ResourceTemplate),\n  resources: Schema.Array(V2ListMcpServerStatusResponse__Resource),\n  serverInfo: Schema.optionalKey(\n    Schema.Union([V2ListMcpServerStatusResponse__McpServerInfo, Schema.Null]),\n  ),\n  tools: Schema.Record(Schema.String, V2ListMcpServerStatusResponse__Tool),\n});\n\nexport type V2ModelListResponse__ReasoningEffortOption = {\n  readonly description: string;\n  readonly reasoningEffort: V2ModelListResponse__ReasoningEffort;\n};\nexport const V2ModelListResponse__ReasoningEffortOption = Schema.Struct({\n  description: Schema.String,\n  reasoningEffort: V2ModelListResponse__ReasoningEffort,\n});\n\nexport type V2PluginInstalledResponse__MarketplaceLoadErrorInfo = {\n  readonly marketplacePath: V2PluginInstalledResponse__AbsolutePathBuf;\n  readonly message: string;\n};\nexport const V2PluginInstalledResponse__MarketplaceLoadErrorInfo = Schema.Struct({\n  marketplacePath: V2PluginInstalledResponse__AbsolutePathBuf,\n  message: Schema.String,\n});\n\nexport type V2PluginInstalledResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginInstalledResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginInstalledResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginInstalledResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginInstalledResponse__PluginSource =\n  | { readonly path: V2PluginInstalledResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginInstalledResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginInstalledResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginInstalledResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginInstalledResponse__PluginSharePrincipalType;\n  readonly role: V2PluginInstalledResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginInstalledResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginInstalledResponse__PluginSharePrincipalType,\n  role: V2PluginInstalledResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginListResponse__MarketplaceLoadErrorInfo = {\n  readonly marketplacePath: V2PluginListResponse__AbsolutePathBuf;\n  readonly message: string;\n};\nexport const V2PluginListResponse__MarketplaceLoadErrorInfo = Schema.Struct({\n  marketplacePath: V2PluginListResponse__AbsolutePathBuf,\n  message: Schema.String,\n});\n\nexport type V2PluginListResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginListResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginListResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginListResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginListResponse__PluginSource =\n  | { readonly path: V2PluginListResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginListResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginListResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginListResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginListResponse__PluginSharePrincipalType;\n  readonly role: V2PluginListResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginListResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginListResponse__PluginSharePrincipalType,\n  role: V2PluginListResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginReadResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginReadResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginReadResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginReadResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__PluginSource =\n  | { readonly path: V2PluginReadResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginReadResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginReadResponse__SkillInterface = {\n  readonly brandColor?: string | null;\n  readonly defaultPrompt?: string | null;\n  readonly displayName?: string | null;\n  readonly iconLarge?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly iconSmall?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly shortDescription?: string | null;\n};\nexport const V2PluginReadResponse__SkillInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconLarge: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),\n  iconSmall: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__AppTemplateSummary = {\n  readonly canonicalConnectorId?: string | null;\n  readonly category?: string | null;\n  readonly description?: string | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly materializedAppIds: ReadonlyArray<string>;\n  readonly name: string;\n  readonly reason?: V2PluginReadResponse__AppTemplateUnavailableReason | null;\n  readonly templateId: string;\n};\nexport const V2PluginReadResponse__AppTemplateSummary = Schema.Struct({\n  canonicalConnectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  materializedAppIds: Schema.Array(Schema.String),\n  name: Schema.String,\n  reason: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AppTemplateUnavailableReason, Schema.Null]),\n  ),\n  templateId: Schema.String,\n});\n\nexport type V2PluginReadResponse__PluginHookSummary = {\n  readonly eventName: V2PluginReadResponse__HookEventName;\n  readonly key: string;\n};\nexport const V2PluginReadResponse__PluginHookSummary = Schema.Struct({\n  eventName: V2PluginReadResponse__HookEventName,\n  key: Schema.String,\n});\n\nexport type V2PluginReadResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginReadResponse__PluginSharePrincipalType;\n  readonly role: V2PluginReadResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginReadResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginReadResponse__PluginSharePrincipalType,\n  role: V2PluginReadResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginReadResponse__ScheduledTaskSchedule =\n  | {\n      readonly days?: ReadonlyArray<V2PluginReadResponse__ScheduledTaskWeekday> | null;\n      readonly intervalHours: number;\n      readonly type: \"hourly\";\n    }\n  | { readonly time: string; readonly type: \"daily\" }\n  | { readonly time: string; readonly type: \"weekdays\" }\n  | {\n      readonly days: ReadonlyArray<V2PluginReadResponse__ScheduledTaskWeekday>;\n      readonly time: string;\n      readonly type: \"weekly\";\n    };\nexport const V2PluginReadResponse__ScheduledTaskSchedule = Schema.Union(\n  [\n    Schema.Struct({\n      days: Schema.optionalKey(\n        Schema.Union([Schema.Array(V2PluginReadResponse__ScheduledTaskWeekday), Schema.Null]),\n      ),\n      intervalHours: Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      type: Schema.Literal(\"hourly\").annotate({ title: \"HourlyScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"HourlyScheduledTaskSchedule\" }),\n    Schema.Struct({\n      time: Schema.String,\n      type: Schema.Literal(\"daily\").annotate({ title: \"DailyScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"DailyScheduledTaskSchedule\" }),\n    Schema.Struct({\n      time: Schema.String,\n      type: Schema.Literal(\"weekdays\").annotate({ title: \"WeekdaysScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"WeekdaysScheduledTaskSchedule\" }),\n    Schema.Struct({\n      days: Schema.Array(V2PluginReadResponse__ScheduledTaskWeekday),\n      time: Schema.String,\n      type: Schema.Literal(\"weekly\").annotate({ title: \"WeeklyScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"WeeklyScheduledTaskSchedule\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginShareListResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginShareListResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginShareListResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginShareListResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginShareListResponse__PluginSource =\n  | { readonly path: V2PluginShareListResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginShareListResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginShareListResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginShareListResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginShareListResponse__PluginSharePrincipalType;\n  readonly role: V2PluginShareListResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginShareListResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginShareListResponse__PluginSharePrincipalType,\n  role: V2PluginShareListResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginShareSaveParams__PluginShareTarget = {\n  readonly principalId: string;\n  readonly principalType: V2PluginShareSaveParams__PluginSharePrincipalType;\n  readonly role: V2PluginShareSaveParams__PluginShareTargetRole;\n};\nexport const V2PluginShareSaveParams__PluginShareTarget = Schema.Struct({\n  principalId: Schema.String,\n  principalType: V2PluginShareSaveParams__PluginSharePrincipalType,\n  role: V2PluginShareSaveParams__PluginShareTargetRole,\n});\n\nexport type V2PluginShareUpdateTargetsParams__PluginShareTarget = {\n  readonly principalId: string;\n  readonly principalType: V2PluginShareUpdateTargetsParams__PluginSharePrincipalType;\n  readonly role: V2PluginShareUpdateTargetsParams__PluginShareTargetRole;\n};\nexport const V2PluginShareUpdateTargetsParams__PluginShareTarget = Schema.Struct({\n  principalId: Schema.String,\n  principalType: V2PluginShareUpdateTargetsParams__PluginSharePrincipalType,\n  role: V2PluginShareUpdateTargetsParams__PluginShareTargetRole,\n});\n\nexport type V2PluginShareUpdateTargetsResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType;\n  readonly role: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginShareUpdateTargetsResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType,\n  role: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole,\n});\n\nexport type V2RawResponseItemCompletedNotification__ContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly text: string; readonly type: \"output_text\" };\nexport const V2RawResponseItemCompletedNotification__ContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({ title: \"InputTextContentItemType\" }),\n    }).annotate({ title: \"InputTextContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({ title: \"InputImageContentItemType\" }),\n    }).annotate({ title: \"InputImageContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({ title: \"InputAudioContentItemType\" }),\n    }).annotate({ title: \"InputAudioContentItem\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"output_text\").annotate({ title: \"OutputTextContentItemType\" }),\n    }).annotate({ title: \"OutputTextContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({\n        title: \"InputImageFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({\n        title: \"InputAudioFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"EncryptedContentFunctionCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.\",\n});\n\nexport type V2ReviewStartResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ReviewStartResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ReviewStartResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ReviewStartResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ReviewStartResponse__CollabAgentStatus;\n};\nexport const V2ReviewStartResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ReviewStartResponse__CollabAgentStatus,\n});\n\nexport type V2ReviewStartResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ReviewStartResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ReviewStartResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ReviewStartResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ReviewStartResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ReviewStartResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ReviewStartResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ReviewStartResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ReviewStartResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ReviewStartResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ReviewStartResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ReviewStartResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ReviewStartResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ReviewStartResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ReviewStartResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ReviewStartResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ReviewStartResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ReviewStartResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2SkillsListResponse__SkillInterface = {\n  readonly brandColor?: string | null;\n  readonly defaultPrompt?: string | null;\n  readonly displayName?: string | null;\n  readonly iconLarge?: V2SkillsListResponse__AbsolutePathBuf | null;\n  readonly iconSmall?: V2SkillsListResponse__AbsolutePathBuf | null;\n  readonly shortDescription?: string | null;\n};\nexport const V2SkillsListResponse__SkillInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconLarge: Schema.optionalKey(Schema.Union([V2SkillsListResponse__AbsolutePathBuf, Schema.Null])),\n  iconSmall: Schema.optionalKey(Schema.Union([V2SkillsListResponse__AbsolutePathBuf, Schema.Null])),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2SkillsListResponse__SkillDependencies = {\n  readonly tools: ReadonlyArray<V2SkillsListResponse__SkillToolDependency>;\n};\nexport const V2SkillsListResponse__SkillDependencies = Schema.Struct({\n  tools: Schema.Array(V2SkillsListResponse__SkillToolDependency),\n});\n\nexport type V2ThreadForkResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadForkResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadForkResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadForkResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadForkResponse__CollabAgentStatus;\n};\nexport const V2ThreadForkResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadForkResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadForkResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadForkResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadForkResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadForkResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadForkResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadForkResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadForkResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadForkResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadForkResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadForkResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadForkResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadForkResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadForkResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadForkResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadForkResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadForkResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadForkResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadForkResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadForkResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadForkResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadForkResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadForkResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadForkResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadGoalGetResponse__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: V2ThreadGoalGetResponse__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const V2ThreadGoalGetResponse__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: V2ThreadGoalGetResponse__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadGoalSetResponse__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: V2ThreadGoalSetResponse__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const V2ThreadGoalSetResponse__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: V2ThreadGoalSetResponse__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadGoalUpdatedNotification__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: V2ThreadGoalUpdatedNotification__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const V2ThreadGoalUpdatedNotification__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: V2ThreadGoalUpdatedNotification__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadListResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadListResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadListResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadListResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadListResponse__CollabAgentStatus;\n};\nexport const V2ThreadListResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadListResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadListResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadListResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadListResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadListResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadListResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadListResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadListResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadListResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadListResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadListResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadListResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadListResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadListResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadListResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadListResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadListResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadListResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadListResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadListResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadListResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadListResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadListResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadListResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadListResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadListResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadMetadataUpdateResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadMetadataUpdateResponse__CollabAgentStatus;\n};\nexport const V2ThreadMetadataUpdateResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadMetadataUpdateResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadMetadataUpdateResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadMetadataUpdateResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadMetadataUpdateResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadMetadataUpdateResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadMetadataUpdateResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadMetadataUpdateResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadMetadataUpdateResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadMetadataUpdateResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadMetadataUpdateResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadMetadataUpdateResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadMetadataUpdateResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadMetadataUpdateResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadMetadataUpdateResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadMetadataUpdateResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadMetadataUpdateResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadMetadataUpdateResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadMetadataUpdateResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadMetadataUpdateResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadReadResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadReadResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadReadResponse__CollabAgentStatus;\n};\nexport const V2ThreadReadResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadReadResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadReadResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadReadResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadReadResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadReadResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadReadResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadReadResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadReadResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadReadResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadReadResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadReadResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadReadResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadReadResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadReadResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadReadResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadReadResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadReadResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadReadResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadReadResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadReadResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadReadResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadReadResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadReadResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadReadResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2ThreadResumeParams__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly text: string; readonly type: \"output_text\" };\nexport const V2ThreadResumeParams__ContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({ title: \"InputTextContentItemType\" }),\n    }).annotate({ title: \"InputTextContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({ title: \"InputImageContentItemType\" }),\n    }).annotate({ title: \"InputImageContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({ title: \"InputAudioContentItemType\" }),\n    }).annotate({ title: \"InputAudioContentItem\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"output_text\").annotate({ title: \"OutputTextContentItemType\" }),\n    }).annotate({ title: \"OutputTextContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__FunctionCallOutputContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2ThreadResumeParams__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2ThreadResumeParams__FunctionCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({\n        title: \"InputImageFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({\n        title: \"InputAudioFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"EncryptedContentFunctionCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.\",\n});\n\nexport type V2ThreadResumeResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadResumeResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadResumeResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadResumeResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadResumeResponse__CollabAgentStatus;\n};\nexport const V2ThreadResumeResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadResumeResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadResumeResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadResumeResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadResumeResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadResumeResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadResumeResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadResumeResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadResumeResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadResumeResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadResumeResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadResumeResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadResumeResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadResumeResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadResumeResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadResumeResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadResumeResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadResumeResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadResumeResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadResumeResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadResumeResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadResumeResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadResumeResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadResumeResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadRollbackResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadRollbackResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadRollbackResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadRollbackResponse__CollabAgentStatus;\n};\nexport const V2ThreadRollbackResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadRollbackResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadRollbackResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadRollbackResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadRollbackResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadRollbackResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadRollbackResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadRollbackResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadRollbackResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadRollbackResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadRollbackResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadRollbackResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadRollbackResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadRollbackResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadRollbackResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadRollbackResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadRollbackResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadRollbackResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadRollbackResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadRollbackResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadRollbackResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadRollbackResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadSettingsUpdatedNotification__AbsolutePathBuf>;\n    };\nexport const V2ThreadSettingsUpdatedNotification__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadSettingsUpdatedNotification__AbsolutePathBuf).annotate({\n          default: [],\n        }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: V2ThreadSettingsUpdatedNotification__ReasoningEffort | null;\n};\nexport const V2ThreadSettingsUpdatedNotification__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ReasoningEffort, Schema.Null]),\n  ),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type V2ThreadStartedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadStartedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadStartedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadStartedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadStartedNotification__CollabAgentStatus;\n};\nexport const V2ThreadStartedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadStartedNotification__CollabAgentStatus,\n});\n\nexport type V2ThreadStartedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadStartedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadStartedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadStartedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadStartedNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadStartedNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadStartedNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadStartedNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadStartedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadStartedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadStartedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadStartedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadStartedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadStartedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadStartedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadStartedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadStartedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadStartedNotification__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadStartedNotification__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadStartedNotification__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadStartedNotification__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadStartedNotification__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadStartResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadStartResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadStartResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadStartResponse__CollabAgentStatus;\n};\nexport const V2ThreadStartResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadStartResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadStartResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadStartResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadStartResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadStartResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadStartResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadStartResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadStartResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadStartResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadStartResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadStartResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadStartResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadStartResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadStartResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadStartResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadStartResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadStartResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadStartResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadStartResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadStartResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadStartResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadStartResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadStartResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStatusChangedNotification__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadStatusChangedNotification__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadStatusChangedNotification__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadStatusChangedNotification__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = {\n  readonly last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown;\n  readonly modelContextWindow?: number | null;\n  readonly total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown;\n};\nexport const V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = Schema.Struct({\n  last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,\n  modelContextWindow: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,\n});\n\nexport type V2ThreadUnarchiveResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadUnarchiveResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadUnarchiveResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadUnarchiveResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadUnarchiveResponse__CollabAgentStatus;\n};\nexport const V2ThreadUnarchiveResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadUnarchiveResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadUnarchiveResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadUnarchiveResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadUnarchiveResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadUnarchiveResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadUnarchiveResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadUnarchiveResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadUnarchiveResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadUnarchiveResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadUnarchiveResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadUnarchiveResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadUnarchiveResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadUnarchiveResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadUnarchiveResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadUnarchiveResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadUnarchiveResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadUnarchiveResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadUnarchiveResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadUnarchiveResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadUnarchiveResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadUnarchiveResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2TurnCompletedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2TurnCompletedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2TurnCompletedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2TurnCompletedNotification__CollabAgentStatus;\n};\nexport const V2TurnCompletedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2TurnCompletedNotification__CollabAgentStatus,\n});\n\nexport type V2TurnCompletedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2TurnCompletedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2TurnCompletedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2TurnCompletedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2TurnCompletedNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2TurnCompletedNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2TurnCompletedNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2TurnCompletedNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2TurnCompletedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2TurnCompletedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2TurnCompletedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2TurnCompletedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnCompletedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnCompletedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnCompletedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnCompletedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnCompletedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnPlanUpdatedNotification__TurnPlanStep = {\n  readonly status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus;\n  readonly step: string;\n};\nexport const V2TurnPlanUpdatedNotification__TurnPlanStep = Schema.Struct({\n  status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus,\n  step: Schema.String,\n});\n\nexport type V2TurnStartedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2TurnStartedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2TurnStartedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2TurnStartedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2TurnStartedNotification__CollabAgentStatus;\n};\nexport const V2TurnStartedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2TurnStartedNotification__CollabAgentStatus,\n});\n\nexport type V2TurnStartedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2TurnStartedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2TurnStartedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2TurnStartedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2TurnStartedNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2TurnStartedNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2TurnStartedNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2TurnStartedNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2TurnStartedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2TurnStartedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2TurnStartedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2TurnStartedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2TurnStartedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnStartedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnStartedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnStartedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnStartedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnStartedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2TurnStartParams__AbsolutePathBuf>;\n    };\nexport const V2TurnStartParams__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: V2TurnStartParams__ReasoningEffort | null;\n};\nexport const V2TurnStartParams__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]),\n  ),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type V2TurnStartParams__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnStartParams__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnStartParams__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnStartParams__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnStartParams__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnStartParams__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartParams__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartParams__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2TurnStartResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2TurnStartResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2TurnStartResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2TurnStartResponse__CollabAgentStatus;\n};\nexport const V2TurnStartResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2TurnStartResponse__CollabAgentStatus,\n});\n\nexport type V2TurnStartResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2TurnStartResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2TurnStartResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2TurnStartResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2TurnStartResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2TurnStartResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2TurnStartResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2TurnStartResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2TurnStartResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2TurnStartResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2TurnStartResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2TurnStartResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2TurnStartResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnStartResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnStartResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnStartResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnStartResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnStartResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnSteerParams__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnSteerParams__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnSteerParams__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnSteerParams__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnSteerParams__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnSteerParams__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnSteerParams__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnSteerParams__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ApplyPatchApprovalResponse__ReviewDecision =\n  | \"approved\"\n  | {\n      readonly approved_execpolicy_amendment: {\n        readonly proposed_execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | \"approved_for_session\"\n  | {\n      readonly network_policy_amendment: {\n        readonly network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment;\n      };\n    }\n  | \"denied\"\n  | \"timed_out\"\n  | \"abort\";\nexport const ApplyPatchApprovalResponse__ReviewDecision = Schema.Union(\n  [\n    Schema.Literal(\"approved\").annotate({\n      description: \"User has approved this command and the agent should execute it.\",\n    }),\n    Schema.Struct({\n      approved_execpolicy_amendment: Schema.Struct({\n        proposed_execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"ApprovedExecpolicyAmendmentReviewDecision\",\n      description:\n        \"User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.\",\n    }),\n    Schema.Literal(\"approved_for_session\").annotate({\n      description:\n        \"User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.\",\n    }),\n    Schema.Struct({\n      network_policy_amendment: Schema.Struct({\n        network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"NetworkPolicyAmendmentReviewDecision\",\n      description:\n        \"User chose to persist a network policy rule (allow/deny) for future requests to the same host.\",\n    }),\n    Schema.Literal(\"denied\").annotate({\n      description:\n        \"User has denied this command and the agent should not execute it, but it should continue the session and try something else.\",\n    }),\n    Schema.Literal(\"timed_out\").annotate({\n      description: \"Automatic approval review timed out before reaching a decision.\",\n    }),\n    Schema.Literal(\"abort\").annotate({\n      description:\n        \"User has denied this command and the agent should not do anything until the user's next command.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"User's decision in response to an ExecApprovalRequest.\" });\n\nexport type ClientRequest__CommandExecParams = {\n  readonly command: ReadonlyArray<string>;\n  readonly cwd?: string | null;\n  readonly disableOutputCap?: boolean;\n  readonly disableTimeout?: boolean;\n  readonly env?: { readonly [x: string]: string | null } | null;\n  readonly outputBytesCap?: number | null;\n  readonly processId?: string | null;\n  readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null;\n  readonly size?: ClientRequest__CommandExecTerminalSize | null;\n  readonly streamStdin?: boolean;\n  readonly streamStdoutStderr?: boolean;\n  readonly timeoutMs?: number | null;\n  readonly tty?: boolean;\n};\nexport const ClientRequest__CommandExecParams = Schema.Struct({\n  command: Schema.Array(Schema.String).annotate({\n    description: \"Command argv vector. Empty arrays are rejected.\",\n  }),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory. Defaults to the server cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  disableOutputCap: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable stdout/stderr capture truncation for this request.\\n\\nCannot be combined with `outputBytesCap`.\",\n    }),\n  ),\n  disableTimeout: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable the timeout entirely for this request.\\n\\nCannot be combined with `timeoutMs`.\",\n    }),\n  ),\n  env: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({\n        description:\n          \"Optional environment overrides merged into the server-computed environment.\\n\\nMatching names override inherited values. Set a key to `null` to unset an inherited variable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputBytesCap: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional per-stream stdout/stderr capture cap in bytes.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.\",\n        format: \"uint\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional client-supplied, connection-scoped process id.\\n\\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({\n      description:\n        \"Optional sandbox policy for this command.\\n\\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted. Cannot be combined with `permissionProfile`.\",\n    }),\n  ),\n  size: Schema.optionalKey(\n    Schema.Union([ClientRequest__CommandExecTerminalSize, Schema.Null]).annotate({\n      description: \"Optional initial PTY size in character cells. Only valid when `tty` is true.\",\n    }),\n  ),\n  streamStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Allow follow-up `command/exec/write` requests to write stdin bytes.\\n\\nRequires a client-supplied `processId`.\",\n    }),\n  ),\n  streamStdoutStderr: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Stream stdout/stderr via `command/exec/outputDelta` notifications.\\n\\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.\",\n    }),\n  ),\n  timeoutMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional timeout in milliseconds.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  tty: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Enable PTY mode.\\n\\nThis implies `streamStdin` and `streamStdoutStderr`.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\\n\\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.\",\n});\n\nexport type ClientRequest__FunctionCallOutputBody =\n  | string\n  | ReadonlyArray<ClientRequest__FunctionCallOutputContentItem>;\nexport const ClientRequest__FunctionCallOutputBody = Schema.Union([\n  Schema.String,\n  Schema.Array(ClientRequest__FunctionCallOutputContentItem),\n]);\n\nexport type ClientRequest__ConfigBatchWriteParams = {\n  readonly edits: ReadonlyArray<ClientRequest__ConfigEdit>;\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly reloadUserConfig?: boolean;\n};\nexport const ClientRequest__ConfigBatchWriteParams = Schema.Struct({\n  edits: Schema.Array(ClientRequest__ConfigEdit),\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reloadUserConfig: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, hot-reload the updated user config into all loaded threads after writing.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__PluginShareSaveParams = {\n  readonly discoverability?: ClientRequest__PluginShareDiscoverability | null;\n  readonly pluginPath: ClientRequest__AbsolutePathBuf;\n  readonly remotePluginId?: string | null;\n  readonly shareTargets?: ReadonlyArray<ClientRequest__PluginShareTarget> | null;\n};\nexport const ClientRequest__PluginShareSaveParams = Schema.Struct({\n  discoverability: Schema.optionalKey(\n    Schema.Union([ClientRequest__PluginShareDiscoverability, Schema.Null]),\n  ),\n  pluginPath: ClientRequest__AbsolutePathBuf,\n  remotePluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  shareTargets: Schema.optionalKey(\n    Schema.Union([Schema.Array(ClientRequest__PluginShareTarget), Schema.Null]),\n  ),\n});\n\nexport type ClientRequest__PluginShareUpdateTargetsParams = {\n  readonly discoverability: ClientRequest__PluginShareUpdateDiscoverability;\n  readonly remotePluginId: string;\n  readonly shareTargets: ReadonlyArray<ClientRequest__PluginShareTarget>;\n};\nexport const ClientRequest__PluginShareUpdateTargetsParams = Schema.Struct({\n  discoverability: ClientRequest__PluginShareUpdateDiscoverability,\n  remotePluginId: Schema.String,\n  shareTargets: Schema.Array(ClientRequest__PluginShareTarget),\n});\n\nexport type ClientRequest__ExternalAgentConfigMigrationItem = {\n  readonly cwd?: string | null;\n  readonly description: string;\n  readonly details?: ClientRequest__MigrationDetails | null;\n  readonly itemType: ClientRequest__ExternalAgentConfigMigrationItemType;\n};\nexport const ClientRequest__ExternalAgentConfigMigrationItem = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Null or empty means home-scoped migration; non-empty means repo-scoped migration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  details: Schema.optionalKey(Schema.Union([ClientRequest__MigrationDetails, Schema.Null])),\n  itemType: ClientRequest__ExternalAgentConfigMigrationItemType,\n});\n\nexport type ClientRequest__TurnStartParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly clientUserMessageId?: string | null;\n  readonly cwd?: string | null;\n  readonly effort?: ClientRequest__ReasoningEffort | null;\n  readonly input: ReadonlyArray<ClientRequest__UserInput>;\n  readonly model?: string | null;\n  readonly outputSchema?: unknown;\n  readonly personality?: ClientRequest__Personality | null;\n  readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null;\n  readonly serviceTier?: string | null;\n  readonly summary?: ClientRequest__ReasoningSummary | null;\n  readonly threadId: string;\n};\nexport const ClientRequest__TurnStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([ClientRequest__AskForApproval, Schema.Null]).annotate({\n      description: \"Override the approval policy for this turn and subsequent turns.\",\n    }),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this turn and subsequent turns.\",\n    }),\n  ),\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the working directory for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  effort: Schema.optionalKey(\n    Schema.Union([ClientRequest__ReasoningEffort, Schema.Null]).annotate({\n      description: \"Override the reasoning effort for this turn and subsequent turns.\",\n    }),\n  ),\n  input: Schema.Array(ClientRequest__UserInput),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the model for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputSchema: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Optional JSON Schema used to constrain the final assistant message for this turn.\",\n    }),\n  ),\n  personality: Schema.optionalKey(\n    Schema.Union([ClientRequest__Personality, Schema.Null]).annotate({\n      description: \"Override the personality for this turn and subsequent turns.\",\n    }),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({\n      description: \"Override the sandbox policy for this turn and subsequent turns.\",\n    }),\n  ),\n  serviceTier: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the service tier for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.optionalKey(\n    Schema.Union([ClientRequest__ReasoningSummary, Schema.Null]).annotate({\n      description: \"Override the reasoning summary for this turn and subsequent turns.\",\n    }),\n  ),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__TurnSteerParams = {\n  readonly clientUserMessageId?: string | null;\n  readonly expectedTurnId: string;\n  readonly input: ReadonlyArray<ClientRequest__UserInput>;\n  readonly threadId: string;\n};\nexport const ClientRequest__TurnSteerParams = Schema.Struct({\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  expectedTurnId: Schema.String.annotate({\n    description:\n      \"Required active turn id precondition. The request fails when it does not match the currently active turn.\",\n  }),\n  input: Schema.Array(ClientRequest__UserInput),\n  threadId: Schema.String,\n});\n\nexport type CommandExecutionRequestApprovalParams__FileSystemPath =\n  | {\n      readonly path: CommandExecutionRequestApprovalParams__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: CommandExecutionRequestApprovalParams__FileSystemSpecialPath;\n    };\nexport const CommandExecutionRequestApprovalParams__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: CommandExecutionRequestApprovalParams__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: CommandExecutionRequestApprovalParams__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | {\n      readonly acceptWithExecpolicyAmendment: {\n        readonly execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | {\n      readonly applyNetworkPolicyAmendment: {\n        readonly network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment;\n      };\n    }\n  | \"decline\"\n  | \"cancel\";\nexport const CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision =\n  Schema.Union(\n    [\n      Schema.Literal(\"accept\").annotate({ description: \"User approved the command.\" }),\n      Schema.Literal(\"acceptForSession\").annotate({\n        description:\n          \"User approved the command and future prompts in the same session-scoped approval cache should run without prompting.\",\n      }),\n      Schema.Struct({\n        acceptWithExecpolicyAmendment: Schema.Struct({\n          execpolicy_amendment: Schema.Array(Schema.String),\n        }),\n      }).annotate({\n        title: \"AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision\",\n        description:\n          \"User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.\",\n      }),\n      Schema.Struct({\n        applyNetworkPolicyAmendment: Schema.Struct({\n          network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment,\n        }),\n      }).annotate({\n        title: \"ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision\",\n        description: \"User chose a persistent network policy rule (allow/deny) for this host.\",\n      }),\n      Schema.Literal(\"decline\").annotate({\n        description: \"User denied the command. The agent will continue the turn.\",\n      }),\n      Schema.Literal(\"cancel\").annotate({\n        description: \"User denied the command. The turn will also be immediately interrupted.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type ExecCommandApprovalResponse__ReviewDecision =\n  | \"approved\"\n  | {\n      readonly approved_execpolicy_amendment: {\n        readonly proposed_execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | \"approved_for_session\"\n  | {\n      readonly network_policy_amendment: {\n        readonly network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment;\n      };\n    }\n  | \"denied\"\n  | \"timed_out\"\n  | \"abort\";\nexport const ExecCommandApprovalResponse__ReviewDecision = Schema.Union(\n  [\n    Schema.Literal(\"approved\").annotate({\n      description: \"User has approved this command and the agent should execute it.\",\n    }),\n    Schema.Struct({\n      approved_execpolicy_amendment: Schema.Struct({\n        proposed_execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"ApprovedExecpolicyAmendmentReviewDecision\",\n      description:\n        \"User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.\",\n    }),\n    Schema.Literal(\"approved_for_session\").annotate({\n      description:\n        \"User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.\",\n    }),\n    Schema.Struct({\n      network_policy_amendment: Schema.Struct({\n        network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"NetworkPolicyAmendmentReviewDecision\",\n      description:\n        \"User chose to persist a network policy rule (allow/deny) for future requests to the same host.\",\n    }),\n    Schema.Literal(\"denied\").annotate({\n      description:\n        \"User has denied this command and the agent should not execute it, but it should continue the session and try something else.\",\n    }),\n    Schema.Literal(\"timed_out\").annotate({\n      description: \"Automatic approval review timed out before reaching a decision.\",\n    }),\n    Schema.Literal(\"abort\").annotate({\n      description:\n        \"User has denied this command and the agent should not do anything until the user's next command.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"User's decision in response to an ExecApprovalRequest.\" });\n\nexport type McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationArrayType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems,\n    maxItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    minItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationArrayType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationArrayType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems,\n    maxItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    minItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationArrayType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema =\n  | McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema;\nexport const McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema = Schema.Union(\n  [\n    McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema,\n    McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema,\n  ],\n);\n\nexport type PermissionsRequestApprovalParams__FileSystemPath =\n  | { readonly path: PermissionsRequestApprovalParams__LegacyAppPathString; readonly type: \"path\" }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: PermissionsRequestApprovalParams__FileSystemSpecialPath;\n    };\nexport const PermissionsRequestApprovalParams__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: PermissionsRequestApprovalParams__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: PermissionsRequestApprovalParams__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type PermissionsRequestApprovalResponse__FileSystemPath =\n  | {\n      readonly path: PermissionsRequestApprovalResponse__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: PermissionsRequestApprovalResponse__FileSystemSpecialPath;\n    };\nexport const PermissionsRequestApprovalResponse__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: PermissionsRequestApprovalResponse__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: PermissionsRequestApprovalResponse__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__AppInfo = {\n  readonly appMetadata?: ServerNotification__AppMetadata | null;\n  readonly branding?: ServerNotification__AppBranding | null;\n  readonly description?: string | null;\n  readonly distributionChannel?: string | null;\n  readonly iconAssets?: { readonly [x: string]: string } | null;\n  readonly iconDarkAssets?: { readonly [x: string]: string } | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly isAccessible?: boolean;\n  readonly isEnabled?: boolean;\n  readonly labels?: { readonly [x: string]: string } | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly name: string;\n  readonly pluginDisplayNames?: ReadonlyArray<string>;\n};\nexport const ServerNotification__AppInfo = Schema.Struct({\n  appMetadata: Schema.optionalKey(Schema.Union([ServerNotification__AppMetadata, Schema.Null])),\n  branding: Schema.optionalKey(Schema.Union([ServerNotification__AppBranding, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  iconDarkAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isEnabled: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```\",\n      default: true,\n    }),\n  ),\n  labels: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type ServerNotification__ExternalAgentConfigImportTypeResult = {\n  readonly failures: ReadonlyArray<ServerNotification__ExternalAgentConfigImportItemTypeFailure>;\n  readonly itemType: ServerNotification__ExternalAgentConfigMigrationItemType;\n  readonly successes: ReadonlyArray<ServerNotification__ExternalAgentConfigImportItemTypeSuccess>;\n};\nexport const ServerNotification__ExternalAgentConfigImportTypeResult = Schema.Struct({\n  failures: Schema.Array(ServerNotification__ExternalAgentConfigImportItemTypeFailure),\n  itemType: ServerNotification__ExternalAgentConfigMigrationItemType,\n  successes: Schema.Array(ServerNotification__ExternalAgentConfigImportItemTypeSuccess),\n});\n\nexport type ServerNotification__FuzzyFileSearchSessionUpdatedNotification = {\n  readonly files: ReadonlyArray<ServerNotification__FuzzyFileSearchResult>;\n  readonly query: string;\n  readonly sessionId: string;\n};\nexport const ServerNotification__FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({\n  files: Schema.Array(ServerNotification__FuzzyFileSearchResult),\n  query: Schema.String,\n  sessionId: Schema.String,\n});\n\nexport type ServerNotification__HookRunSummary = {\n  readonly completedAt?: number | null;\n  readonly displayOrder: number;\n  readonly durationMs?: number | null;\n  readonly entries: ReadonlyArray<ServerNotification__HookOutputEntry>;\n  readonly eventName: ServerNotification__HookEventName;\n  readonly executionMode: ServerNotification__HookExecutionMode;\n  readonly handlerType: ServerNotification__HookHandlerType;\n  readonly id: string;\n  readonly scope: ServerNotification__HookScope;\n  readonly source?:\n    | \"system\"\n    | \"user\"\n    | \"project\"\n    | \"mdm\"\n    | \"sessionFlags\"\n    | \"plugin\"\n    | \"cloudRequirements\"\n    | \"cloudManagedConfig\"\n    | \"legacyManagedConfigFile\"\n    | \"legacyManagedConfigMdm\"\n    | \"unknown\";\n  readonly sourcePath: ServerNotification__AbsolutePathBuf;\n  readonly startedAt: number;\n  readonly status: ServerNotification__HookRunStatus;\n  readonly statusMessage?: string | null;\n};\nexport const ServerNotification__HookRunSummary = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  durationMs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  entries: Schema.Array(ServerNotification__HookOutputEntry),\n  eventName: ServerNotification__HookEventName,\n  executionMode: ServerNotification__HookExecutionMode,\n  handlerType: ServerNotification__HookHandlerType,\n  id: Schema.String,\n  scope: ServerNotification__HookScope,\n  source: Schema.optionalKey(\n    Schema.Literals([\n      \"system\",\n      \"user\",\n      \"project\",\n      \"mdm\",\n      \"sessionFlags\",\n      \"plugin\",\n      \"cloudRequirements\",\n      \"cloudManagedConfig\",\n      \"legacyManagedConfigFile\",\n      \"legacyManagedConfigMdm\",\n      \"unknown\",\n    ]).annotate({ default: \"unknown\" }),\n  ),\n  sourcePath: ServerNotification__AbsolutePathBuf,\n  startedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  status: ServerNotification__HookRunStatus,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__FileSystemPath =\n  | { readonly path: ServerNotification__LegacyAppPathString; readonly type: \"path\" }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | { readonly type: \"special\"; readonly value: ServerNotification__FileSystemSpecialPath };\nexport const ServerNotification__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: ServerNotification__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: ServerNotification__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: ServerNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const ServerNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([ServerNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type ServerNotification__FileChangePatchUpdatedNotification = {\n  readonly changes: ReadonlyArray<ServerNotification__FileUpdateChange>;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__FileChangePatchUpdatedNotification = Schema.Struct({\n  changes: Schema.Array(ServerNotification__FileUpdateChange),\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__CollaborationMode = {\n  readonly mode: ServerNotification__ModeKind;\n  readonly settings: ServerNotification__Settings;\n};\nexport const ServerNotification__CollaborationMode = Schema.Struct({\n  mode: ServerNotification__ModeKind,\n  settings: ServerNotification__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type ServerNotification__AccountRateLimitsUpdatedNotification = {\n  readonly rateLimits: ServerNotification__RateLimitSnapshot;\n};\nexport const ServerNotification__AccountRateLimitsUpdatedNotification = Schema.Struct({\n  rateLimits: ServerNotification__RateLimitSnapshot,\n}).annotate({\n  description:\n    \"Sparse rolling rate-limit update.\\n\\nClients should merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and does not clear a previously observed value.\",\n});\n\nexport type ServerNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<ServerNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<ServerNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: ServerNotification__MemoryCitation | null;\n      readonly phase?: ServerNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<ServerNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: ServerNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<ServerNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: ServerNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: ServerNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: ServerNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: ServerNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: ServerNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<ServerNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: ServerNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: ServerNotification__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: ServerNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: ServerNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: ServerNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: ServerNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: ServerNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const ServerNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(ServerNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(ServerNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([ServerNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([ServerNotification__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(ServerNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: ServerNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(ServerNotification__FileUpdateChange),\n      id: Schema.String,\n      status: ServerNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([ServerNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(Schema.Union([ServerNotification__McpToolCallError, Schema.Null])),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([ServerNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: ServerNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(ServerNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: ServerNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, ServerNotification__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([ServerNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: ServerNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(Schema.Union([ServerNotification__WebSearchAction, Schema.Null])),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: ServerNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([ServerNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ConfigWarningNotification = {\n  readonly details?: string | null;\n  readonly path?: string | null;\n  readonly range?: ServerNotification__TextRange | null;\n  readonly summary: string;\n};\nexport const ServerNotification__ConfigWarningNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional extra guidance or error details.\" }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional path to the config file that triggered the warning.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  range: Schema.optionalKey(\n    Schema.Union([ServerNotification__TextRange, Schema.Null]).annotate({\n      description: \"Optional range for the error location inside the config file.\",\n    }),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of the warning.\" }),\n});\n\nexport type ServerNotification__ThreadStatusChangedNotification = {\n  readonly status: ServerNotification__ThreadStatus;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadStatusChangedNotification = Schema.Struct({\n  status: ServerNotification__ThreadStatus,\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadGoalUpdatedNotification = {\n  readonly goal: ServerNotification__ThreadGoal;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const ServerNotification__ThreadGoalUpdatedNotification = Schema.Struct({\n  goal: ServerNotification__ThreadGoal,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__ThreadTokenUsageUpdatedNotification = {\n  readonly threadId: string;\n  readonly tokenUsage: ServerNotification__ThreadTokenUsage;\n  readonly turnId: string;\n};\nexport const ServerNotification__ThreadTokenUsageUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  tokenUsage: ServerNotification__ThreadTokenUsage,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__TurnPlanUpdatedNotification = {\n  readonly explanation?: string | null;\n  readonly plan: ReadonlyArray<ServerNotification__TurnPlanStep>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TurnPlanUpdatedNotification = Schema.Struct({\n  explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  plan: Schema.Array(ServerNotification__TurnPlanStep),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__FileSystemPath =\n  | { readonly path: ServerRequest__LegacyAppPathString; readonly type: \"path\" }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | { readonly type: \"special\"; readonly value: ServerRequest__FileSystemSpecialPath };\nexport const ServerRequest__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: ServerRequest__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: ServerRequest__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__McpElicitationTitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: ServerRequest__McpElicitationTitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationArrayType;\n};\nexport const ServerRequest__McpElicitationTitledMultiSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  items: ServerRequest__McpElicitationTitledEnumItems,\n  maxItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationArrayType,\n});\n\nexport type ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: ServerRequest__McpElicitationUntitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationArrayType;\n};\nexport const ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  items: ServerRequest__McpElicitationUntitledEnumItems,\n  maxItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationArrayType,\n});\n\nexport type ServerRequest__McpElicitationSingleSelectEnumSchema =\n  | ServerRequest__McpElicitationUntitledSingleSelectEnumSchema\n  | ServerRequest__McpElicitationTitledSingleSelectEnumSchema;\nexport const ServerRequest__McpElicitationSingleSelectEnumSchema = Schema.Union([\n  ServerRequest__McpElicitationUntitledSingleSelectEnumSchema,\n  ServerRequest__McpElicitationTitledSingleSelectEnumSchema,\n]);\n\nexport type ServerRequest__CommandExecutionRequestApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly command?: string | null;\n  readonly commandActions?: ReadonlyArray<ServerRequest__CommandAction> | null;\n  readonly cwd?: ServerRequest__LegacyAppPathString | null;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly networkApprovalContext?: ServerRequest__NetworkApprovalContext | null;\n  readonly proposedExecpolicyAmendment?: ReadonlyArray<string> | null;\n  readonly proposedNetworkPolicyAmendments?: ReadonlyArray<ServerRequest__NetworkPolicyAmendment> | null;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__CommandExecutionRequestApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Unique identifier for this specific approval callback.\\n\\nFor regular shell/unified_exec approvals, this is null.\\n\\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  command: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"The command to be executed.\" }),\n      Schema.Null,\n    ]),\n  ),\n  commandActions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__CommandAction).annotate({\n        description: \"Best-effort parsed command actions for friendly display.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([ServerRequest__LegacyAppPathString, Schema.Null]).annotate({\n      description: \"The command's working directory.\",\n    }),\n  ),\n  environmentId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Environment in which the command will run.\" }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  networkApprovalContext: Schema.optionalKey(\n    Schema.Union([ServerRequest__NetworkApprovalContext, Schema.Null]).annotate({\n      description: \"Optional context for a managed-network approval prompt.\",\n    }),\n  ),\n  proposedExecpolicyAmendment: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional proposed execpolicy amendment to allow similar commands without prompting.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  proposedNetworkPolicyAmendments: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__NetworkPolicyAmendment).annotate({\n        description:\n          \"Optional proposed network policy amendments (allow/deny host) for future requests.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for network access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__ToolRequestUserInputParams = {\n  readonly autoResolutionMs?: number | null;\n  readonly itemId: string;\n  readonly questions: ReadonlyArray<ServerRequest__ToolRequestUserInputQuestion>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__ToolRequestUserInputParams = Schema.Struct({\n  autoResolutionMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  questions: Schema.Array(ServerRequest__ToolRequestUserInputQuestion),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL. Params sent with a request_user_input event.\" });\n\nexport type V2AppListUpdatedNotification__AppInfo = {\n  readonly appMetadata?: V2AppListUpdatedNotification__AppMetadata | null;\n  readonly branding?: V2AppListUpdatedNotification__AppBranding | null;\n  readonly description?: string | null;\n  readonly distributionChannel?: string | null;\n  readonly iconAssets?: { readonly [x: string]: string } | null;\n  readonly iconDarkAssets?: { readonly [x: string]: string } | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly isAccessible?: boolean;\n  readonly isEnabled?: boolean;\n  readonly labels?: { readonly [x: string]: string } | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly name: string;\n  readonly pluginDisplayNames?: ReadonlyArray<string>;\n};\nexport const V2AppListUpdatedNotification__AppInfo = Schema.Struct({\n  appMetadata: Schema.optionalKey(\n    Schema.Union([V2AppListUpdatedNotification__AppMetadata, Schema.Null]),\n  ),\n  branding: Schema.optionalKey(\n    Schema.Union([V2AppListUpdatedNotification__AppBranding, Schema.Null]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  iconDarkAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isEnabled: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```\",\n      default: true,\n    }),\n  ),\n  labels: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2AppsListResponse__AppInfo = {\n  readonly appMetadata?: V2AppsListResponse__AppMetadata | null;\n  readonly branding?: V2AppsListResponse__AppBranding | null;\n  readonly description?: string | null;\n  readonly distributionChannel?: string | null;\n  readonly iconAssets?: { readonly [x: string]: string } | null;\n  readonly iconDarkAssets?: { readonly [x: string]: string } | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly isAccessible?: boolean;\n  readonly isEnabled?: boolean;\n  readonly labels?: { readonly [x: string]: string } | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly name: string;\n  readonly pluginDisplayNames?: ReadonlyArray<string>;\n};\nexport const V2AppsListResponse__AppInfo = Schema.Struct({\n  appMetadata: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppMetadata, Schema.Null])),\n  branding: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppBranding, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  iconDarkAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isEnabled: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```\",\n      default: true,\n    }),\n  ),\n  labels: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2ConfigReadResponse__ConfigLayer = {\n  readonly config: unknown;\n  readonly disabledReason?: string | null;\n  readonly name: V2ConfigReadResponse__ConfigLayerSource;\n  readonly version: string;\n};\nexport const V2ConfigReadResponse__ConfigLayer = Schema.Struct({\n  config: Schema.Unknown,\n  disabledReason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: V2ConfigReadResponse__ConfigLayerSource,\n  version: Schema.String,\n});\n\nexport type V2ConfigReadResponse__ConfigLayerMetadata = {\n  readonly name: V2ConfigReadResponse__ConfigLayerSource;\n  readonly version: string;\n};\nexport const V2ConfigReadResponse__ConfigLayerMetadata = Schema.Struct({\n  name: V2ConfigReadResponse__ConfigLayerSource,\n  version: Schema.String,\n});\n\nexport type V2ConfigReadResponse__ToolsV2 = {\n  readonly web_search?: V2ConfigReadResponse__WebSearchToolConfig | null;\n};\nexport const V2ConfigReadResponse__ToolsV2 = Schema.Struct({\n  web_search: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__WebSearchToolConfig, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigRequirementsReadResponse__ModelsRequirements = {\n  readonly newThread?: V2ConfigRequirementsReadResponse__NewThreadModelDefaults | null;\n};\nexport const V2ConfigRequirementsReadResponse__ModelsRequirements = Schema.Struct({\n  newThread: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__NewThreadModelDefaults, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigWriteResponse__ConfigLayerMetadata = {\n  readonly name: V2ConfigWriteResponse__ConfigLayerSource;\n  readonly version: string;\n};\nexport const V2ConfigWriteResponse__ConfigLayerMetadata = Schema.Struct({\n  name: V2ConfigWriteResponse__ConfigLayerSource,\n  version: Schema.String,\n});\n\nexport type V2ErrorNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ErrorNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ErrorNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ErrorNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = {\n  readonly cwd?: string | null;\n  readonly description: string;\n  readonly details?: V2ExternalAgentConfigDetectResponse__MigrationDetails | null;\n  readonly itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType;\n};\nexport const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Null or empty means home-scoped migration; non-empty means repo-scoped migration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  details: Schema.optionalKey(\n    Schema.Union([V2ExternalAgentConfigDetectResponse__MigrationDetails, Schema.Null]),\n  ),\n  itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType,\n});\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult =\n  {\n    readonly failures: ReadonlyArray<V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure>;\n    readonly itemType: V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType;\n    readonly successes: ReadonlyArray<V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess>;\n  };\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult =\n  Schema.Struct({\n    failures: Schema.Array(\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure,\n    ),\n    itemType:\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType,\n    successes: Schema.Array(\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess,\n    ),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory = {\n  readonly completedAtMs: number;\n  readonly failures: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure>;\n  readonly importId: string;\n  readonly successes: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess>;\n};\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory =\n  Schema.Struct({\n    completedAtMs: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n    failures: Schema.Array(\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure,\n    ),\n    importId: Schema.String,\n    successes: Schema.Array(\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess,\n    ),\n  });\n\nexport type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = {\n  readonly cwd?: string | null;\n  readonly description: string;\n  readonly details?: V2ExternalAgentConfigImportParams__MigrationDetails | null;\n  readonly itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType;\n};\nexport const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Null or empty means home-scoped migration; non-empty means repo-scoped migration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  details: Schema.optionalKey(\n    Schema.Union([V2ExternalAgentConfigImportParams__MigrationDetails, Schema.Null]),\n  ),\n  itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType,\n});\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult = {\n  readonly failures: ReadonlyArray<V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure>;\n  readonly itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType;\n  readonly successes: ReadonlyArray<V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess>;\n};\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult =\n  Schema.Struct({\n    failures: Schema.Array(\n      V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure,\n    ),\n    itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType,\n    successes: Schema.Array(\n      V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess,\n    ),\n  });\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary = {\n  readonly availableCount: number;\n  readonly credits?: ReadonlyArray<V2GetAccountRateLimitsResponse__RateLimitResetCredit> | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary = Schema.Struct({\n  availableCount: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  credits: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2GetAccountRateLimitsResponse__RateLimitResetCredit).annotate({\n        description:\n          \"Detail rows for available reset credits, when the backend provides them.\\n\\n`null` means only `availableCount` is known, while an empty array means details were fetched and no available credits were returned. The backend may cap this list, so its length can be less than `availableCount`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2HookCompletedNotification__HookRunSummary = {\n  readonly completedAt?: number | null;\n  readonly displayOrder: number;\n  readonly durationMs?: number | null;\n  readonly entries: ReadonlyArray<V2HookCompletedNotification__HookOutputEntry>;\n  readonly eventName: V2HookCompletedNotification__HookEventName;\n  readonly executionMode: V2HookCompletedNotification__HookExecutionMode;\n  readonly handlerType: V2HookCompletedNotification__HookHandlerType;\n  readonly id: string;\n  readonly scope: V2HookCompletedNotification__HookScope;\n  readonly source?:\n    | \"system\"\n    | \"user\"\n    | \"project\"\n    | \"mdm\"\n    | \"sessionFlags\"\n    | \"plugin\"\n    | \"cloudRequirements\"\n    | \"cloudManagedConfig\"\n    | \"legacyManagedConfigFile\"\n    | \"legacyManagedConfigMdm\"\n    | \"unknown\";\n  readonly sourcePath: V2HookCompletedNotification__AbsolutePathBuf;\n  readonly startedAt: number;\n  readonly status: V2HookCompletedNotification__HookRunStatus;\n  readonly statusMessage?: string | null;\n};\nexport const V2HookCompletedNotification__HookRunSummary = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  durationMs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  entries: Schema.Array(V2HookCompletedNotification__HookOutputEntry),\n  eventName: V2HookCompletedNotification__HookEventName,\n  executionMode: V2HookCompletedNotification__HookExecutionMode,\n  handlerType: V2HookCompletedNotification__HookHandlerType,\n  id: Schema.String,\n  scope: V2HookCompletedNotification__HookScope,\n  source: Schema.optionalKey(\n    Schema.Literals([\n      \"system\",\n      \"user\",\n      \"project\",\n      \"mdm\",\n      \"sessionFlags\",\n      \"plugin\",\n      \"cloudRequirements\",\n      \"cloudManagedConfig\",\n      \"legacyManagedConfigFile\",\n      \"legacyManagedConfigMdm\",\n      \"unknown\",\n    ]).annotate({ default: \"unknown\" }),\n  ),\n  sourcePath: V2HookCompletedNotification__AbsolutePathBuf,\n  startedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  status: V2HookCompletedNotification__HookRunStatus,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2HooksListResponse__HooksListEntry = {\n  readonly cwd: string;\n  readonly errors: ReadonlyArray<V2HooksListResponse__HookErrorInfo>;\n  readonly hooks: ReadonlyArray<V2HooksListResponse__HookMetadata>;\n  readonly warnings: ReadonlyArray<string>;\n};\nexport const V2HooksListResponse__HooksListEntry = Schema.Struct({\n  cwd: Schema.String,\n  errors: Schema.Array(V2HooksListResponse__HookErrorInfo),\n  hooks: Schema.Array(V2HooksListResponse__HookMetadata),\n  warnings: Schema.Array(Schema.String),\n});\n\nexport type V2HookStartedNotification__HookRunSummary = {\n  readonly completedAt?: number | null;\n  readonly displayOrder: number;\n  readonly durationMs?: number | null;\n  readonly entries: ReadonlyArray<V2HookStartedNotification__HookOutputEntry>;\n  readonly eventName: V2HookStartedNotification__HookEventName;\n  readonly executionMode: V2HookStartedNotification__HookExecutionMode;\n  readonly handlerType: V2HookStartedNotification__HookHandlerType;\n  readonly id: string;\n  readonly scope: V2HookStartedNotification__HookScope;\n  readonly source?:\n    | \"system\"\n    | \"user\"\n    | \"project\"\n    | \"mdm\"\n    | \"sessionFlags\"\n    | \"plugin\"\n    | \"cloudRequirements\"\n    | \"cloudManagedConfig\"\n    | \"legacyManagedConfigFile\"\n    | \"legacyManagedConfigMdm\"\n    | \"unknown\";\n  readonly sourcePath: V2HookStartedNotification__AbsolutePathBuf;\n  readonly startedAt: number;\n  readonly status: V2HookStartedNotification__HookRunStatus;\n  readonly statusMessage?: string | null;\n};\nexport const V2HookStartedNotification__HookRunSummary = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  durationMs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  entries: Schema.Array(V2HookStartedNotification__HookOutputEntry),\n  eventName: V2HookStartedNotification__HookEventName,\n  executionMode: V2HookStartedNotification__HookExecutionMode,\n  handlerType: V2HookStartedNotification__HookHandlerType,\n  id: Schema.String,\n  scope: V2HookStartedNotification__HookScope,\n  source: Schema.optionalKey(\n    Schema.Literals([\n      \"system\",\n      \"user\",\n      \"project\",\n      \"mdm\",\n      \"sessionFlags\",\n      \"plugin\",\n      \"cloudRequirements\",\n      \"cloudManagedConfig\",\n      \"legacyManagedConfigFile\",\n      \"legacyManagedConfigMdm\",\n      \"unknown\",\n    ]).annotate({ default: \"unknown\" }),\n  ),\n  sourcePath: V2HookStartedNotification__AbsolutePathBuf,\n  startedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  status: V2HookStartedNotification__HookRunStatus,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ItemCompletedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ItemCompletedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ItemCompletedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ItemCompletedNotification__MemoryCitation | null;\n      readonly phase?: V2ItemCompletedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ItemCompletedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ItemCompletedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ItemCompletedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ItemCompletedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ItemCompletedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ItemCompletedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ItemCompletedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ItemCompletedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ItemCompletedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ItemCompletedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2ItemCompletedNotification__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ItemCompletedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ItemCompletedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ItemCompletedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ItemCompletedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ItemCompletedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ItemCompletedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ItemCompletedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ItemCompletedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ItemCompletedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ItemCompletedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ItemCompletedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2ItemCompletedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ItemCompletedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ItemCompletedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ItemCompletedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ItemCompletedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ItemCompletedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ItemCompletedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath =\n  | {\n      readonly path: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath;\n    };\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath =\n  | {\n      readonly path: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath;\n    };\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ItemStartedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ItemStartedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ItemStartedNotification__MemoryCitation | null;\n      readonly phase?: V2ItemStartedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ItemStartedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ItemStartedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ItemStartedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ItemStartedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ItemStartedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ItemStartedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ItemStartedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ItemStartedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ItemStartedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ItemStartedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ItemStartedNotification__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ItemStartedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ItemStartedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ItemStartedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ItemStartedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ItemStartedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ItemStartedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ItemStartedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ItemStartedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ItemStartedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ItemStartedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ItemStartedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2ItemStartedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ItemStartedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ItemStartedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ItemStartedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ItemStartedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ItemStartedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ItemStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ModelListResponse__Model = {\n  readonly additionalSpeedTiers?: ReadonlyArray<string>;\n  readonly availabilityNux?: V2ModelListResponse__ModelAvailabilityNux | null;\n  readonly defaultReasoningEffort: V2ModelListResponse__ReasoningEffort;\n  readonly defaultServiceTier?: string | null;\n  readonly description: string;\n  readonly displayName: string;\n  readonly hidden: boolean;\n  readonly id: string;\n  readonly inputModalities?: ReadonlyArray<V2ModelListResponse__InputModality>;\n  readonly isDefault: boolean;\n  readonly model: string;\n  readonly serviceTiers?: ReadonlyArray<V2ModelListResponse__ModelServiceTier>;\n  readonly supportedReasoningEfforts: ReadonlyArray<V2ModelListResponse__ReasoningEffortOption>;\n  readonly supportsPersonality?: boolean;\n  readonly upgrade?: string | null;\n  readonly upgradeInfo?: V2ModelListResponse__ModelUpgradeInfo | null;\n};\nexport const V2ModelListResponse__Model = Schema.Struct({\n  additionalSpeedTiers: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"Deprecated: use `serviceTiers` instead.\",\n      default: [],\n    }),\n  ),\n  availabilityNux: Schema.optionalKey(\n    Schema.Union([V2ModelListResponse__ModelAvailabilityNux, Schema.Null]),\n  ),\n  defaultReasoningEffort: V2ModelListResponse__ReasoningEffort,\n  defaultServiceTier: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Catalog default service tier id for this model, when one is configured.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  displayName: Schema.String,\n  hidden: Schema.Boolean,\n  id: Schema.String,\n  inputModalities: Schema.optionalKey(\n    Schema.Array(V2ModelListResponse__InputModality).annotate({ default: [\"text\", \"image\"] }),\n  ),\n  isDefault: Schema.Boolean,\n  model: Schema.String,\n  serviceTiers: Schema.optionalKey(\n    Schema.Array(V2ModelListResponse__ModelServiceTier).annotate({ default: [] }),\n  ),\n  supportedReasoningEfforts: Schema.Array(V2ModelListResponse__ReasoningEffortOption),\n  supportsPersonality: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  upgrade: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  upgradeInfo: Schema.optionalKey(\n    Schema.Union([V2ModelListResponse__ModelUpgradeInfo, Schema.Null]),\n  ),\n});\n\nexport type V2PluginInstalledResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginInstalledResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginInstalledResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginInstalledResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginInstalledResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginListResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginListResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginListResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginListResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginListResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__SkillSummary = {\n  readonly description: string;\n  readonly enabled: boolean;\n  readonly interface?: V2PluginReadResponse__SkillInterface | null;\n  readonly name: string;\n  readonly path?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly shortDescription?: string | null;\n};\nexport const V2PluginReadResponse__SkillSummary = Schema.Struct({\n  description: Schema.String,\n  enabled: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__SkillInterface, Schema.Null])),\n  name: Schema.String,\n  path: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginReadResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginReadResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginReadResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginReadResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__ScheduledTaskSummary = {\n  readonly key: string;\n  readonly name: string;\n  readonly prompt: string;\n  readonly schedule: V2PluginReadResponse__ScheduledTaskSchedule;\n};\nexport const V2PluginReadResponse__ScheduledTaskSummary = Schema.Struct({\n  key: Schema.String,\n  name: Schema.String,\n  prompt: Schema.String,\n  schedule: V2PluginReadResponse__ScheduledTaskSchedule,\n});\n\nexport type V2PluginShareListResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginShareListResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginShareListResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginShareListResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginShareListResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2RawResponseItemCompletedNotification__FunctionCallOutputBody =\n  | string\n  | ReadonlyArray<V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem>;\nexport const V2RawResponseItemCompletedNotification__FunctionCallOutputBody = Schema.Union([\n  Schema.String,\n  Schema.Array(V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem),\n]);\n\nexport type V2ReviewStartResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ReviewStartResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ReviewStartResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ReviewStartResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ReviewStartResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ReviewStartResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ReviewStartResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ReviewStartResponse__MemoryCitation | null;\n      readonly phase?: V2ReviewStartResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ReviewStartResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ReviewStartResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ReviewStartResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ReviewStartResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ReviewStartResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ReviewStartResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ReviewStartResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ReviewStartResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ReviewStartResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ReviewStartResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ReviewStartResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ReviewStartResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ReviewStartResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ReviewStartResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ReviewStartResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ReviewStartResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ReviewStartResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ReviewStartResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ReviewStartResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ReviewStartResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ReviewStartResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ReviewStartResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ReviewStartResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ReviewStartResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ReviewStartResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ReviewStartResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ReviewStartResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ReviewStartResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ReviewStartResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2SkillsListResponse__SkillMetadata = {\n  readonly dependencies?: V2SkillsListResponse__SkillDependencies | null;\n  readonly description: string;\n  readonly enabled: boolean;\n  readonly interface?: V2SkillsListResponse__SkillInterface | null;\n  readonly name: string;\n  readonly path: V2SkillsListResponse__AbsolutePathBuf;\n  readonly scope: V2SkillsListResponse__SkillScope;\n  readonly shortDescription?: string | null;\n};\nexport const V2SkillsListResponse__SkillMetadata = Schema.Struct({\n  dependencies: Schema.optionalKey(\n    Schema.Union([V2SkillsListResponse__SkillDependencies, Schema.Null]),\n  ),\n  description: Schema.String,\n  enabled: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2SkillsListResponse__SkillInterface, Schema.Null])),\n  name: Schema.String,\n  path: V2SkillsListResponse__AbsolutePathBuf,\n  scope: V2SkillsListResponse__SkillScope,\n  shortDescription: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadForkResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadForkResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadForkResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadForkResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadForkResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadForkResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadForkResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadForkResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadForkResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadForkResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadForkResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadForkResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadForkResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadForkResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadForkResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadForkResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadForkResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadForkResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadForkResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadForkResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadForkResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadForkResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadForkResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadForkResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadForkResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadForkResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadForkResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadForkResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadForkResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadForkResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadForkResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadForkResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadForkResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadForkResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadForkResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadForkResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadListResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadListResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadListResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadListResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadListResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadListResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadListResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadListResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadListResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadListResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadListResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadListResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadListResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadListResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadListResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadListResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadListResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadListResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadListResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadListResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadListResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadListResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadListResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadListResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadListResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadListResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadListResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadListResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadListResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadListResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadListResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadListResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadListResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadListResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadListResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadListResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadListResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadMetadataUpdateResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadMetadataUpdateResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadMetadataUpdateResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadMetadataUpdateResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadMetadataUpdateResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadMetadataUpdateResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadMetadataUpdateResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadMetadataUpdateResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadMetadataUpdateResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadMetadataUpdateResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadMetadataUpdateResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadMetadataUpdateResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadMetadataUpdateResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2ThreadMetadataUpdateResponse__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadMetadataUpdateResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadMetadataUpdateResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadMetadataUpdateResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadMetadataUpdateResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadMetadataUpdateResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadMetadataUpdateResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadMetadataUpdateResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadMetadataUpdateResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadMetadataUpdateResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadMetadataUpdateResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadMetadataUpdateResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadMetadataUpdateResponse__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadMetadataUpdateResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadMetadataUpdateResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadReadResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadReadResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadReadResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadReadResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadReadResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadReadResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadReadResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadReadResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadReadResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadReadResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadReadResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadReadResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadReadResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadReadResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadReadResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadReadResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadReadResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadReadResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadReadResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadReadResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadReadResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadReadResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadReadResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadReadResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadReadResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadReadResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadReadResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadReadResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadReadResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadReadResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadReadResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadReadResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadReadResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadReadResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadReadResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadReadResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__FunctionCallOutputBody =\n  | string\n  | ReadonlyArray<V2ThreadResumeParams__FunctionCallOutputContentItem>;\nexport const V2ThreadResumeParams__FunctionCallOutputBody = Schema.Union([\n  Schema.String,\n  Schema.Array(V2ThreadResumeParams__FunctionCallOutputContentItem),\n]);\n\nexport type V2ThreadResumeResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadResumeResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadResumeResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadResumeResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadResumeResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadResumeResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadResumeResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadResumeResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadResumeResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadResumeResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadResumeResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadResumeResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadResumeResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadResumeResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadResumeResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadResumeResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadResumeResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadResumeResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadResumeResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadResumeResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadResumeResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadResumeResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadResumeResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadResumeResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadResumeResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadResumeResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadResumeResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadResumeResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadResumeResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadResumeResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadResumeResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadResumeResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadResumeResponse__CollabAgentState).annotate(\n        { description: \"Last known status of the target agents, when available.\" },\n      ),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadResumeResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadResumeResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadRollbackResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadRollbackResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadRollbackResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadRollbackResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadRollbackResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadRollbackResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadRollbackResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadRollbackResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadRollbackResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadRollbackResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadRollbackResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadRollbackResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadRollbackResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadRollbackResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadRollbackResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadRollbackResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadRollbackResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadRollbackResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadRollbackResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadRollbackResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadRollbackResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadRollbackResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadRollbackResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadRollbackResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadRollbackResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadRollbackResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadRollbackResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadRollbackResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadRollbackResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadRollbackResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadRollbackResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadRollbackResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadRollbackResponse__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadRollbackResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadRollbackResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__CollaborationMode = {\n  readonly mode: V2ThreadSettingsUpdatedNotification__ModeKind;\n  readonly settings: V2ThreadSettingsUpdatedNotification__Settings;\n};\nexport const V2ThreadSettingsUpdatedNotification__CollaborationMode = Schema.Struct({\n  mode: V2ThreadSettingsUpdatedNotification__ModeKind,\n  settings: V2ThreadSettingsUpdatedNotification__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type V2ThreadStartedNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadStartedNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadStartedNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadStartedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadStartedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadStartedNotification__MemoryCitation | null;\n      readonly phase?: V2ThreadStartedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadStartedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadStartedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadStartedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadStartedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadStartedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadStartedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadStartedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadStartedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadStartedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadStartedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2ThreadStartedNotification__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadStartedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadStartedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadStartedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadStartedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadStartedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadStartedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadStartedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadStartedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadStartedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadStartedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadStartedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadStartedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadStartedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadStartedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadStartedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadStartedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadStartedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadStartResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadStartResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadStartResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadStartResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadStartResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadStartResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadStartResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadStartResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadStartResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadStartResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadStartResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadStartResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadStartResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadStartResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadStartResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadStartResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadStartResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadStartResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadStartResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadStartResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadStartResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadStartResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadStartResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadStartResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadStartResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadStartResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadStartResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadStartResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadStartResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadStartResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadStartResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadStartResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadStartResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadStartResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadStartResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadUnarchiveResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadUnarchiveResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadUnarchiveResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadUnarchiveResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadUnarchiveResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadUnarchiveResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadUnarchiveResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadUnarchiveResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadUnarchiveResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadUnarchiveResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadUnarchiveResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadUnarchiveResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadUnarchiveResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadUnarchiveResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadUnarchiveResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadUnarchiveResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadUnarchiveResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadUnarchiveResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadUnarchiveResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadUnarchiveResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadUnarchiveResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadUnarchiveResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadUnarchiveResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadUnarchiveResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadUnarchiveResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadUnarchiveResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadUnarchiveResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadUnarchiveResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadUnarchiveResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadUnarchiveResponse__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadUnarchiveResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadUnarchiveResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2TurnCompletedNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2TurnCompletedNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2TurnCompletedNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2TurnCompletedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2TurnCompletedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2TurnCompletedNotification__MemoryCitation | null;\n      readonly phase?: V2TurnCompletedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2TurnCompletedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2TurnCompletedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2TurnCompletedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2TurnCompletedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2TurnCompletedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2TurnCompletedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2TurnCompletedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2TurnCompletedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2TurnCompletedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2TurnCompletedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2TurnCompletedNotification__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2TurnCompletedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2TurnCompletedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2TurnCompletedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2TurnCompletedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2TurnCompletedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2TurnCompletedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2TurnCompletedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2TurnCompletedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2TurnCompletedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2TurnCompletedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2TurnCompletedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2TurnCompletedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2TurnCompletedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2TurnCompletedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2TurnCompletedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2TurnCompletedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2TurnCompletedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2TurnCompletedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2TurnStartedNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2TurnStartedNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2TurnStartedNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2TurnStartedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2TurnStartedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2TurnStartedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2TurnStartedNotification__MemoryCitation | null;\n      readonly phase?: V2TurnStartedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2TurnStartedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2TurnStartedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2TurnStartedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2TurnStartedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2TurnStartedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2TurnStartedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2TurnStartedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2TurnStartedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2TurnStartedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2TurnStartedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2TurnStartedNotification__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2TurnStartedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2TurnStartedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2TurnStartedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2TurnStartedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2TurnStartedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2TurnStartedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2TurnStartedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2TurnStartedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2TurnStartedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2TurnStartedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2TurnStartedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2TurnStartedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2TurnStartedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2TurnStartedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2TurnStartedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2TurnStartedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2TurnStartedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2TurnStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2TurnStartResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2TurnStartResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2TurnStartResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2TurnStartResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2TurnStartResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2TurnStartResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2TurnStartResponse__MemoryCitation | null;\n      readonly phase?: V2TurnStartResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2TurnStartResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2TurnStartResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2TurnStartResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2TurnStartResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2TurnStartResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2TurnStartResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2TurnStartResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2TurnStartResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2TurnStartResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2TurnStartResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2TurnStartResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2TurnStartResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2TurnStartResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2TurnStartResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2TurnStartResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2TurnStartResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2TurnStartResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2TurnStartResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2TurnStartResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2TurnStartResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2TurnStartResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2TurnStartResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2TurnStartResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2TurnStartResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(Schema.Union([V2TurnStartResponse__McpToolCallError, Schema.Null])),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2TurnStartResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2TurnStartResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2TurnStartResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2TurnStartResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2TurnStartResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(Schema.Union([V2TurnStartResponse__WebSearchAction, Schema.Null])),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2TurnStartResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ExternalAgentConfigImportParams = {\n  readonly migrationItems: ReadonlyArray<ClientRequest__ExternalAgentConfigMigrationItem>;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const ClientRequest__ExternalAgentConfigImportParams = Schema.Struct({\n  migrationItems: Schema.Array(ClientRequest__ExternalAgentConfigMigrationItem),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Migration-source selector used to produce the migration items. Pass the same value to detection and import; missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional identifier for the product that initiated the import.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type CommandExecutionRequestApprovalParams__FileSystemSandboxEntry = {\n  readonly access: CommandExecutionRequestApprovalParams__FileSystemAccessMode;\n  readonly path: CommandExecutionRequestApprovalParams__FileSystemPath;\n};\nexport const CommandExecutionRequestApprovalParams__FileSystemSandboxEntry = Schema.Struct({\n  access: CommandExecutionRequestApprovalParams__FileSystemAccessMode,\n  path: CommandExecutionRequestApprovalParams__FileSystemPath,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema =\n  | McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema;\nexport const McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema = Schema.Union([\n  McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema,\n]);\n\nexport type PermissionsRequestApprovalParams__FileSystemSandboxEntry = {\n  readonly access: PermissionsRequestApprovalParams__FileSystemAccessMode;\n  readonly path: PermissionsRequestApprovalParams__FileSystemPath;\n};\nexport const PermissionsRequestApprovalParams__FileSystemSandboxEntry = Schema.Struct({\n  access: PermissionsRequestApprovalParams__FileSystemAccessMode,\n  path: PermissionsRequestApprovalParams__FileSystemPath,\n});\n\nexport type PermissionsRequestApprovalResponse__FileSystemSandboxEntry = {\n  readonly access: PermissionsRequestApprovalResponse__FileSystemAccessMode;\n  readonly path: PermissionsRequestApprovalResponse__FileSystemPath;\n};\nexport const PermissionsRequestApprovalResponse__FileSystemSandboxEntry = Schema.Struct({\n  access: PermissionsRequestApprovalResponse__FileSystemAccessMode,\n  path: PermissionsRequestApprovalResponse__FileSystemPath,\n});\n\nexport type ServerNotification__AppListUpdatedNotification = {\n  readonly data: ReadonlyArray<ServerNotification__AppInfo>;\n};\nexport const ServerNotification__AppListUpdatedNotification = Schema.Struct({\n  data: Schema.Array(ServerNotification__AppInfo),\n}).annotate({ description: \"EXPERIMENTAL - notification emitted when the app list changes.\" });\n\nexport type ServerNotification__ExternalAgentConfigImportCompletedNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<ServerNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const ServerNotification__ExternalAgentConfigImportCompletedNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(ServerNotification__ExternalAgentConfigImportTypeResult),\n});\n\nexport type ServerNotification__ExternalAgentConfigImportProgressNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<ServerNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const ServerNotification__ExternalAgentConfigImportProgressNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(ServerNotification__ExternalAgentConfigImportTypeResult),\n});\n\nexport type ServerNotification__HookCompletedNotification = {\n  readonly run: ServerNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const ServerNotification__HookCompletedNotification = Schema.Struct({\n  run: ServerNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__HookStartedNotification = {\n  readonly run: ServerNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const ServerNotification__HookStartedNotification = Schema.Struct({\n  run: ServerNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__FileSystemSandboxEntry = {\n  readonly access: ServerNotification__FileSystemAccessMode;\n  readonly path: ServerNotification__FileSystemPath;\n};\nexport const ServerNotification__FileSystemSandboxEntry = Schema.Struct({\n  access: ServerNotification__FileSystemAccessMode,\n  path: ServerNotification__FileSystemPath,\n});\n\nexport type ServerNotification__ErrorNotification = {\n  readonly error: ServerNotification__TurnError;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly willRetry: boolean;\n};\nexport const ServerNotification__ErrorNotification = Schema.Struct({\n  error: ServerNotification__TurnError,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  willRetry: Schema.Boolean,\n});\n\nexport type ServerNotification__ThreadSettings = {\n  readonly activePermissionProfile?: ServerNotification__ActivePermissionProfile | null;\n  readonly approvalPolicy: ServerNotification__AskForApproval;\n  readonly approvalsReviewer: ServerNotification__ApprovalsReviewer;\n  readonly collaborationMode: ServerNotification__CollaborationMode;\n  readonly cwd: ServerNotification__AbsolutePathBuf;\n  readonly effort?: ServerNotification__ReasoningEffort | null;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly personality?: ServerNotification__Personality | null;\n  readonly sandboxPolicy: ServerNotification__SandboxPolicy;\n  readonly serviceTier?: string | null;\n  readonly summary?: ServerNotification__ReasoningSummary | null;\n};\nexport const ServerNotification__ThreadSettings = Schema.Struct({\n  activePermissionProfile: Schema.optionalKey(\n    Schema.Union([ServerNotification__ActivePermissionProfile, Schema.Null]),\n  ),\n  approvalPolicy: ServerNotification__AskForApproval,\n  approvalsReviewer: ServerNotification__ApprovalsReviewer,\n  collaborationMode: ServerNotification__CollaborationMode,\n  cwd: ServerNotification__AbsolutePathBuf,\n  effort: Schema.optionalKey(Schema.Union([ServerNotification__ReasoningEffort, Schema.Null])),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  personality: Schema.optionalKey(Schema.Union([ServerNotification__Personality, Schema.Null])),\n  sandboxPolicy: ServerNotification__SandboxPolicy,\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  summary: Schema.optionalKey(Schema.Union([ServerNotification__ReasoningSummary, Schema.Null])),\n});\n\nexport type ServerNotification__ItemCompletedNotification = {\n  readonly completedAtMs: number;\n  readonly item: ServerNotification__ThreadItem;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemCompletedNotification = Schema.Struct({\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  item: ServerNotification__ThreadItem,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ItemStartedNotification = {\n  readonly item: ServerNotification__ThreadItem;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemStartedNotification = Schema.Struct({\n  item: ServerNotification__ThreadItem,\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: ServerNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<ServerNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: ServerNotification__TurnStatus;\n};\nexport const ServerNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([ServerNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(ServerNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: ServerNotification__TurnStatus,\n});\n\nexport type ServerRequest__FileSystemSandboxEntry = {\n  readonly access: ServerRequest__FileSystemAccessMode;\n  readonly path: ServerRequest__FileSystemPath;\n};\nexport const ServerRequest__FileSystemSandboxEntry = Schema.Struct({\n  access: ServerRequest__FileSystemAccessMode,\n  path: ServerRequest__FileSystemPath,\n});\n\nexport type ServerRequest__McpElicitationMultiSelectEnumSchema =\n  | ServerRequest__McpElicitationUntitledMultiSelectEnumSchema\n  | ServerRequest__McpElicitationTitledMultiSelectEnumSchema;\nexport const ServerRequest__McpElicitationMultiSelectEnumSchema = Schema.Union([\n  ServerRequest__McpElicitationUntitledMultiSelectEnumSchema,\n  ServerRequest__McpElicitationTitledMultiSelectEnumSchema,\n]);\n\nexport type V2ConfigReadResponse__Config = {\n  readonly analytics?: V2ConfigReadResponse__AnalyticsConfig | null;\n  readonly approval_policy?: V2ConfigReadResponse__AskForApproval | null;\n  readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;\n  readonly compact_prompt?: string | null;\n  readonly desktop?: { readonly [x: string]: unknown } | null;\n  readonly developer_instructions?: string | null;\n  readonly forced_chatgpt_workspace_id?: V2ConfigReadResponse__ForcedChatgptWorkspaceIds | null;\n  readonly forced_login_method?: V2ConfigReadResponse__ForcedLoginMethod | null;\n  readonly instructions?: string | null;\n  readonly model?: string | null;\n  readonly model_auto_compact_token_limit?: number | null;\n  readonly model_auto_compact_token_limit_scope?: V2ConfigReadResponse__AutoCompactTokenLimitScope | null;\n  readonly model_context_window?: number | null;\n  readonly model_provider?: string | null;\n  readonly model_reasoning_effort?: V2ConfigReadResponse__ReasoningEffort | null;\n  readonly model_reasoning_summary?: V2ConfigReadResponse__ReasoningSummary | null;\n  readonly model_verbosity?: V2ConfigReadResponse__Verbosity | null;\n  readonly review_model?: string | null;\n  readonly sandbox_mode?: V2ConfigReadResponse__SandboxMode | null;\n  readonly sandbox_workspace_write?: V2ConfigReadResponse__SandboxWorkspaceWrite | null;\n  readonly service_tier?: string | null;\n  readonly tools?: V2ConfigReadResponse__ToolsV2 | null;\n  readonly web_search?: V2ConfigReadResponse__WebSearchMode | null;\n  readonly [x: string]: unknown;\n};\nexport const V2ConfigReadResponse__Config = Schema.StructWithRest(\n  Schema.Struct({\n    analytics: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__AnalyticsConfig, Schema.Null]),\n    ),\n    approval_policy: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__AskForApproval, Schema.Null]),\n    ),\n    approvals_reviewer: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]).annotate({\n        description:\n          \"[UNSTABLE] Optional default for where approval requests are routed for review.\",\n      }),\n    ),\n    compact_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    desktop: Schema.optionalKey(\n      Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n    ),\n    developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    forced_chatgpt_workspace_id: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ForcedChatgptWorkspaceIds, Schema.Null]),\n    ),\n    forced_login_method: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ForcedLoginMethod, Schema.Null]),\n    ),\n    instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    model_auto_compact_token_limit: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n        Schema.Null,\n      ]),\n    ),\n    model_auto_compact_token_limit_scope: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__AutoCompactTokenLimitScope, Schema.Null]),\n    ),\n    model_context_window: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n        Schema.Null,\n      ]),\n    ),\n    model_provider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    model_reasoning_effort: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ReasoningEffort, Schema.Null]),\n    ),\n    model_reasoning_summary: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ReasoningSummary, Schema.Null]),\n    ),\n    model_verbosity: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__Verbosity, Schema.Null]),\n    ),\n    review_model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    sandbox_mode: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__SandboxMode, Schema.Null]),\n    ),\n    sandbox_workspace_write: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__SandboxWorkspaceWrite, Schema.Null]),\n    ),\n    service_tier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__ToolsV2, Schema.Null])),\n    web_search: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__WebSearchMode, Schema.Null]),\n    ),\n  }),\n  [Schema.Record(Schema.String, Schema.Unknown)],\n);\n\nexport type V2ConfigRequirementsReadResponse__ConfigRequirements = {\n  readonly allowAppshots?: boolean | null;\n  readonly allowManagedHooksOnly?: boolean | null;\n  readonly allowRemoteControl?: boolean | null;\n  readonly allowedApprovalPolicies?: ReadonlyArray<V2ConfigRequirementsReadResponse__AskForApproval> | null;\n  readonly allowedPermissionProfiles?: { readonly [x: string]: boolean } | null;\n  readonly allowedSandboxModes?: ReadonlyArray<V2ConfigRequirementsReadResponse__SandboxMode> | null;\n  readonly allowedWebSearchModes?: ReadonlyArray<V2ConfigRequirementsReadResponse__WebSearchMode> | null;\n  readonly allowedWindowsSandboxImplementations?: ReadonlyArray<V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode> | null;\n  readonly computerUse?: V2ConfigRequirementsReadResponse__ComputerUseRequirements | null;\n  readonly defaultPermissions?: string | null;\n  readonly enforceResidency?: V2ConfigRequirementsReadResponse__ResidencyRequirement | null;\n  readonly featureRequirements?: { readonly [x: string]: boolean } | null;\n  readonly models?: V2ConfigRequirementsReadResponse__ModelsRequirements | null;\n};\nexport const V2ConfigRequirementsReadResponse__ConfigRequirements = Schema.Struct({\n  allowAppshots: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowManagedHooksOnly: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowRemoteControl: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowedApprovalPolicies: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__AskForApproval), Schema.Null]),\n  ),\n  allowedPermissionProfiles: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Boolean), Schema.Null]),\n  ),\n  allowedSandboxModes: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__SandboxMode), Schema.Null]),\n  ),\n  allowedWebSearchModes: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__WebSearchMode), Schema.Null]),\n  ),\n  allowedWindowsSandboxImplementations: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode),\n      Schema.Null,\n    ]),\n  ),\n  computerUse: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ComputerUseRequirements, Schema.Null]),\n  ),\n  defaultPermissions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  enforceResidency: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ResidencyRequirement, Schema.Null]),\n  ),\n  featureRequirements: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Boolean), Schema.Null]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ModelsRequirements, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigWriteResponse__OverriddenMetadata = {\n  readonly effectiveValue: unknown;\n  readonly message: string;\n  readonly overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata;\n};\nexport const V2ConfigWriteResponse__OverriddenMetadata = Schema.Struct({\n  effectiveValue: Schema.Unknown,\n  message: Schema.String,\n  overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata,\n});\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry = {\n  readonly access: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode;\n  readonly path: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry =\n  Schema.Struct({\n    access: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode,\n    path: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath,\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry = {\n  readonly access: V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode;\n  readonly path: V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry =\n  Schema.Struct({\n    access: V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode,\n    path: V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath,\n  });\n\nexport type V2PluginInstalledResponse__PluginSummary = {\n  readonly authPolicy: V2PluginInstalledResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginInstalledResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginInstalledResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginInstalledResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginInstalledResponse__PluginShareContext | null;\n  readonly source: V2PluginInstalledResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginInstalledResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginInstalledResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginInstalledResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginInterface, Schema.Null]),\n  ),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginInstalledResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2PluginListResponse__PluginSummary = {\n  readonly authPolicy: V2PluginListResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginListResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginListResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginListResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginListResponse__PluginShareContext | null;\n  readonly source: V2PluginListResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginListResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginListResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginListResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2PluginListResponse__PluginInterface, Schema.Null])),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginListResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2PluginReadResponse__PluginSummary = {\n  readonly authPolicy: V2PluginReadResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginReadResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginReadResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginReadResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginReadResponse__PluginShareContext | null;\n  readonly source: V2PluginReadResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginReadResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginReadResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginReadResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__PluginInterface, Schema.Null])),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginReadResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2PluginShareListResponse__PluginSummary = {\n  readonly authPolicy: V2PluginShareListResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginShareListResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginShareListResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginShareListResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginShareListResponse__PluginShareContext | null;\n  readonly source: V2PluginShareListResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginShareListResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginShareListResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginShareListResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginInterface, Schema.Null]),\n  ),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginShareListResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2RawResponseItemCompletedNotification__ResponseItem =\n  | {\n      readonly content: ReadonlyArray<V2RawResponseItemCompletedNotification__ContentItem>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly phase?: V2RawResponseItemCompletedNotification__MessagePhase | null;\n      readonly role: string;\n      readonly type: \"message\";\n    }\n  | {\n      readonly author: string;\n      readonly content: ReadonlyArray<V2RawResponseItemCompletedNotification__AgentMessageInputContent>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly recipient: string;\n      readonly type: \"agent_message\";\n    }\n  | {\n      readonly content?: ReadonlyArray<V2RawResponseItemCompletedNotification__ReasoningItemContent> | null;\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly summary: ReadonlyArray<V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly action: V2RawResponseItemCompletedNotification__LocalShellAction;\n      readonly call_id?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status: V2RawResponseItemCompletedNotification__LocalShellStatus;\n      readonly type: \"local_shell_call\";\n    }\n  | {\n      readonly arguments: string;\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly type: \"function_call\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"tool_search_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody;\n      readonly type: \"function_call_output\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly input: string;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly status?: string | null;\n      readonly type: \"custom_tool_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly name?: string | null;\n      readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody;\n      readonly type: \"custom_tool_call_output\";\n    }\n  | {\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status: string;\n      readonly tools: ReadonlyArray<unknown>;\n      readonly type: \"tool_search_output\";\n    }\n  | {\n      readonly action?: V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"web_search_call\";\n    }\n  | {\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly result: string;\n      readonly revised_prompt?: string | null;\n      readonly status: string;\n      readonly type: \"image_generation_call\";\n    }\n  | {\n      readonly encrypted_content: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"compaction\";\n    }\n  | { readonly type: \"compaction_trigger\" }\n  | {\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"context_compaction\";\n    }\n  | { readonly type: \"other\" };\nexport const V2RawResponseItemCompletedNotification__ResponseItem = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.Array(V2RawResponseItemCompletedNotification__ContentItem),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2RawResponseItemCompletedNotification__MessagePhase, Schema.Null]),\n      ),\n      role: Schema.String,\n      type: Schema.Literal(\"message\").annotate({ title: \"MessageResponseItemType\" }),\n    }).annotate({ title: \"MessageResponseItem\" }),\n    Schema.Struct({\n      author: Schema.String,\n      content: Schema.Array(V2RawResponseItemCompletedNotification__AgentMessageInputContent),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      recipient: Schema.String,\n      type: Schema.Literal(\"agent_message\").annotate({ title: \"AgentMessageResponseItemType\" }),\n    }).annotate({ title: \"AgentMessageResponseItem\" }),\n    Schema.Struct({\n      content: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemContent),\n          Schema.Null,\n        ]),\n      ),\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      summary: Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningResponseItemType\" }),\n    }).annotate({ title: \"ReasoningResponseItem\" }),\n    Schema.Struct({\n      action: V2RawResponseItemCompletedNotification__LocalShellAction,\n      call_id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Set when using the Responses API.\" }),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Legacy id field retained for compatibility with older payloads.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: V2RawResponseItemCompletedNotification__LocalShellStatus,\n      type: Schema.Literal(\"local_shell_call\").annotate({\n        title: \"LocalShellCallResponseItemType\",\n      }),\n    }).annotate({ title: \"LocalShellCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.String,\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"function_call\").annotate({ title: \"FunctionCallResponseItemType\" }),\n    }).annotate({ title: \"FunctionCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"tool_search_call\").annotate({\n        title: \"ToolSearchCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody,\n      type: Schema.Literal(\"function_call_output\").annotate({\n        title: \"FunctionCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"FunctionCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      input: Schema.String,\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"custom_tool_call\").annotate({\n        title: \"CustomToolCallResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody,\n      type: Schema.Literal(\"custom_tool_call_output\").annotate({\n        title: \"CustomToolCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: Schema.String,\n      tools: Schema.Array(Schema.Unknown),\n      type: Schema.Literal(\"tool_search_output\").annotate({\n        title: \"ToolSearchOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchOutputResponseItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction,\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"web_search_call\").annotate({ title: \"WebSearchCallResponseItemType\" }),\n    }).annotate({ title: \"WebSearchCallResponseItem\" }),\n    Schema.Struct({\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      result: Schema.String,\n      revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.String,\n      type: Schema.Literal(\"image_generation_call\").annotate({\n        title: \"ImageGenerationCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ImageGenerationCallResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"compaction\").annotate({ title: \"CompactionResponseItemType\" }),\n    }).annotate({ title: \"CompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"compaction_trigger\").annotate({\n        title: \"CompactionTriggerResponseItemType\",\n      }),\n    }).annotate({ title: \"CompactionTriggerResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"context_compaction\").annotate({\n        title: \"ContextCompactionResponseItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponseItemType\" }),\n    }).annotate({ title: \"OtherResponseItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ReviewStartResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ReviewStartResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ReviewStartResponse__TurnStatus;\n};\nexport const V2ReviewStartResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ReviewStartResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ReviewStartResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ReviewStartResponse__TurnStatus,\n});\n\nexport type V2SkillsListResponse__SkillsListEntry = {\n  readonly cwd: string;\n  readonly errors: ReadonlyArray<V2SkillsListResponse__SkillErrorInfo>;\n  readonly skills: ReadonlyArray<V2SkillsListResponse__SkillMetadata>;\n};\nexport const V2SkillsListResponse__SkillsListEntry = Schema.Struct({\n  cwd: Schema.String,\n  errors: Schema.Array(V2SkillsListResponse__SkillErrorInfo),\n  skills: Schema.Array(V2SkillsListResponse__SkillMetadata),\n});\n\nexport type V2ThreadForkResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadForkResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadForkResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadForkResponse__TurnStatus;\n};\nexport const V2ThreadForkResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadForkResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadForkResponse__TurnStatus,\n});\n\nexport type V2ThreadListResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadListResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadListResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadListResponse__TurnStatus;\n};\nexport const V2ThreadListResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadListResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadListResponse__TurnStatus,\n});\n\nexport type V2ThreadMetadataUpdateResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadMetadataUpdateResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadMetadataUpdateResponse__TurnStatus;\n};\nexport const V2ThreadMetadataUpdateResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadMetadataUpdateResponse__TurnStatus,\n});\n\nexport type V2ThreadReadResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadReadResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadReadResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadReadResponse__TurnStatus;\n};\nexport const V2ThreadReadResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadReadResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadReadResponse__TurnStatus,\n});\n\nexport type V2ThreadResumeResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadResumeResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadResumeResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadResumeResponse__TurnStatus;\n};\nexport const V2ThreadResumeResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadResumeResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadResumeResponse__TurnStatus,\n});\n\nexport type V2ThreadRollbackResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadRollbackResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadRollbackResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadRollbackResponse__TurnStatus;\n};\nexport const V2ThreadRollbackResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadRollbackResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadRollbackResponse__TurnStatus,\n});\n\nexport type V2ThreadSettingsUpdatedNotification__ThreadSettings = {\n  readonly activePermissionProfile?: V2ThreadSettingsUpdatedNotification__ActivePermissionProfile | null;\n  readonly approvalPolicy: V2ThreadSettingsUpdatedNotification__AskForApproval;\n  readonly approvalsReviewer: V2ThreadSettingsUpdatedNotification__ApprovalsReviewer;\n  readonly collaborationMode: V2ThreadSettingsUpdatedNotification__CollaborationMode;\n  readonly cwd: V2ThreadSettingsUpdatedNotification__AbsolutePathBuf;\n  readonly effort?: V2ThreadSettingsUpdatedNotification__ReasoningEffort | null;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly personality?: V2ThreadSettingsUpdatedNotification__Personality | null;\n  readonly sandboxPolicy: V2ThreadSettingsUpdatedNotification__SandboxPolicy;\n  readonly serviceTier?: string | null;\n  readonly summary?: V2ThreadSettingsUpdatedNotification__ReasoningSummary | null;\n};\nexport const V2ThreadSettingsUpdatedNotification__ThreadSettings = Schema.Struct({\n  activePermissionProfile: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ActivePermissionProfile, Schema.Null]),\n  ),\n  approvalPolicy: V2ThreadSettingsUpdatedNotification__AskForApproval,\n  approvalsReviewer: V2ThreadSettingsUpdatedNotification__ApprovalsReviewer,\n  collaborationMode: V2ThreadSettingsUpdatedNotification__CollaborationMode,\n  cwd: V2ThreadSettingsUpdatedNotification__AbsolutePathBuf,\n  effort: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ReasoningEffort, Schema.Null]),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  personality: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__Personality, Schema.Null]),\n  ),\n  sandboxPolicy: V2ThreadSettingsUpdatedNotification__SandboxPolicy,\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  summary: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ReasoningSummary, Schema.Null]),\n  ),\n});\n\nexport type V2ThreadStartedNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadStartedNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadStartedNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadStartedNotification__TurnStatus;\n};\nexport const V2ThreadStartedNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadStartedNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadStartedNotification__TurnStatus,\n});\n\nexport type V2ThreadStartResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadStartResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadStartResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadStartResponse__TurnStatus;\n};\nexport const V2ThreadStartResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadStartResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadStartResponse__TurnStatus,\n});\n\nexport type V2ThreadUnarchiveResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadUnarchiveResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadUnarchiveResponse__TurnStatus;\n};\nexport const V2ThreadUnarchiveResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadUnarchiveResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadUnarchiveResponse__TurnStatus,\n});\n\nexport type V2TurnCompletedNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2TurnCompletedNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2TurnCompletedNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2TurnCompletedNotification__TurnStatus;\n};\nexport const V2TurnCompletedNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2TurnCompletedNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2TurnCompletedNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2TurnCompletedNotification__TurnStatus,\n});\n\nexport type V2TurnStartedNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2TurnStartedNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2TurnStartedNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2TurnStartedNotification__TurnStatus;\n};\nexport const V2TurnStartedNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2TurnStartedNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2TurnStartedNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2TurnStartedNotification__TurnStatus,\n});\n\nexport type V2TurnStartResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2TurnStartResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2TurnStartResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2TurnStartResponse__TurnStatus;\n};\nexport const V2TurnStartResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2TurnStartResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2TurnStartResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2TurnStartResponse__TurnStatus,\n});\n\nexport type CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<CommandExecutionRequestApprovalParams__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<CommandExecutionRequestApprovalParams__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<CommandExecutionRequestApprovalParams__LegacyAppPathString> | null;\n};\nexport const CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct(\n  {\n    entries: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(CommandExecutionRequestApprovalParams__FileSystemSandboxEntry),\n        Schema.Null,\n      ]),\n    ),\n    globScanMaxDepth: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(1)),\n        Schema.Null,\n      ]),\n    ),\n    read: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(CommandExecutionRequestApprovalParams__LegacyAppPathString).annotate({\n          description: \"This will be removed in favor of `entries`.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    write: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(CommandExecutionRequestApprovalParams__LegacyAppPathString).annotate({\n          description: \"This will be removed in favor of `entries`.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n  },\n);\n\nexport type McpServerElicitationRequestParams__McpElicitationEnumSchema =\n  | McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema;\nexport const McpServerElicitationRequestParams__McpElicitationEnumSchema = Schema.Union([\n  McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema,\n]);\n\nexport type PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<PermissionsRequestApprovalParams__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<PermissionsRequestApprovalParams__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<PermissionsRequestApprovalParams__LegacyAppPathString> | null;\n};\nexport const PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalParams__FileSystemSandboxEntry),\n      Schema.Null,\n    ]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalParams__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalParams__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<PermissionsRequestApprovalResponse__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<PermissionsRequestApprovalResponse__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<PermissionsRequestApprovalResponse__LegacyAppPathString> | null;\n};\nexport const PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalResponse__FileSystemSandboxEntry),\n      Schema.Null,\n    ]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalResponse__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalResponse__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<ServerNotification__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<ServerNotification__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<ServerNotification__LegacyAppPathString> | null;\n};\nexport const ServerNotification__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerNotification__FileSystemSandboxEntry), Schema.Null]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerNotification__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerNotification__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__ThreadSettingsUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadSettings: ServerNotification__ThreadSettings;\n};\nexport const ServerNotification__ThreadSettingsUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadSettings: ServerNotification__ThreadSettings,\n});\n\nexport type ServerNotification__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: ServerNotification__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: ServerNotification__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<ServerNotification__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: ServerNotification__ThreadSource | null;\n  readonly turns: ReadonlyArray<ServerNotification__Turn>;\n  readonly updatedAt: number;\n};\nexport const ServerNotification__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([ServerNotification__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([ServerNotification__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(ServerNotification__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type ServerNotification__TurnCompletedNotification = {\n  readonly threadId: string;\n  readonly turn: ServerNotification__Turn;\n};\nexport const ServerNotification__TurnCompletedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: ServerNotification__Turn,\n});\n\nexport type ServerNotification__TurnStartedNotification = {\n  readonly threadId: string;\n  readonly turn: ServerNotification__Turn;\n};\nexport const ServerNotification__TurnStartedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: ServerNotification__Turn,\n});\n\nexport type ServerRequest__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<ServerRequest__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<ServerRequest__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<ServerRequest__LegacyAppPathString> | null;\n};\nexport const ServerRequest__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerRequest__FileSystemSandboxEntry), Schema.Null]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerRequest__McpElicitationEnumSchema =\n  | ServerRequest__McpElicitationSingleSelectEnumSchema\n  | ServerRequest__McpElicitationMultiSelectEnumSchema\n  | ServerRequest__McpElicitationLegacyTitledEnumSchema;\nexport const ServerRequest__McpElicitationEnumSchema = Schema.Union([\n  ServerRequest__McpElicitationSingleSelectEnumSchema,\n  ServerRequest__McpElicitationMultiSelectEnumSchema,\n  ServerRequest__McpElicitationLegacyTitledEnumSchema,\n]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString> | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions =\n  Schema.Struct({\n    entries: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry),\n        Schema.Null,\n      ]),\n    ),\n    globScanMaxDepth: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(1)),\n        Schema.Null,\n      ]),\n    ),\n    read: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(\n          V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n        ).annotate({ description: \"This will be removed in favor of `entries`.\" }),\n        Schema.Null,\n      ]),\n    ),\n    write: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(\n          V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n        ).annotate({ description: \"This will be removed in favor of `entries`.\" }),\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString> | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions =\n  Schema.Struct({\n    entries: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry),\n        Schema.Null,\n      ]),\n    ),\n    globScanMaxDepth: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(1)),\n        Schema.Null,\n      ]),\n    ),\n    read: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString).annotate(\n          { description: \"This will be removed in favor of `entries`.\" },\n        ),\n        Schema.Null,\n      ]),\n    ),\n    write: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString).annotate(\n          { description: \"This will be removed in favor of `entries`.\" },\n        ),\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type V2PluginInstalledResponse__PluginMarketplaceEntry = {\n  readonly interface?: V2PluginInstalledResponse__MarketplaceInterface | null;\n  readonly name: string;\n  readonly path?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly plugins: ReadonlyArray<V2PluginInstalledResponse__PluginSummary>;\n};\nexport const V2PluginInstalledResponse__PluginMarketplaceEntry = Schema.Struct({\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__MarketplaceInterface, Schema.Null]),\n  ),\n  name: Schema.String,\n  path: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description:\n        \"Local marketplace file path when the marketplace is backed by a local file. Remote-only catalog marketplaces do not have a local path.\",\n    }),\n  ),\n  plugins: Schema.Array(V2PluginInstalledResponse__PluginSummary),\n});\n\nexport type V2PluginListResponse__PluginMarketplaceEntry = {\n  readonly interface?: V2PluginListResponse__MarketplaceInterface | null;\n  readonly name: string;\n  readonly path?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly plugins: ReadonlyArray<V2PluginListResponse__PluginSummary>;\n};\nexport const V2PluginListResponse__PluginMarketplaceEntry = Schema.Struct({\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__MarketplaceInterface, Schema.Null]),\n  ),\n  name: Schema.String,\n  path: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description:\n        \"Local marketplace file path when the marketplace is backed by a local file. Remote-only catalog marketplaces do not have a local path.\",\n    }),\n  ),\n  plugins: Schema.Array(V2PluginListResponse__PluginSummary),\n});\n\nexport type V2PluginReadResponse__PluginDetail = {\n  readonly appTemplates: ReadonlyArray<V2PluginReadResponse__AppTemplateSummary>;\n  readonly apps: ReadonlyArray<V2PluginReadResponse__AppSummary>;\n  readonly description?: string | null;\n  readonly hooks: ReadonlyArray<V2PluginReadResponse__PluginHookSummary>;\n  readonly marketplaceName: string;\n  readonly marketplacePath?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly mcpServers: ReadonlyArray<string>;\n  readonly scheduledTasks?: ReadonlyArray<V2PluginReadResponse__ScheduledTaskSummary> | null;\n  readonly shareUrl?: string | null;\n  readonly skills: ReadonlyArray<V2PluginReadResponse__SkillSummary>;\n  readonly summary: V2PluginReadResponse__PluginSummary;\n};\nexport const V2PluginReadResponse__PluginDetail = Schema.Struct({\n  appTemplates: Schema.Array(V2PluginReadResponse__AppTemplateSummary),\n  apps: Schema.Array(V2PluginReadResponse__AppSummary),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hooks: Schema.Array(V2PluginReadResponse__PluginHookSummary),\n  marketplaceName: Schema.String,\n  marketplacePath: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]),\n  ),\n  mcpServers: Schema.Array(Schema.String),\n  scheduledTasks: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginReadResponse__ScheduledTaskSummary), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  skills: Schema.Array(V2PluginReadResponse__SkillSummary),\n  summary: V2PluginReadResponse__PluginSummary,\n});\n\nexport type V2PluginShareListResponse__PluginShareListItem = {\n  readonly localPluginPath?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly plugin: V2PluginShareListResponse__PluginSummary;\n};\nexport const V2PluginShareListResponse__PluginShareListItem = Schema.Struct({\n  localPluginPath: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]),\n  ),\n  plugin: V2PluginShareListResponse__PluginSummary,\n});\n\nexport type V2ThreadForkResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadForkResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadForkResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadForkResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadForkResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadForkResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadForkResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadForkResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadListResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadListResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadListResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadListResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadListResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadListResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadListResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadListResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadMetadataUpdateResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadMetadataUpdateResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadMetadataUpdateResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadMetadataUpdateResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadMetadataUpdateResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadMetadataUpdateResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadReadResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadReadResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadReadResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadReadResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadReadResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadReadResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadReadResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadReadResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadResumeResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadResumeResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadResumeResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadResumeResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadResumeResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadResumeResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadResumeResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadStartedNotification__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadStartedNotification__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadStartedNotification__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadStartedNotification__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadStartedNotification__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadStartedNotification__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadStartedNotification__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadStartResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadStartResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadStartResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadStartResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadStartResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadStartResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadStartResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadStartResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadUnarchiveResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadUnarchiveResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadUnarchiveResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadUnarchiveResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadUnarchiveResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadUnarchiveResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationPrimitiveSchema =\n  | McpServerElicitationRequestParams__McpElicitationEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationStringSchema\n  | McpServerElicitationRequestParams__McpElicitationNumberSchema\n  | McpServerElicitationRequestParams__McpElicitationBooleanSchema;\nexport const McpServerElicitationRequestParams__McpElicitationPrimitiveSchema = Schema.Union([\n  McpServerElicitationRequestParams__McpElicitationEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationStringSchema,\n  McpServerElicitationRequestParams__McpElicitationNumberSchema,\n  McpServerElicitationRequestParams__McpElicitationBooleanSchema,\n]);\n\nexport type PermissionsRequestApprovalParams__RequestPermissionProfile = {\n  readonly fileSystem?: PermissionsRequestApprovalParams__AdditionalFileSystemPermissions | null;\n  readonly network?: PermissionsRequestApprovalParams__AdditionalNetworkPermissions | null;\n};\nexport const PermissionsRequestApprovalParams__RequestPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([PermissionsRequestApprovalParams__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([PermissionsRequestApprovalParams__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type PermissionsRequestApprovalResponse__GrantedPermissionProfile = {\n  readonly fileSystem?: PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions | null;\n  readonly network?: PermissionsRequestApprovalResponse__AdditionalNetworkPermissions | null;\n};\nexport const PermissionsRequestApprovalResponse__GrantedPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([\n      PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions,\n      Schema.Null,\n    ]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([PermissionsRequestApprovalResponse__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type ServerNotification__RequestPermissionProfile = {\n  readonly fileSystem?: ServerNotification__AdditionalFileSystemPermissions | null;\n  readonly network?: ServerNotification__AdditionalNetworkPermissions | null;\n};\nexport const ServerNotification__RequestPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([ServerNotification__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([ServerNotification__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type ServerNotification__ThreadStartedNotification = {\n  readonly thread: ServerNotification__Thread;\n};\nexport const ServerNotification__ThreadStartedNotification = Schema.Struct({\n  thread: ServerNotification__Thread,\n});\n\nexport type ServerRequest__RequestPermissionProfile = {\n  readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null;\n  readonly network?: ServerRequest__AdditionalNetworkPermissions | null;\n};\nexport const ServerRequest__RequestPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type ServerRequest__McpElicitationPrimitiveSchema =\n  | ServerRequest__McpElicitationEnumSchema\n  | ServerRequest__McpElicitationStringSchema\n  | ServerRequest__McpElicitationNumberSchema\n  | ServerRequest__McpElicitationBooleanSchema;\nexport const ServerRequest__McpElicitationPrimitiveSchema = Schema.Union([\n  ServerRequest__McpElicitationEnumSchema,\n  ServerRequest__McpElicitationStringSchema,\n  ServerRequest__McpElicitationNumberSchema,\n  ServerRequest__McpElicitationBooleanSchema,\n]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile = {\n  readonly fileSystem?: V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions | null;\n  readonly network?: V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile =\n  Schema.Struct({\n    fileSystem: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions,\n        Schema.Null,\n      ]),\n    ),\n    network: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions,\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile = {\n  readonly fileSystem?: V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions | null;\n  readonly network?: V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile =\n  Schema.Struct({\n    fileSystem: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions,\n        Schema.Null,\n      ]),\n    ),\n    network: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions,\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationSchema = {\n  readonly $schema?: string | null;\n  readonly properties: {\n    readonly [x: string]: McpServerElicitationRequestParams__McpElicitationPrimitiveSchema;\n  };\n  readonly required?: ReadonlyArray<string> | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationObjectType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationSchema = Schema.Struct({\n  $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  properties: Schema.Record(\n    Schema.String,\n    McpServerElicitationRequestParams__McpElicitationPrimitiveSchema,\n  ),\n  required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationObjectType,\n}).annotate({\n  description:\n    \"Typed form schema for MCP `elicitation/create` requests.\\n\\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.\",\n});\n\nexport type ServerNotification__GuardianApprovalReviewAction =\n  | {\n      readonly command: string;\n      readonly cwd: ServerNotification__AbsolutePathBuf;\n      readonly source: ServerNotification__GuardianCommandSource;\n      readonly type: \"command\";\n    }\n  | {\n      readonly argv: ReadonlyArray<string>;\n      readonly cwd: ServerNotification__AbsolutePathBuf;\n      readonly program: string;\n      readonly source: ServerNotification__GuardianCommandSource;\n      readonly type: \"execve\";\n    }\n  | {\n      readonly cwd: ServerNotification__AbsolutePathBuf;\n      readonly files: ReadonlyArray<ServerNotification__AbsolutePathBuf>;\n      readonly type: \"applyPatch\";\n    }\n  | {\n      readonly host: string;\n      readonly port: number;\n      readonly protocol: ServerNotification__NetworkApprovalProtocol;\n      readonly target: string;\n      readonly type: \"networkAccess\";\n    }\n  | {\n      readonly connectorId?: string | null;\n      readonly connectorName?: string | null;\n      readonly server: string;\n      readonly toolName: string;\n      readonly toolTitle?: string | null;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly permissions: ServerNotification__RequestPermissionProfile;\n      readonly reason?: string | null;\n      readonly type: \"requestPermissions\";\n    };\nexport const ServerNotification__GuardianApprovalReviewAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      cwd: ServerNotification__AbsolutePathBuf,\n      source: ServerNotification__GuardianCommandSource,\n      type: Schema.Literal(\"command\").annotate({\n        title: \"CommandGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"CommandGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      argv: Schema.Array(Schema.String),\n      cwd: ServerNotification__AbsolutePathBuf,\n      program: Schema.String,\n      source: ServerNotification__GuardianCommandSource,\n      type: Schema.Literal(\"execve\").annotate({ title: \"ExecveGuardianApprovalReviewActionType\" }),\n    }).annotate({ title: \"ExecveGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      cwd: ServerNotification__AbsolutePathBuf,\n      files: Schema.Array(ServerNotification__AbsolutePathBuf),\n      type: Schema.Literal(\"applyPatch\").annotate({\n        title: \"ApplyPatchGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"ApplyPatchGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      host: Schema.String,\n      port: Schema.Number.annotate({ format: \"uint16\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      protocol: ServerNotification__NetworkApprovalProtocol,\n      target: Schema.String,\n      type: Schema.Literal(\"networkAccess\").annotate({\n        title: \"NetworkAccessGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"NetworkAccessGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      server: Schema.String,\n      toolName: Schema.String,\n      toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"mcpToolCall\").annotate({\n        title: \"McpToolCallGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"McpToolCallGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      permissions: ServerNotification__RequestPermissionProfile,\n      reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"requestPermissions\").annotate({\n        title: \"RequestPermissionsGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"RequestPermissionsGuardianApprovalReviewAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__PermissionsRequestApprovalParams = {\n  readonly cwd: ServerRequest__AbsolutePathBuf;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly permissions: ServerRequest__RequestPermissionProfile;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__PermissionsRequestApprovalParams = Schema.Struct({\n  cwd: ServerRequest__AbsolutePathBuf,\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  itemId: Schema.String,\n  permissions: ServerRequest__RequestPermissionProfile,\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__McpElicitationSchema = {\n  readonly $schema?: string | null;\n  readonly properties: { readonly [x: string]: ServerRequest__McpElicitationPrimitiveSchema };\n  readonly required?: ReadonlyArray<string> | null;\n  readonly type: ServerRequest__McpElicitationObjectType;\n};\nexport const ServerRequest__McpElicitationSchema = Schema.Struct({\n  $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  properties: Schema.Record(Schema.String, ServerRequest__McpElicitationPrimitiveSchema),\n  required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  type: ServerRequest__McpElicitationObjectType,\n}).annotate({\n  description:\n    \"Typed form schema for MCP `elicitation/create` requests.\\n\\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.\",\n});\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction =\n  | {\n      readonly command: string;\n      readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf;\n      readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource;\n      readonly type: \"command\";\n    }\n  | {\n      readonly argv: ReadonlyArray<string>;\n      readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf;\n      readonly program: string;\n      readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource;\n      readonly type: \"execve\";\n    }\n  | {\n      readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf;\n      readonly files: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf>;\n      readonly type: \"applyPatch\";\n    }\n  | {\n      readonly host: string;\n      readonly port: number;\n      readonly protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol;\n      readonly target: string;\n      readonly type: \"networkAccess\";\n    }\n  | {\n      readonly connectorId?: string | null;\n      readonly connectorName?: string | null;\n      readonly server: string;\n      readonly toolName: string;\n      readonly toolTitle?: string | null;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly permissions: V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile;\n      readonly reason?: string | null;\n      readonly type: \"requestPermissions\";\n    };\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction =\n  Schema.Union(\n    [\n      Schema.Struct({\n        command: Schema.String,\n        cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf,\n        source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"command\").annotate({\n          title: \"CommandGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"CommandGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        argv: Schema.Array(Schema.String),\n        cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf,\n        program: Schema.String,\n        source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"execve\").annotate({\n          title: \"ExecveGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ExecveGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf,\n        files: Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf),\n        type: Schema.Literal(\"applyPatch\").annotate({\n          title: \"ApplyPatchGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ApplyPatchGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        host: Schema.String,\n        port: Schema.Number.annotate({ format: \"uint16\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol,\n        target: Schema.String,\n        type: Schema.Literal(\"networkAccess\").annotate({\n          title: \"NetworkAccessGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"NetworkAccessGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        server: Schema.String,\n        toolName: Schema.String,\n        toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"mcpToolCall\").annotate({\n          title: \"McpToolCallGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"McpToolCallGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        permissions: V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile,\n        reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"requestPermissions\").annotate({\n          title: \"RequestPermissionsGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"RequestPermissionsGuardianApprovalReviewAction\" }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction =\n  | {\n      readonly command: string;\n      readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf;\n      readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource;\n      readonly type: \"command\";\n    }\n  | {\n      readonly argv: ReadonlyArray<string>;\n      readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf;\n      readonly program: string;\n      readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource;\n      readonly type: \"execve\";\n    }\n  | {\n      readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf;\n      readonly files: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf>;\n      readonly type: \"applyPatch\";\n    }\n  | {\n      readonly host: string;\n      readonly port: number;\n      readonly protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol;\n      readonly target: string;\n      readonly type: \"networkAccess\";\n    }\n  | {\n      readonly connectorId?: string | null;\n      readonly connectorName?: string | null;\n      readonly server: string;\n      readonly toolName: string;\n      readonly toolTitle?: string | null;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly permissions: V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile;\n      readonly reason?: string | null;\n      readonly type: \"requestPermissions\";\n    };\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction =\n  Schema.Union(\n    [\n      Schema.Struct({\n        command: Schema.String,\n        cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf,\n        source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"command\").annotate({\n          title: \"CommandGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"CommandGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        argv: Schema.Array(Schema.String),\n        cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf,\n        program: Schema.String,\n        source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"execve\").annotate({\n          title: \"ExecveGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ExecveGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf,\n        files: Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf),\n        type: Schema.Literal(\"applyPatch\").annotate({\n          title: \"ApplyPatchGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ApplyPatchGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        host: Schema.String,\n        port: Schema.Number.annotate({ format: \"uint16\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol,\n        target: Schema.String,\n        type: Schema.Literal(\"networkAccess\").annotate({\n          title: \"NetworkAccessGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"NetworkAccessGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        server: Schema.String,\n        toolName: Schema.String,\n        toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"mcpToolCall\").annotate({\n          title: \"McpToolCallGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"McpToolCallGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        permissions: V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile,\n        reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"requestPermissions\").annotate({\n          title: \"RequestPermissionsGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"RequestPermissionsGuardianApprovalReviewAction\" }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type ServerNotification__ItemGuardianApprovalReviewCompletedNotification = {\n  readonly action: ServerNotification__GuardianApprovalReviewAction;\n  readonly completedAtMs: number;\n  readonly decisionSource: ServerNotification__AutoReviewDecisionSource;\n  readonly review: ServerNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({\n  action: ServerNotification__GuardianApprovalReviewAction,\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  decisionSource: ServerNotification__AutoReviewDecisionSource,\n  review: ServerNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type ServerNotification__ItemGuardianApprovalReviewStartedNotification = {\n  readonly action: ServerNotification__GuardianApprovalReviewAction;\n  readonly review: ServerNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemGuardianApprovalReviewStartedNotification = Schema.Struct({\n  action: ServerNotification__GuardianApprovalReviewAction,\n  review: ServerNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type ServerRequest__McpServerElicitationRequestParams =\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"form\";\n      readonly requestedSchema: ServerRequest__McpElicitationSchema;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"openai/form\";\n      readonly requestedSchema: unknown;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly elicitationId: string;\n      readonly message: string;\n      readonly mode: \"url\";\n      readonly url: string;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    };\nexport const ServerRequest__McpServerElicitationRequestParams = Schema.Union(\n  [\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"form\"),\n      requestedSchema: ServerRequest__McpElicitationSchema,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"openai/form\"),\n      requestedSchema: Schema.Unknown,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      elicitationId: Schema.String,\n      message: Schema.String,\n      mode: Schema.Literal(\"url\"),\n      url: Schema.String,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ApplyPatchApprovalParams = {\n  readonly callId: string;\n  readonly conversationId: ApplyPatchApprovalParams__ThreadId;\n  readonly fileChanges: { readonly [x: string]: ApplyPatchApprovalParams__FileChange };\n  readonly grantRoot?: string | null;\n  readonly reason?: string | null;\n};\nexport const ApplyPatchApprovalParams = Schema.Struct({\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].\",\n  }),\n  conversationId: ApplyPatchApprovalParams__ThreadId,\n  fileChanges: Schema.Record(Schema.String, ApplyPatchApprovalParams__FileChange),\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ApplyPatchApprovalParams\" });\n\nexport type ApplyPatchApprovalResponse = {\n  readonly decision: ApplyPatchApprovalResponse__ReviewDecision;\n};\nexport const ApplyPatchApprovalResponse = Schema.Struct({\n  decision: ApplyPatchApprovalResponse__ReviewDecision,\n}).annotate({ title: \"ApplyPatchApprovalResponse\" });\n\nexport type AttestationGenerateParams = {};\nexport const AttestationGenerateParams = Schema.Struct({}).annotate({\n  title: \"AttestationGenerateParams\",\n});\n\nexport type AttestationGenerateResponse = { readonly token: string };\nexport const AttestationGenerateResponse = Schema.Struct({\n  token: Schema.String.annotate({ description: \"Opaque client attestation token.\" }),\n}).annotate({ title: \"AttestationGenerateResponse\" });\n\nexport type ChatgptAuthTokensRefreshParams = {\n  readonly previousAccountId?: string | null;\n  readonly reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason;\n};\nexport const ChatgptAuthTokensRefreshParams = Schema.Struct({\n  previousAccountId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Workspace/account identifier that Codex was previously using.\\n\\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\\n\\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason,\n}).annotate({ title: \"ChatgptAuthTokensRefreshParams\" });\n\nexport type ChatgptAuthTokensRefreshResponse = {\n  readonly accessToken: string;\n  readonly chatgptAccountId: string;\n  readonly chatgptPlanType?: string | null;\n};\nexport const ChatgptAuthTokensRefreshResponse = Schema.Struct({\n  accessToken: Schema.String,\n  chatgptAccountId: Schema.String,\n  chatgptPlanType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ChatgptAuthTokensRefreshResponse\" });\n\nexport type ClientNotification = { readonly method: \"initialized\" };\nexport const ClientNotification = Schema.Union(\n  [\n    Schema.Struct({\n      method: Schema.Literal(\"initialized\").annotate({ title: \"InitializedNotificationMethod\" }),\n    }).annotate({ title: \"InitializedNotification\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"ClientNotification\" });\n\nexport type ClientRequest =\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"initialize\";\n      readonly params: ClientRequest__InitializeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/start\";\n      readonly params: ClientRequest__ThreadStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/resume\";\n      readonly params: ClientRequest__ThreadResumeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/fork\";\n      readonly params: ClientRequest__ThreadForkParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/archive\";\n      readonly params: ClientRequest__ThreadArchiveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/delete\";\n      readonly params: ClientRequest__ThreadDeleteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/unsubscribe\";\n      readonly params: ClientRequest__ThreadUnsubscribeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/name/set\";\n      readonly params: ClientRequest__ThreadSetNameParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/goal/set\";\n      readonly params: ClientRequest__ThreadGoalSetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/goal/get\";\n      readonly params: ClientRequest__ThreadGoalGetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/goal/clear\";\n      readonly params: ClientRequest__ThreadGoalClearParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/metadata/update\";\n      readonly params: ClientRequest__ThreadMetadataUpdateParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/unarchive\";\n      readonly params: ClientRequest__ThreadUnarchiveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/compact/start\";\n      readonly params: ClientRequest__ThreadCompactStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/shellCommand\";\n      readonly params: ClientRequest__ThreadShellCommandParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/approveGuardianDeniedAction\";\n      readonly params: ClientRequest__ThreadApproveGuardianDeniedActionParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/rollback\";\n      readonly params: ClientRequest__ThreadRollbackParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/list\";\n      readonly params: ClientRequest__ThreadListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/loaded/list\";\n      readonly params: ClientRequest__ThreadLoadedListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/read\";\n      readonly params: ClientRequest__ThreadReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/inject_items\";\n      readonly params: ClientRequest__ThreadInjectItemsParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"skills/list\";\n      readonly params: ClientRequest__SkillsListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"skills/extraRoots/set\";\n      readonly params: ClientRequest__SkillsExtraRootsSetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"hooks/list\";\n      readonly params: ClientRequest__HooksListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"marketplace/add\";\n      readonly params: ClientRequest__MarketplaceAddParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"marketplace/remove\";\n      readonly params: ClientRequest__MarketplaceRemoveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"marketplace/upgrade\";\n      readonly params: ClientRequest__MarketplaceUpgradeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/list\";\n      readonly params: ClientRequest__PluginListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/installed\";\n      readonly params: ClientRequest__PluginInstalledParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/read\";\n      readonly params: ClientRequest__PluginReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/skill/read\";\n      readonly params: ClientRequest__PluginSkillReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/save\";\n      readonly params: ClientRequest__PluginShareSaveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/updateTargets\";\n      readonly params: ClientRequest__PluginShareUpdateTargetsParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/list\";\n      readonly params: ClientRequest__PluginShareListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/checkout\";\n      readonly params: ClientRequest__PluginShareCheckoutParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/delete\";\n      readonly params: ClientRequest__PluginShareDeleteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"app/read\";\n      readonly params: ClientRequest__AppsReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"app/list\";\n      readonly params: ClientRequest__AppsListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"app/installed\";\n      readonly params: ClientRequest__AppsInstalledParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/readFile\";\n      readonly params: ClientRequest__FsReadFileParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/writeFile\";\n      readonly params: ClientRequest__FsWriteFileParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/createDirectory\";\n      readonly params: ClientRequest__FsCreateDirectoryParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/getMetadata\";\n      readonly params: ClientRequest__FsGetMetadataParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/readDirectory\";\n      readonly params: ClientRequest__FsReadDirectoryParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/remove\";\n      readonly params: ClientRequest__FsRemoveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/copy\";\n      readonly params: ClientRequest__FsCopyParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/watch\";\n      readonly params: ClientRequest__FsWatchParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/unwatch\";\n      readonly params: ClientRequest__FsUnwatchParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"skills/config/write\";\n      readonly params: ClientRequest__SkillsConfigWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/install\";\n      readonly params: ClientRequest__PluginInstallParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/uninstall\";\n      readonly params: ClientRequest__PluginUninstallParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"turn/start\";\n      readonly params: ClientRequest__TurnStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"turn/steer\";\n      readonly params: ClientRequest__TurnSteerParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"turn/interrupt\";\n      readonly params: ClientRequest__TurnInterruptParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"review/start\";\n      readonly params: ClientRequest__ReviewStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"model/list\";\n      readonly params: ClientRequest__ModelListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"modelProvider/capabilities/read\";\n      readonly params: ClientRequest__ModelProviderCapabilitiesReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"experimentalFeature/list\";\n      readonly params: ClientRequest__ExperimentalFeatureListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"permissionProfile/list\";\n      readonly params: ClientRequest__PermissionProfileListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"experimentalFeature/enablement/set\";\n      readonly params: ClientRequest__ExperimentalFeatureEnablementSetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServer/oauth/login\";\n      readonly params: ClientRequest__McpServerOauthLoginParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/mcpServer/reload\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServerStatus/list\";\n      readonly params: ClientRequest__ListMcpServerStatusParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServer/resource/read\";\n      readonly params: ClientRequest__McpResourceReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServer/tool/call\";\n      readonly params: ClientRequest__McpServerToolCallParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"windowsSandbox/setupStart\";\n      readonly params: ClientRequest__WindowsSandboxSetupStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"windowsSandbox/readiness\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/login/start\";\n      readonly params: ClientRequest__LoginAccountParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/login/cancel\";\n      readonly params: ClientRequest__CancelLoginAccountParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/logout\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/rateLimits/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/rateLimitResetCredit/consume\";\n      readonly params: ClientRequest__ConsumeAccountRateLimitResetCreditParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/usage/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/workspaceMessages/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/sendAddCreditsNudgeEmail\";\n      readonly params: ClientRequest__SendAddCreditsNudgeEmailParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"feedback/upload\";\n      readonly params: ClientRequest__FeedbackUploadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec\";\n      readonly params: ClientRequest__CommandExecParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec/write\";\n      readonly params: ClientRequest__CommandExecWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec/terminate\";\n      readonly params: ClientRequest__CommandExecTerminateParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec/resize\";\n      readonly params: ClientRequest__CommandExecResizeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/read\";\n      readonly params: ClientRequest__ConfigReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"externalAgentConfig/detect\";\n      readonly params: ClientRequest__ExternalAgentConfigDetectParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"externalAgentConfig/import\";\n      readonly params: ClientRequest__ExternalAgentConfigImportParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"externalAgentConfig/import/readHistories\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/value/write\";\n      readonly params: ClientRequest__ConfigValueWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/batchWrite\";\n      readonly params: ClientRequest__ConfigBatchWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"configRequirements/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/read\";\n      readonly params: ClientRequest__GetAccountParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fuzzyFileSearch\";\n      readonly params: ClientRequest__FuzzyFileSearchParams;\n    };\nexport const ClientRequest = Schema.Union(\n  [\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"initialize\").annotate({ title: \"InitializeRequestMethod\" }),\n      params: ClientRequest__InitializeParams,\n    }).annotate({ title: \"InitializeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/start\").annotate({ title: \"Thread/startRequestMethod\" }),\n      params: ClientRequest__ThreadStartParams,\n    }).annotate({ title: \"Thread/startRequest\", description: \"NEW APIs\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/resume\").annotate({ title: \"Thread/resumeRequestMethod\" }),\n      params: ClientRequest__ThreadResumeParams,\n    }).annotate({ title: \"Thread/resumeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/fork\").annotate({ title: \"Thread/forkRequestMethod\" }),\n      params: ClientRequest__ThreadForkParams,\n    }).annotate({ title: \"Thread/forkRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/archive\").annotate({ title: \"Thread/archiveRequestMethod\" }),\n      params: ClientRequest__ThreadArchiveParams,\n    }).annotate({ title: \"Thread/archiveRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/delete\").annotate({ title: \"Thread/deleteRequestMethod\" }),\n      params: ClientRequest__ThreadDeleteParams,\n    }).annotate({ title: \"Thread/deleteRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/unsubscribe\").annotate({\n        title: \"Thread/unsubscribeRequestMethod\",\n      }),\n      params: ClientRequest__ThreadUnsubscribeParams,\n    }).annotate({ title: \"Thread/unsubscribeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/name/set\").annotate({ title: \"Thread/name/setRequestMethod\" }),\n      params: ClientRequest__ThreadSetNameParams,\n    }).annotate({ title: \"Thread/name/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/goal/set\").annotate({ title: \"Thread/goal/setRequestMethod\" }),\n      params: ClientRequest__ThreadGoalSetParams,\n    }).annotate({ title: \"Thread/goal/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/goal/get\").annotate({ title: \"Thread/goal/getRequestMethod\" }),\n      params: ClientRequest__ThreadGoalGetParams,\n    }).annotate({ title: \"Thread/goal/getRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/goal/clear\").annotate({\n        title: \"Thread/goal/clearRequestMethod\",\n      }),\n      params: ClientRequest__ThreadGoalClearParams,\n    }).annotate({ title: \"Thread/goal/clearRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/metadata/update\").annotate({\n        title: \"Thread/metadata/updateRequestMethod\",\n      }),\n      params: ClientRequest__ThreadMetadataUpdateParams,\n    }).annotate({ title: \"Thread/metadata/updateRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/unarchive\").annotate({\n        title: \"Thread/unarchiveRequestMethod\",\n      }),\n      params: ClientRequest__ThreadUnarchiveParams,\n    }).annotate({ title: \"Thread/unarchiveRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/compact/start\").annotate({\n        title: \"Thread/compact/startRequestMethod\",\n      }),\n      params: ClientRequest__ThreadCompactStartParams,\n    }).annotate({ title: \"Thread/compact/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/shellCommand\").annotate({\n        title: \"Thread/shellCommandRequestMethod\",\n      }),\n      params: ClientRequest__ThreadShellCommandParams,\n    }).annotate({ title: \"Thread/shellCommandRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/approveGuardianDeniedAction\").annotate({\n        title: \"Thread/approveGuardianDeniedActionRequestMethod\",\n      }),\n      params: ClientRequest__ThreadApproveGuardianDeniedActionParams,\n    }).annotate({ title: \"Thread/approveGuardianDeniedActionRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/rollback\").annotate({ title: \"Thread/rollbackRequestMethod\" }),\n      params: ClientRequest__ThreadRollbackParams,\n    }).annotate({ title: \"Thread/rollbackRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/list\").annotate({ title: \"Thread/listRequestMethod\" }),\n      params: ClientRequest__ThreadListParams,\n    }).annotate({ title: \"Thread/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/loaded/list\").annotate({\n        title: \"Thread/loaded/listRequestMethod\",\n      }),\n      params: ClientRequest__ThreadLoadedListParams,\n    }).annotate({ title: \"Thread/loaded/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/read\").annotate({ title: \"Thread/readRequestMethod\" }),\n      params: ClientRequest__ThreadReadParams,\n    }).annotate({ title: \"Thread/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/inject_items\").annotate({\n        title: \"Thread/injectItemsRequestMethod\",\n      }),\n      params: ClientRequest__ThreadInjectItemsParams,\n    }).annotate({\n      title: \"Thread/injectItemsRequest\",\n      description:\n        \"Append raw Responses API items to the thread history without starting a user turn.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"skills/list\").annotate({ title: \"Skills/listRequestMethod\" }),\n      params: ClientRequest__SkillsListParams,\n    }).annotate({ title: \"Skills/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"skills/extraRoots/set\").annotate({\n        title: \"Skills/extraRoots/setRequestMethod\",\n      }),\n      params: ClientRequest__SkillsExtraRootsSetParams,\n    }).annotate({ title: \"Skills/extraRoots/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"hooks/list\").annotate({ title: \"Hooks/listRequestMethod\" }),\n      params: ClientRequest__HooksListParams,\n    }).annotate({ title: \"Hooks/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"marketplace/add\").annotate({ title: \"Marketplace/addRequestMethod\" }),\n      params: ClientRequest__MarketplaceAddParams,\n    }).annotate({ title: \"Marketplace/addRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"marketplace/remove\").annotate({\n        title: \"Marketplace/removeRequestMethod\",\n      }),\n      params: ClientRequest__MarketplaceRemoveParams,\n    }).annotate({ title: \"Marketplace/removeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"marketplace/upgrade\").annotate({\n        title: \"Marketplace/upgradeRequestMethod\",\n      }),\n      params: ClientRequest__MarketplaceUpgradeParams,\n    }).annotate({ title: \"Marketplace/upgradeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/list\").annotate({ title: \"Plugin/listRequestMethod\" }),\n      params: ClientRequest__PluginListParams,\n    }).annotate({ title: \"Plugin/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/installed\").annotate({\n        title: \"Plugin/installedRequestMethod\",\n      }),\n      params: ClientRequest__PluginInstalledParams,\n    }).annotate({ title: \"Plugin/installedRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/read\").annotate({ title: \"Plugin/readRequestMethod\" }),\n      params: ClientRequest__PluginReadParams,\n    }).annotate({ title: \"Plugin/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/skill/read\").annotate({\n        title: \"Plugin/skill/readRequestMethod\",\n      }),\n      params: ClientRequest__PluginSkillReadParams,\n    }).annotate({ title: \"Plugin/skill/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/save\").annotate({\n        title: \"Plugin/share/saveRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareSaveParams,\n    }).annotate({ title: \"Plugin/share/saveRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/updateTargets\").annotate({\n        title: \"Plugin/share/updateTargetsRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareUpdateTargetsParams,\n    }).annotate({ title: \"Plugin/share/updateTargetsRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/list\").annotate({\n        title: \"Plugin/share/listRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareListParams,\n    }).annotate({ title: \"Plugin/share/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/checkout\").annotate({\n        title: \"Plugin/share/checkoutRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareCheckoutParams,\n    }).annotate({ title: \"Plugin/share/checkoutRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/delete\").annotate({\n        title: \"Plugin/share/deleteRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareDeleteParams,\n    }).annotate({ title: \"Plugin/share/deleteRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"app/read\").annotate({ title: \"App/readRequestMethod\" }),\n      params: ClientRequest__AppsReadParams,\n    }).annotate({ title: \"App/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"app/list\").annotate({ title: \"App/listRequestMethod\" }),\n      params: ClientRequest__AppsListParams,\n    }).annotate({ title: \"App/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"app/installed\").annotate({ title: \"App/installedRequestMethod\" }),\n      params: ClientRequest__AppsInstalledParams,\n    }).annotate({ title: \"App/installedRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/readFile\").annotate({ title: \"Fs/readFileRequestMethod\" }),\n      params: ClientRequest__FsReadFileParams,\n    }).annotate({ title: \"Fs/readFileRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/writeFile\").annotate({ title: \"Fs/writeFileRequestMethod\" }),\n      params: ClientRequest__FsWriteFileParams,\n    }).annotate({ title: \"Fs/writeFileRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/createDirectory\").annotate({\n        title: \"Fs/createDirectoryRequestMethod\",\n      }),\n      params: ClientRequest__FsCreateDirectoryParams,\n    }).annotate({ title: \"Fs/createDirectoryRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/getMetadata\").annotate({ title: \"Fs/getMetadataRequestMethod\" }),\n      params: ClientRequest__FsGetMetadataParams,\n    }).annotate({ title: \"Fs/getMetadataRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/readDirectory\").annotate({\n        title: \"Fs/readDirectoryRequestMethod\",\n      }),\n      params: ClientRequest__FsReadDirectoryParams,\n    }).annotate({ title: \"Fs/readDirectoryRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/remove\").annotate({ title: \"Fs/removeRequestMethod\" }),\n      params: ClientRequest__FsRemoveParams,\n    }).annotate({ title: \"Fs/removeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/copy\").annotate({ title: \"Fs/copyRequestMethod\" }),\n      params: ClientRequest__FsCopyParams,\n    }).annotate({ title: \"Fs/copyRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/watch\").annotate({ title: \"Fs/watchRequestMethod\" }),\n      params: ClientRequest__FsWatchParams,\n    }).annotate({ title: \"Fs/watchRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/unwatch\").annotate({ title: \"Fs/unwatchRequestMethod\" }),\n      params: ClientRequest__FsUnwatchParams,\n    }).annotate({ title: \"Fs/unwatchRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"skills/config/write\").annotate({\n        title: \"Skills/config/writeRequestMethod\",\n      }),\n      params: ClientRequest__SkillsConfigWriteParams,\n    }).annotate({ title: \"Skills/config/writeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/install\").annotate({ title: \"Plugin/installRequestMethod\" }),\n      params: ClientRequest__PluginInstallParams,\n    }).annotate({ title: \"Plugin/installRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/uninstall\").annotate({\n        title: \"Plugin/uninstallRequestMethod\",\n      }),\n      params: ClientRequest__PluginUninstallParams,\n    }).annotate({ title: \"Plugin/uninstallRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"turn/start\").annotate({ title: \"Turn/startRequestMethod\" }),\n      params: ClientRequest__TurnStartParams,\n    }).annotate({ title: \"Turn/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"turn/steer\").annotate({ title: \"Turn/steerRequestMethod\" }),\n      params: ClientRequest__TurnSteerParams,\n    }).annotate({ title: \"Turn/steerRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"turn/interrupt\").annotate({ title: \"Turn/interruptRequestMethod\" }),\n      params: ClientRequest__TurnInterruptParams,\n    }).annotate({ title: \"Turn/interruptRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"review/start\").annotate({ title: \"Review/startRequestMethod\" }),\n      params: ClientRequest__ReviewStartParams,\n    }).annotate({ title: \"Review/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"model/list\").annotate({ title: \"Model/listRequestMethod\" }),\n      params: ClientRequest__ModelListParams,\n    }).annotate({ title: \"Model/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"modelProvider/capabilities/read\").annotate({\n        title: \"ModelProvider/capabilities/readRequestMethod\",\n      }),\n      params: ClientRequest__ModelProviderCapabilitiesReadParams,\n    }).annotate({ title: \"ModelProvider/capabilities/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"experimentalFeature/list\").annotate({\n        title: \"ExperimentalFeature/listRequestMethod\",\n      }),\n      params: ClientRequest__ExperimentalFeatureListParams,\n    }).annotate({ title: \"ExperimentalFeature/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"permissionProfile/list\").annotate({\n        title: \"PermissionProfile/listRequestMethod\",\n      }),\n      params: ClientRequest__PermissionProfileListParams,\n    }).annotate({ title: \"PermissionProfile/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"experimentalFeature/enablement/set\").annotate({\n        title: \"ExperimentalFeature/enablement/setRequestMethod\",\n      }),\n      params: ClientRequest__ExperimentalFeatureEnablementSetParams,\n    }).annotate({ title: \"ExperimentalFeature/enablement/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/oauth/login\").annotate({\n        title: \"McpServer/oauth/loginRequestMethod\",\n      }),\n      params: ClientRequest__McpServerOauthLoginParams,\n    }).annotate({ title: \"McpServer/oauth/loginRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/mcpServer/reload\").annotate({\n        title: \"Config/mcpServer/reloadRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Config/mcpServer/reloadRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServerStatus/list\").annotate({\n        title: \"McpServerStatus/listRequestMethod\",\n      }),\n      params: ClientRequest__ListMcpServerStatusParams,\n    }).annotate({ title: \"McpServerStatus/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/resource/read\").annotate({\n        title: \"McpServer/resource/readRequestMethod\",\n      }),\n      params: ClientRequest__McpResourceReadParams,\n    }).annotate({ title: \"McpServer/resource/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/tool/call\").annotate({\n        title: \"McpServer/tool/callRequestMethod\",\n      }),\n      params: ClientRequest__McpServerToolCallParams,\n    }).annotate({ title: \"McpServer/tool/callRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"windowsSandbox/setupStart\").annotate({\n        title: \"WindowsSandbox/setupStartRequestMethod\",\n      }),\n      params: ClientRequest__WindowsSandboxSetupStartParams,\n    }).annotate({ title: \"WindowsSandbox/setupStartRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"windowsSandbox/readiness\").annotate({\n        title: \"WindowsSandbox/readinessRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"WindowsSandbox/readinessRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/login/start\").annotate({\n        title: \"Account/login/startRequestMethod\",\n      }),\n      params: ClientRequest__LoginAccountParams,\n    }).annotate({ title: \"Account/login/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/login/cancel\").annotate({\n        title: \"Account/login/cancelRequestMethod\",\n      }),\n      params: ClientRequest__CancelLoginAccountParams,\n    }).annotate({ title: \"Account/login/cancelRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/logout\").annotate({ title: \"Account/logoutRequestMethod\" }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/logoutRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/rateLimits/read\").annotate({\n        title: \"Account/rateLimits/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/rateLimits/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/rateLimitResetCredit/consume\").annotate({\n        title: \"Account/rateLimitResetCredit/consumeRequestMethod\",\n      }),\n      params: ClientRequest__ConsumeAccountRateLimitResetCreditParams,\n    }).annotate({ title: \"Account/rateLimitResetCredit/consumeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/usage/read\").annotate({\n        title: \"Account/usage/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/usage/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/workspaceMessages/read\").annotate({\n        title: \"Account/workspaceMessages/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/workspaceMessages/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/sendAddCreditsNudgeEmail\").annotate({\n        title: \"Account/sendAddCreditsNudgeEmailRequestMethod\",\n      }),\n      params: ClientRequest__SendAddCreditsNudgeEmailParams,\n    }).annotate({ title: \"Account/sendAddCreditsNudgeEmailRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"feedback/upload\").annotate({ title: \"Feedback/uploadRequestMethod\" }),\n      params: ClientRequest__FeedbackUploadParams,\n    }).annotate({ title: \"Feedback/uploadRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec\").annotate({ title: \"Command/execRequestMethod\" }),\n      params: ClientRequest__CommandExecParams,\n    }).annotate({\n      title: \"Command/execRequest\",\n      description: \"Execute a standalone command (argv vector) under the server's sandbox.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec/write\").annotate({\n        title: \"Command/exec/writeRequestMethod\",\n      }),\n      params: ClientRequest__CommandExecWriteParams,\n    }).annotate({\n      title: \"Command/exec/writeRequest\",\n      description: \"Write stdin bytes to a running `command/exec` session or close stdin.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec/terminate\").annotate({\n        title: \"Command/exec/terminateRequestMethod\",\n      }),\n      params: ClientRequest__CommandExecTerminateParams,\n    }).annotate({\n      title: \"Command/exec/terminateRequest\",\n      description: \"Terminate a running `command/exec` session by client-supplied `processId`.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec/resize\").annotate({\n        title: \"Command/exec/resizeRequestMethod\",\n      }),\n      params: ClientRequest__CommandExecResizeParams,\n    }).annotate({\n      title: \"Command/exec/resizeRequest\",\n      description:\n        \"Resize a running PTY-backed `command/exec` session by client-supplied `processId`.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/read\").annotate({ title: \"Config/readRequestMethod\" }),\n      params: ClientRequest__ConfigReadParams,\n    }).annotate({ title: \"Config/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"externalAgentConfig/detect\").annotate({\n        title: \"ExternalAgentConfig/detectRequestMethod\",\n      }),\n      params: ClientRequest__ExternalAgentConfigDetectParams,\n    }).annotate({ title: \"ExternalAgentConfig/detectRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"externalAgentConfig/import\").annotate({\n        title: \"ExternalAgentConfig/importRequestMethod\",\n      }),\n      params: ClientRequest__ExternalAgentConfigImportParams,\n    }).annotate({ title: \"ExternalAgentConfig/importRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"externalAgentConfig/import/readHistories\").annotate({\n        title: \"ExternalAgentConfig/import/readHistoriesRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"ExternalAgentConfig/import/readHistoriesRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/value/write\").annotate({\n        title: \"Config/value/writeRequestMethod\",\n      }),\n      params: ClientRequest__ConfigValueWriteParams,\n    }).annotate({ title: \"Config/value/writeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/batchWrite\").annotate({\n        title: \"Config/batchWriteRequestMethod\",\n      }),\n      params: ClientRequest__ConfigBatchWriteParams,\n    }).annotate({ title: \"Config/batchWriteRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"configRequirements/read\").annotate({\n        title: \"ConfigRequirements/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"ConfigRequirements/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/read\").annotate({ title: \"Account/readRequestMethod\" }),\n      params: ClientRequest__GetAccountParams,\n    }).annotate({ title: \"Account/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fuzzyFileSearch\").annotate({ title: \"FuzzyFileSearchRequestMethod\" }),\n      params: ClientRequest__FuzzyFileSearchParams,\n    }).annotate({ title: \"FuzzyFileSearchRequest\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"ClientRequest\", description: \"Request from the client to the server.\" });\n\nexport type ClientRequest__AdditionalContextEntry = {\n  readonly kind: ClientRequest__AdditionalContextKind;\n  readonly value: string;\n};\nexport const ClientRequest__AdditionalContextEntry = Schema.Struct({\n  kind: ClientRequest__AdditionalContextKind,\n  value: Schema.String,\n});\n\nexport type ClientRequest__ByteRange = { readonly end: number; readonly start: number };\nexport const ClientRequest__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type ClientRequest__CapabilityRootLocation = {\n  readonly environmentId: string;\n  readonly path: string;\n  readonly type: \"environment\";\n};\nexport const ClientRequest__CapabilityRootLocation = Schema.Union(\n  [\n    Schema.Struct({\n      environmentId: Schema.String,\n      path: Schema.String.annotate({\n        description: \"Absolute path for the root in the selected environment.\",\n      }),\n      type: Schema.Literal(\"environment\").annotate({\n        title: \"EnvironmentCapabilityRootLocationType\",\n      }),\n    }).annotate({\n      title: \"EnvironmentCapabilityRootLocation\",\n      description: \"A path owned by an execution environment.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"Location used to resolve a selected capability root.\" });\n\nexport type ClientRequest__CodexResponseHandoffMode = \"thinking\" | \"commentary\" | \"bemTags\";\nexport const ClientRequest__CodexResponseHandoffMode = Schema.Literals([\n  \"thinking\",\n  \"commentary\",\n  \"bemTags\",\n]);\n\nexport type ClientRequest__CollaborationMode = {\n  readonly mode: ClientRequest__ModeKind;\n  readonly settings: ClientRequest__Settings;\n};\nexport const ClientRequest__CollaborationMode = Schema.Struct({\n  mode: ClientRequest__ModeKind,\n  settings: ClientRequest__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type ClientRequest__DynamicToolSpec =\n  | {\n      readonly deferLoading?: boolean;\n      readonly description: string;\n      readonly inputSchema: unknown;\n      readonly name: string;\n      readonly type: \"function\";\n    }\n  | {\n      readonly description: string;\n      readonly name: string;\n      readonly tools: ReadonlyArray<ClientRequest__DynamicToolNamespaceTool>;\n      readonly type: \"namespace\";\n    };\nexport const ClientRequest__DynamicToolSpec = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolSpecType\" }),\n    }).annotate({ title: \"FunctionDynamicToolSpec\" }),\n    Schema.Struct({\n      description: Schema.String,\n      name: Schema.String,\n      tools: Schema.Array(ClientRequest__DynamicToolNamespaceTool),\n      type: Schema.Literal(\"namespace\").annotate({ title: \"NamespaceDynamicToolSpecType\" }),\n    }).annotate({ title: \"NamespaceDynamicToolSpec\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const ClientRequest__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type ClientRequest__NetworkAccess = \"restricted\" | \"enabled\";\nexport const ClientRequest__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type ClientRequest__ProcessTerminalSize = { readonly cols: number; readonly rows: number };\nexport const ClientRequest__ProcessTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `process/spawn` PTY sessions.\" });\n\nexport type ClientRequest__RealtimeConversationVersion = \"v1\" | \"v2\" | \"v3\";\nexport const ClientRequest__RealtimeConversationVersion = Schema.Literals([\"v1\", \"v2\", \"v3\"]);\n\nexport type ClientRequest__RealtimeOutputModality = \"text\" | \"audio\";\nexport const ClientRequest__RealtimeOutputModality = Schema.Literals([\"text\", \"audio\"]);\n\nexport type ClientRequest__RealtimeVoice =\n  | \"alloy\"\n  | \"arbor\"\n  | \"ash\"\n  | \"ballad\"\n  | \"breeze\"\n  | \"cedar\"\n  | \"coral\"\n  | \"cove\"\n  | \"echo\"\n  | \"ember\"\n  | \"juniper\"\n  | \"maple\"\n  | \"marin\"\n  | \"sage\"\n  | \"shimmer\"\n  | \"sol\"\n  | \"spruce\"\n  | \"vale\"\n  | \"verse\";\nexport const ClientRequest__RealtimeVoice = Schema.Literals([\n  \"alloy\",\n  \"arbor\",\n  \"ash\",\n  \"ballad\",\n  \"breeze\",\n  \"cedar\",\n  \"coral\",\n  \"cove\",\n  \"echo\",\n  \"ember\",\n  \"juniper\",\n  \"maple\",\n  \"marin\",\n  \"sage\",\n  \"shimmer\",\n  \"sol\",\n  \"spruce\",\n  \"vale\",\n  \"verse\",\n]);\n\nexport type ClientRequest__RemoteControlDisableParams = { readonly ephemeral?: boolean };\nexport const ClientRequest__RemoteControlDisableParams = Schema.Struct({\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type ClientRequest__RemoteControlEnableParams = { readonly ephemeral?: boolean };\nexport const ClientRequest__RemoteControlEnableParams = Schema.Struct({\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type ClientRequest__ResponseItem =\n  | {\n      readonly content: ReadonlyArray<ClientRequest__ContentItem>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly phase?: ClientRequest__MessagePhase | null;\n      readonly role: string;\n      readonly type: \"message\";\n    }\n  | {\n      readonly author: string;\n      readonly content: ReadonlyArray<ClientRequest__AgentMessageInputContent>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly recipient: string;\n      readonly type: \"agent_message\";\n    }\n  | {\n      readonly content?: ReadonlyArray<ClientRequest__ReasoningItemContent> | null;\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly summary: ReadonlyArray<ClientRequest__ReasoningItemReasoningSummary>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly action: ClientRequest__LocalShellAction;\n      readonly call_id?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status: ClientRequest__LocalShellStatus;\n      readonly type: \"local_shell_call\";\n    }\n  | {\n      readonly arguments: string;\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly type: \"function_call\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"tool_search_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly output: ClientRequest__FunctionCallOutputBody;\n      readonly type: \"function_call_output\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly input: string;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly status?: string | null;\n      readonly type: \"custom_tool_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly name?: string | null;\n      readonly output: ClientRequest__FunctionCallOutputBody;\n      readonly type: \"custom_tool_call_output\";\n    }\n  | {\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status: string;\n      readonly tools: ReadonlyArray<unknown>;\n      readonly type: \"tool_search_output\";\n    }\n  | {\n      readonly action?: ClientRequest__ResponsesApiWebSearchAction | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"web_search_call\";\n    }\n  | {\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly result: string;\n      readonly revised_prompt?: string | null;\n      readonly status: string;\n      readonly type: \"image_generation_call\";\n    }\n  | {\n      readonly encrypted_content: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"compaction\";\n    }\n  | { readonly type: \"compaction_trigger\" }\n  | {\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"context_compaction\";\n    }\n  | { readonly type: \"other\" };\nexport const ClientRequest__ResponseItem = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.Array(ClientRequest__ContentItem),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([ClientRequest__MessagePhase, Schema.Null])),\n      role: Schema.String,\n      type: Schema.Literal(\"message\").annotate({ title: \"MessageResponseItemType\" }),\n    }).annotate({ title: \"MessageResponseItem\" }),\n    Schema.Struct({\n      author: Schema.String,\n      content: Schema.Array(ClientRequest__AgentMessageInputContent),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      recipient: Schema.String,\n      type: Schema.Literal(\"agent_message\").annotate({ title: \"AgentMessageResponseItemType\" }),\n    }).annotate({ title: \"AgentMessageResponseItem\" }),\n    Schema.Struct({\n      content: Schema.optionalKey(\n        Schema.Union([Schema.Array(ClientRequest__ReasoningItemContent), Schema.Null]),\n      ),\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      summary: Schema.Array(ClientRequest__ReasoningItemReasoningSummary),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningResponseItemType\" }),\n    }).annotate({ title: \"ReasoningResponseItem\" }),\n    Schema.Struct({\n      action: ClientRequest__LocalShellAction,\n      call_id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Set when using the Responses API.\" }),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Legacy id field retained for compatibility with older payloads.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: ClientRequest__LocalShellStatus,\n      type: Schema.Literal(\"local_shell_call\").annotate({\n        title: \"LocalShellCallResponseItemType\",\n      }),\n    }).annotate({ title: \"LocalShellCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.String,\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"function_call\").annotate({ title: \"FunctionCallResponseItemType\" }),\n    }).annotate({ title: \"FunctionCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"tool_search_call\").annotate({\n        title: \"ToolSearchCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      output: ClientRequest__FunctionCallOutputBody,\n      type: Schema.Literal(\"function_call_output\").annotate({\n        title: \"FunctionCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"FunctionCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      input: Schema.String,\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"custom_tool_call\").annotate({\n        title: \"CustomToolCallResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      output: ClientRequest__FunctionCallOutputBody,\n      type: Schema.Literal(\"custom_tool_call_output\").annotate({\n        title: \"CustomToolCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.String,\n      tools: Schema.Array(Schema.Unknown),\n      type: Schema.Literal(\"tool_search_output\").annotate({\n        title: \"ToolSearchOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchOutputResponseItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([ClientRequest__ResponsesApiWebSearchAction, Schema.Null]),\n      ),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"web_search_call\").annotate({ title: \"WebSearchCallResponseItemType\" }),\n    }).annotate({ title: \"WebSearchCallResponseItem\" }),\n    Schema.Struct({\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      result: Schema.String,\n      revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.String,\n      type: Schema.Literal(\"image_generation_call\").annotate({\n        title: \"ImageGenerationCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ImageGenerationCallResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"compaction\").annotate({ title: \"CompactionResponseItemType\" }),\n    }).annotate({ title: \"CompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"compaction_trigger\").annotate({\n        title: \"CompactionTriggerResponseItemType\",\n      }),\n    }).annotate({ title: \"CompactionTriggerResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"context_compaction\").annotate({\n        title: \"ContextCompactionResponseItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponseItemType\" }),\n    }).annotate({ title: \"OtherResponseItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__SelectedCapabilityRoot = {\n  readonly id: string;\n  readonly location: {\n    readonly environmentId: string;\n    readonly path: string;\n    readonly type: \"environment\";\n  };\n};\nexport const ClientRequest__SelectedCapabilityRoot = Schema.Struct({\n  id: Schema.String.annotate({\n    description: \"Stable identifier supplied by the capability selection platform.\",\n  }),\n  location: Schema.Union(\n    [\n      Schema.Struct({\n        environmentId: Schema.String,\n        path: Schema.String.annotate({\n          description: \"Absolute path for the root in the selected environment.\",\n        }),\n        type: Schema.Literal(\"environment\").annotate({\n          title: \"EnvironmentCapabilityRootLocationType\",\n        }),\n      }).annotate({\n        title: \"EnvironmentCapabilityRootLocation\",\n        description: \"A path owned by an execution environment.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Location used to resolve a selected capability root.\" }),\n}).annotate({\n  description: \"A user-selected root that can expose one or more runtime capabilities.\",\n});\n\nexport type ClientRequest__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const ClientRequest__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type ClientRequest__ThreadMemoryMode = \"enabled\" | \"disabled\";\nexport const ClientRequest__ThreadMemoryMode = Schema.Literals([\"enabled\", \"disabled\"]);\n\nexport type ClientRequest__ThreadRealtimeAudioChunk = {\n  readonly data: string;\n  readonly itemId?: string | null;\n  readonly numChannels: number;\n  readonly sampleRate: number;\n  readonly samplesPerChannel?: number | null;\n};\nexport const ClientRequest__ThreadRealtimeAudioChunk = Schema.Struct({\n  data: Schema.String,\n  itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  numChannels: Schema.Number.annotate({ format: \"uint16\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  sampleRate: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  samplesPerChannel: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - thread realtime audio chunk.\" });\n\nexport type ClientRequest__ThreadRealtimeInitialItem = {\n  readonly role: ClientRequest__ConversationTextRole;\n  readonly text: string;\n};\nexport const ClientRequest__ThreadRealtimeInitialItem = Schema.Struct({\n  role: ClientRequest__ConversationTextRole,\n  text: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL - role-bearing text item included when a realtime V3 session starts.\",\n});\n\nexport type ClientRequest__ThreadRealtimeStartTransport =\n  | { readonly type: \"websocket\" }\n  | { readonly sdp: string; readonly type: \"webrtc\" };\nexport const ClientRequest__ThreadRealtimeStartTransport = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"websocket\").annotate({\n        title: \"WebsocketThreadRealtimeStartTransportType\",\n      }),\n    }).annotate({ title: \"WebsocketThreadRealtimeStartTransport\" }),\n    Schema.Struct({\n      sdp: Schema.String.annotate({\n        description:\n          \"SDP offer generated by a WebRTC RTCPeerConnection after configuring audio and the realtime events data channel.\",\n      }),\n      type: Schema.Literal(\"webrtc\").annotate({ title: \"WebrtcThreadRealtimeStartTransportType\" }),\n    }).annotate({ title: \"WebrtcThreadRealtimeStartTransport\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"EXPERIMENTAL - transport used by thread realtime.\" });\n\nexport type ClientRequest__ThreadResumeInitialTurnsPageParams = {\n  readonly itemsView?: ClientRequest__TurnItemsView | null;\n  readonly limit?: number | null;\n  readonly sortDirection?: ClientRequest__SortDirection | null;\n};\nexport const ClientRequest__ThreadResumeInitialTurnsPageParams = Schema.Struct({\n  itemsView: Schema.optionalKey(\n    Schema.Union([ClientRequest__TurnItemsView, Schema.Null]).annotate({\n      description: \"How much item detail to include for each returned turn; defaults to summary.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Optional turn page size.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([ClientRequest__SortDirection, Schema.Null]).annotate({\n      description: \"Optional turn pagination direction; defaults to descending.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__TurnEnvironmentParams = {\n  readonly cwd: ClientRequest__LegacyAppPathString;\n  readonly environmentId: string;\n  readonly runtimeWorkspaceRoots?: ReadonlyArray<ClientRequest__LegacyAppPathString> | null;\n};\nexport const ClientRequest__TurnEnvironmentParams = Schema.Struct({\n  cwd: ClientRequest__LegacyAppPathString,\n  environmentId: Schema.String,\n  runtimeWorkspaceRoots: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__LegacyAppPathString).annotate({\n        description: \"Environment-native runtime workspace roots. Omitted defaults to `cwd`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type CommandExecutionRequestApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly command?: string | null;\n  readonly commandActions?: ReadonlyArray<CommandExecutionRequestApprovalParams__CommandAction> | null;\n  readonly cwd?: CommandExecutionRequestApprovalParams__LegacyAppPathString | null;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly networkApprovalContext?: CommandExecutionRequestApprovalParams__NetworkApprovalContext | null;\n  readonly proposedExecpolicyAmendment?: ReadonlyArray<string> | null;\n  readonly proposedNetworkPolicyAmendments?: ReadonlyArray<CommandExecutionRequestApprovalParams__NetworkPolicyAmendment> | null;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const CommandExecutionRequestApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Unique identifier for this specific approval callback.\\n\\nFor regular shell/unified_exec approvals, this is null.\\n\\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  command: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"The command to be executed.\" }),\n      Schema.Null,\n    ]),\n  ),\n  commandActions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(CommandExecutionRequestApprovalParams__CommandAction).annotate({\n        description: \"Best-effort parsed command actions for friendly display.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__LegacyAppPathString,\n      Schema.Null,\n    ]).annotate({ description: \"The command's working directory.\" }),\n  ),\n  environmentId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Environment in which the command will run.\" }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  networkApprovalContext: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__NetworkApprovalContext,\n      Schema.Null,\n    ]).annotate({ description: \"Optional context for a managed-network approval prompt.\" }),\n  ),\n  proposedExecpolicyAmendment: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional proposed execpolicy amendment to allow similar commands without prompting.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  proposedNetworkPolicyAmendments: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(CommandExecutionRequestApprovalParams__NetworkPolicyAmendment).annotate({\n        description:\n          \"Optional proposed network policy amendments (allow/deny host) for future requests.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for network access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"CommandExecutionRequestApprovalParams\" });\n\nexport type CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = {\n  readonly fileSystem?: CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions | null;\n  readonly network?: CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions | null;\n};\nexport const CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions,\n      Schema.Null,\n    ]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions,\n      Schema.Null,\n    ]).annotate({ description: \"Partial overlay used for per-command permission requests.\" }),\n  ),\n});\n\nexport type CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | {\n      readonly acceptWithExecpolicyAmendment: {\n        readonly execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | {\n      readonly applyNetworkPolicyAmendment: {\n        readonly network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment;\n      };\n    }\n  | \"decline\"\n  | \"cancel\";\nexport const CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision = Schema.Union(\n  [\n    Schema.Literal(\"accept\").annotate({ description: \"User approved the command.\" }),\n    Schema.Literal(\"acceptForSession\").annotate({\n      description:\n        \"User approved the command and future prompts in the same session-scoped approval cache should run without prompting.\",\n    }),\n    Schema.Struct({\n      acceptWithExecpolicyAmendment: Schema.Struct({\n        execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision\",\n      description:\n        \"User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.\",\n    }),\n    Schema.Struct({\n      applyNetworkPolicyAmendment: Schema.Struct({\n        network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision\",\n      description: \"User chose a persistent network policy rule (allow/deny) for this host.\",\n    }),\n    Schema.Literal(\"decline\").annotate({\n      description: \"User denied the command. The agent will continue the turn.\",\n    }),\n    Schema.Literal(\"cancel\").annotate({\n      description: \"User denied the command. The turn will also be immediately interrupted.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalResponse = {\n  readonly decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision;\n};\nexport const CommandExecutionRequestApprovalResponse = Schema.Struct({\n  decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision,\n}).annotate({ title: \"CommandExecutionRequestApprovalResponse\" });\n\nexport type DynamicToolCallParams = {\n  readonly arguments: unknown;\n  readonly callId: string;\n  readonly namespace?: string | null;\n  readonly threadId: string;\n  readonly tool: string;\n  readonly turnId: string;\n};\nexport const DynamicToolCallParams = Schema.Struct({\n  arguments: Schema.Unknown,\n  callId: Schema.String,\n  namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  tool: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"DynamicToolCallParams\" });\n\nexport type DynamicToolCallResponse = {\n  readonly contentItems: ReadonlyArray<DynamicToolCallResponse__DynamicToolCallOutputContentItem>;\n  readonly success: boolean;\n};\nexport const DynamicToolCallResponse = Schema.Struct({\n  contentItems: Schema.Array(DynamicToolCallResponse__DynamicToolCallOutputContentItem),\n  success: Schema.Boolean,\n}).annotate({ title: \"DynamicToolCallResponse\" });\n\nexport type ExecCommandApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly callId: string;\n  readonly command: ReadonlyArray<string>;\n  readonly conversationId: ExecCommandApprovalParams__ThreadId;\n  readonly cwd: string;\n  readonly parsedCmd: ReadonlyArray<ExecCommandApprovalParams__ParsedCommand>;\n  readonly reason?: string | null;\n};\nexport const ExecCommandApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Identifier for this specific approval callback.\" }),\n      Schema.Null,\n    ]),\n  ),\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].\",\n  }),\n  command: Schema.Array(Schema.String),\n  conversationId: ExecCommandApprovalParams__ThreadId,\n  cwd: Schema.String,\n  parsedCmd: Schema.Array(ExecCommandApprovalParams__ParsedCommand),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ExecCommandApprovalParams\" });\n\nexport type ExecCommandApprovalResponse = {\n  readonly decision: ExecCommandApprovalResponse__ReviewDecision;\n};\nexport const ExecCommandApprovalResponse = Schema.Struct({\n  decision: ExecCommandApprovalResponse__ReviewDecision,\n}).annotate({ title: \"ExecCommandApprovalResponse\" });\n\nexport type FileChangeRequestApprovalParams = {\n  readonly grantRoot?: string | null;\n  readonly itemId: string;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const FileChangeRequestApprovalParams = Schema.Struct({\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"FileChangeRequestApprovalParams\" });\n\nexport type FileChangeRequestApprovalResponse = {\n  readonly decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision;\n};\nexport const FileChangeRequestApprovalResponse = Schema.Struct({\n  decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision,\n}).annotate({ title: \"FileChangeRequestApprovalResponse\" });\n\nexport type FuzzyFileSearchParams = {\n  readonly cancellationToken?: string | null;\n  readonly query: string;\n  readonly roots: ReadonlyArray<string>;\n};\nexport const FuzzyFileSearchParams = Schema.Struct({\n  cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  query: Schema.String,\n  roots: Schema.Array(Schema.String),\n}).annotate({ title: \"FuzzyFileSearchParams\" });\n\nexport type FuzzyFileSearchResponse = {\n  readonly files: ReadonlyArray<FuzzyFileSearchResponse__FuzzyFileSearchResult>;\n};\nexport const FuzzyFileSearchResponse = Schema.Struct({\n  files: Schema.Array(FuzzyFileSearchResponse__FuzzyFileSearchResult),\n}).annotate({ title: \"FuzzyFileSearchResponse\" });\n\nexport type FuzzyFileSearchSessionCompletedNotification = { readonly sessionId: string };\nexport const FuzzyFileSearchSessionCompletedNotification = Schema.Struct({\n  sessionId: Schema.String,\n}).annotate({ title: \"FuzzyFileSearchSessionCompletedNotification\" });\n\nexport type FuzzyFileSearchSessionUpdatedNotification = {\n  readonly files: ReadonlyArray<FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult>;\n  readonly query: string;\n  readonly sessionId: string;\n};\nexport const FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({\n  files: Schema.Array(FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult),\n  query: Schema.String,\n  sessionId: Schema.String,\n}).annotate({ title: \"FuzzyFileSearchSessionUpdatedNotification\" });\n\nexport type GetAuthStatusParams = {\n  readonly includeToken?: boolean | null;\n  readonly refreshToken?: boolean | null;\n};\nexport const GetAuthStatusParams = Schema.Struct({\n  includeToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  refreshToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n}).annotate({ title: \"GetAuthStatusParams\" });\n\nexport type GetAuthStatusResponse = {\n  readonly authMethod: unknown | null;\n  readonly authToken: string | null;\n  readonly requiresOpenaiAuth: boolean | null;\n};\nexport const GetAuthStatusResponse = Schema.Struct({\n  authMethod: Schema.Union([Schema.Unknown, Schema.Null]),\n  authToken: Schema.Union([Schema.String, Schema.Null]),\n  requiresOpenaiAuth: Schema.Union([Schema.Boolean, Schema.Null]),\n}).annotate({ title: \"GetAuthStatusResponse\" });\n\nexport type GetConversationSummaryParams =\n  | { readonly rolloutPath: string }\n  | { readonly conversationId: string };\nexport const GetConversationSummaryParams = Schema.Union(\n  [Schema.Struct({ rolloutPath: Schema.String }), Schema.Struct({ conversationId: Schema.String })],\n  { mode: \"oneOf\" },\n).annotate({ title: \"GetConversationSummaryParams\" });\n\nexport type GetConversationSummaryResponse = { readonly summary: unknown };\nexport const GetConversationSummaryResponse = Schema.Struct({ summary: Schema.Unknown }).annotate({\n  title: \"GetConversationSummaryResponse\",\n});\n\nexport type GitDiffToRemoteParams = { readonly cwd: string };\nexport const GitDiffToRemoteParams = Schema.Struct({ cwd: Schema.String }).annotate({\n  title: \"GitDiffToRemoteParams\",\n});\n\nexport type GitDiffToRemoteResponse = { readonly sha: string; readonly diff: string };\nexport const GitDiffToRemoteResponse = Schema.Struct({\n  sha: Schema.String,\n  diff: Schema.String,\n}).annotate({ title: \"GitDiffToRemoteResponse\" });\n\nexport type JSONRPCError = {\n  readonly error: JSONRPCError__JSONRPCErrorError;\n  readonly id: JSONRPCError__RequestId;\n};\nexport const JSONRPCError = Schema.Struct({\n  error: JSONRPCError__JSONRPCErrorError,\n  id: JSONRPCError__RequestId,\n}).annotate({\n  title: \"JSONRPCError\",\n  description: \"A response to a request that indicates an error occurred.\",\n});\n\nexport type JSONRPCErrorError = {\n  readonly code: number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const JSONRPCErrorError = Schema.Struct({\n  code: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  data: Schema.optionalKey(Schema.Unknown),\n  message: Schema.String,\n}).annotate({ title: \"JSONRPCErrorError\" });\n\nexport type JSONRPCMessage =\n  | JSONRPCMessage__JSONRPCRequest\n  | JSONRPCMessage__JSONRPCNotification\n  | JSONRPCMessage__JSONRPCResponse\n  | JSONRPCMessage__JSONRPCError;\nexport const JSONRPCMessage = Schema.Union([\n  JSONRPCMessage__JSONRPCRequest,\n  JSONRPCMessage__JSONRPCNotification,\n  JSONRPCMessage__JSONRPCResponse,\n  JSONRPCMessage__JSONRPCError,\n]).annotate({\n  title: \"JSONRPCMessage\",\n  description:\n    \"Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.\",\n});\n\nexport type JSONRPCNotification = { readonly method: string; readonly params?: unknown };\nexport const JSONRPCNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n}).annotate({\n  title: \"JSONRPCNotification\",\n  description: \"A notification which does not expect a response.\",\n});\n\nexport type JSONRPCRequest = {\n  readonly id: JSONRPCRequest__RequestId;\n  readonly method: string;\n  readonly params?: unknown;\n  readonly trace?: JSONRPCRequest__W3cTraceContext | null;\n};\nexport const JSONRPCRequest = Schema.Struct({\n  id: JSONRPCRequest__RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n  trace: Schema.optionalKey(\n    Schema.Union([JSONRPCRequest__W3cTraceContext, Schema.Null]).annotate({\n      description: \"Optional W3C Trace Context for distributed tracing.\",\n    }),\n  ),\n}).annotate({ title: \"JSONRPCRequest\", description: \"A request that expects a response.\" });\n\nexport type JSONRPCResponse = { readonly id: JSONRPCResponse__RequestId; readonly result: unknown };\nexport const JSONRPCResponse = Schema.Struct({\n  id: JSONRPCResponse__RequestId,\n  result: Schema.Unknown,\n}).annotate({\n  title: \"JSONRPCResponse\",\n  description: \"A successful (non-error) response to a request.\",\n});\n\nexport type McpServerElicitationRequestParams =\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"form\";\n      readonly requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"openai/form\";\n      readonly requestedSchema: unknown;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly elicitationId: string;\n      readonly message: string;\n      readonly mode: \"url\";\n      readonly url: string;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    };\nexport const McpServerElicitationRequestParams = Schema.Union(\n  [\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"form\"),\n      requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"McpServerElicitationRequestParams\" }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"openai/form\"),\n      requestedSchema: Schema.Unknown,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"McpServerElicitationRequestParams\" }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      elicitationId: Schema.String,\n      message: Schema.String,\n      mode: Schema.Literal(\"url\"),\n      url: Schema.String,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"McpServerElicitationRequestParams\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type McpServerElicitationRequestResponse = {\n  readonly _meta?: unknown;\n  readonly action: McpServerElicitationRequestResponse__McpServerElicitationAction;\n  readonly content?: unknown;\n};\nexport const McpServerElicitationRequestResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description: \"Optional client metadata for form-mode action handling.\",\n    }),\n  ),\n  action: McpServerElicitationRequestResponse__McpServerElicitationAction,\n  content: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.\\n\\nThis is nullable because decline/cancel responses have no content.\",\n    }),\n  ),\n}).annotate({ title: \"McpServerElicitationRequestResponse\" });\n\nexport type PermissionsRequestApprovalParams = {\n  readonly cwd: PermissionsRequestApprovalParams__AbsolutePathBuf;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly permissions: PermissionsRequestApprovalParams__RequestPermissionProfile;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const PermissionsRequestApprovalParams = Schema.Struct({\n  cwd: PermissionsRequestApprovalParams__AbsolutePathBuf,\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  itemId: Schema.String,\n  permissions: PermissionsRequestApprovalParams__RequestPermissionProfile,\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"PermissionsRequestApprovalParams\" });\n\nexport type PermissionsRequestApprovalResponse = {\n  readonly permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile;\n  readonly scope?: \"turn\" | \"session\";\n  readonly strictAutoReview?: boolean | null;\n};\nexport const PermissionsRequestApprovalResponse = Schema.Struct({\n  permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile,\n  scope: Schema.optionalKey(Schema.Literals([\"turn\", \"session\"]).annotate({ default: \"turn\" })),\n  strictAutoReview: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Review every subsequent command in this turn before normal sandboxed execution.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PermissionsRequestApprovalResponse\" });\n\nexport type PermissionsRequestApprovalResponse__PermissionGrantScope = \"turn\" | \"session\";\nexport const PermissionsRequestApprovalResponse__PermissionGrantScope = Schema.Literals([\n  \"turn\",\n  \"session\",\n]);\n\nexport type RequestId = string | number;\nexport const RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]).annotate({ title: \"RequestId\" });\n\nexport type ServerNotification =\n  | {\n      readonly method: \"error\";\n      readonly params: ServerNotification__ErrorNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/started\";\n      readonly params: ServerNotification__ThreadStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/status/changed\";\n      readonly params: ServerNotification__ThreadStatusChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/archived\";\n      readonly params: ServerNotification__ThreadArchivedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/deleted\";\n      readonly params: ServerNotification__ThreadDeletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/unarchived\";\n      readonly params: ServerNotification__ThreadUnarchivedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/closed\";\n      readonly params: ServerNotification__ThreadClosedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"skills/changed\";\n      readonly params: ServerNotification__SkillsChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/name/updated\";\n      readonly params: ServerNotification__ThreadNameUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/goal/updated\";\n      readonly params: ServerNotification__ThreadGoalUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/goal/cleared\";\n      readonly params: ServerNotification__ThreadGoalClearedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/environment/connected\";\n      readonly params: ServerNotification__EnvironmentConnectionNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/environment/disconnected\";\n      readonly params: ServerNotification__EnvironmentConnectionNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/settings/updated\";\n      readonly params: ServerNotification__ThreadSettingsUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/tokenUsage/updated\";\n      readonly params: ServerNotification__ThreadTokenUsageUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/started\";\n      readonly params: ServerNotification__TurnStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"hook/started\";\n      readonly params: ServerNotification__HookStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/completed\";\n      readonly params: ServerNotification__TurnCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"hook/completed\";\n      readonly params: ServerNotification__HookCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/diff/updated\";\n      readonly params: ServerNotification__TurnDiffUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/plan/updated\";\n      readonly params: ServerNotification__TurnPlanUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/started\";\n      readonly params: ServerNotification__ItemStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/autoApprovalReview/started\";\n      readonly params: ServerNotification__ItemGuardianApprovalReviewStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/autoApprovalReview/completed\";\n      readonly params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/completed\";\n      readonly params: ServerNotification__ItemCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/agentMessage/delta\";\n      readonly params: ServerNotification__AgentMessageDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/plan/delta\";\n      readonly params: ServerNotification__PlanDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"command/exec/outputDelta\";\n      readonly params: ServerNotification__CommandExecOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"process/outputDelta\";\n      readonly params: ServerNotification__ProcessOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"process/exited\";\n      readonly params: ServerNotification__ProcessExitedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/commandExecution/outputDelta\";\n      readonly params: ServerNotification__CommandExecutionOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/commandExecution/terminalInteraction\";\n      readonly params: ServerNotification__TerminalInteractionNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/fileChange/outputDelta\";\n      readonly params: ServerNotification__FileChangeOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/fileChange/patchUpdated\";\n      readonly params: ServerNotification__FileChangePatchUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"serverRequest/resolved\";\n      readonly params: ServerNotification__ServerRequestResolvedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/mcpToolCall/progress\";\n      readonly params: ServerNotification__McpToolCallProgressNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"mcpServer/oauthLogin/completed\";\n      readonly params: ServerNotification__McpServerOauthLoginCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"mcpServer/startupStatus/updated\";\n      readonly params: ServerNotification__McpServerStatusUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"account/updated\";\n      readonly params: ServerNotification__AccountUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"account/rateLimits/updated\";\n      readonly params: ServerNotification__AccountRateLimitsUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"app/list/updated\";\n      readonly params: ServerNotification__AppListUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"remoteControl/status/changed\";\n      readonly params: ServerNotification__RemoteControlStatusChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"externalAgentConfig/import/progress\";\n      readonly params: ServerNotification__ExternalAgentConfigImportProgressNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"externalAgentConfig/import/completed\";\n      readonly params: ServerNotification__ExternalAgentConfigImportCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"fs/changed\";\n      readonly params: ServerNotification__FsChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/reasoning/summaryTextDelta\";\n      readonly params: ServerNotification__ReasoningSummaryTextDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/reasoning/summaryPartAdded\";\n      readonly params: ServerNotification__ReasoningSummaryPartAddedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/reasoning/textDelta\";\n      readonly params: ServerNotification__ReasoningTextDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/compacted\";\n      readonly params: ServerNotification__ContextCompactedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"model/rerouted\";\n      readonly params: ServerNotification__ModelReroutedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"model/verification\";\n      readonly params: ServerNotification__ModelVerificationNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/moderationMetadata\";\n      readonly params: ServerNotification__TurnModerationMetadataNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"model/safetyBuffering/updated\";\n      readonly params: ServerNotification__ModelSafetyBufferingUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"warning\";\n      readonly params: ServerNotification__WarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"guardianWarning\";\n      readonly params: ServerNotification__GuardianWarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"deprecationNotice\";\n      readonly params: ServerNotification__DeprecationNoticeNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"configWarning\";\n      readonly params: ServerNotification__ConfigWarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"fuzzyFileSearch/sessionUpdated\";\n      readonly params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"fuzzyFileSearch/sessionCompleted\";\n      readonly params: ServerNotification__FuzzyFileSearchSessionCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/started\";\n      readonly params: ServerNotification__ThreadRealtimeStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/itemAdded\";\n      readonly params: ServerNotification__ThreadRealtimeItemAddedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/transcript/delta\";\n      readonly params: ServerNotification__ThreadRealtimeTranscriptDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/transcript/done\";\n      readonly params: ServerNotification__ThreadRealtimeTranscriptDoneNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/outputAudio/delta\";\n      readonly params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/sdp\";\n      readonly params: ServerNotification__ThreadRealtimeSdpNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/error\";\n      readonly params: ServerNotification__ThreadRealtimeErrorNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/closed\";\n      readonly params: ServerNotification__ThreadRealtimeClosedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"windows/worldWritableWarning\";\n      readonly params: ServerNotification__WindowsWorldWritableWarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"windowsSandbox/setupCompleted\";\n      readonly params: ServerNotification__WindowsSandboxSetupCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"account/login/completed\";\n      readonly params: ServerNotification__AccountLoginCompletedNotification;\n      readonly emittedAtMs?: number;\n    };\nexport const ServerNotification = Schema.Union(\n  [\n    Schema.Struct({\n      method: Schema.Literal(\"error\").annotate({ title: \"ErrorNotificationMethod\" }),\n      params: ServerNotification__ErrorNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/started\").annotate({\n        title: \"Thread/startedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/status/changed\").annotate({\n        title: \"Thread/status/changedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadStatusChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/archived\").annotate({\n        title: \"Thread/archivedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadArchivedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/deleted\").annotate({\n        title: \"Thread/deletedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadDeletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/unarchived\").annotate({\n        title: \"Thread/unarchivedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadUnarchivedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/closed\").annotate({\n        title: \"Thread/closedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadClosedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"skills/changed\").annotate({\n        title: \"Skills/changedNotificationMethod\",\n      }),\n      params: ServerNotification__SkillsChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/name/updated\").annotate({\n        title: \"Thread/name/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadNameUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/goal/updated\").annotate({\n        title: \"Thread/goal/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadGoalUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/goal/cleared\").annotate({\n        title: \"Thread/goal/clearedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadGoalClearedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/environment/connected\").annotate({\n        title: \"Thread/environment/connectedNotificationMethod\",\n      }),\n      params: ServerNotification__EnvironmentConnectionNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/environment/disconnected\").annotate({\n        title: \"Thread/environment/disconnectedNotificationMethod\",\n      }),\n      params: ServerNotification__EnvironmentConnectionNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/settings/updated\").annotate({\n        title: \"Thread/settings/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadSettingsUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/tokenUsage/updated\").annotate({\n        title: \"Thread/tokenUsage/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadTokenUsageUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/started\").annotate({ title: \"Turn/startedNotificationMethod\" }),\n      params: ServerNotification__TurnStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"hook/started\").annotate({ title: \"Hook/startedNotificationMethod\" }),\n      params: ServerNotification__HookStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/completed\").annotate({\n        title: \"Turn/completedNotificationMethod\",\n      }),\n      params: ServerNotification__TurnCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"hook/completed\").annotate({\n        title: \"Hook/completedNotificationMethod\",\n      }),\n      params: ServerNotification__HookCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/diff/updated\").annotate({\n        title: \"Turn/diff/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__TurnDiffUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/plan/updated\").annotate({\n        title: \"Turn/plan/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__TurnPlanUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/started\").annotate({ title: \"Item/startedNotificationMethod\" }),\n      params: ServerNotification__ItemStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/autoApprovalReview/started\").annotate({\n        title: \"Item/autoApprovalReview/startedNotificationMethod\",\n      }),\n      params: ServerNotification__ItemGuardianApprovalReviewStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/autoApprovalReview/completed\").annotate({\n        title: \"Item/autoApprovalReview/completedNotificationMethod\",\n      }),\n      params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/completed\").annotate({\n        title: \"Item/completedNotificationMethod\",\n      }),\n      params: ServerNotification__ItemCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/agentMessage/delta\").annotate({\n        title: \"Item/agentMessage/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__AgentMessageDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/plan/delta\").annotate({\n        title: \"Item/plan/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__PlanDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"command/exec/outputDelta\").annotate({\n        title: \"Command/exec/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__CommandExecOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"process/outputDelta\").annotate({\n        title: \"Process/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__ProcessOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"process/exited\").annotate({\n        title: \"Process/exitedNotificationMethod\",\n      }),\n      params: ServerNotification__ProcessExitedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/commandExecution/outputDelta\").annotate({\n        title: \"Item/commandExecution/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__CommandExecutionOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/commandExecution/terminalInteraction\").annotate({\n        title: \"Item/commandExecution/terminalInteractionNotificationMethod\",\n      }),\n      params: ServerNotification__TerminalInteractionNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/fileChange/outputDelta\").annotate({\n        title: \"Item/fileChange/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__FileChangeOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/fileChange/patchUpdated\").annotate({\n        title: \"Item/fileChange/patchUpdatedNotificationMethod\",\n      }),\n      params: ServerNotification__FileChangePatchUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"serverRequest/resolved\").annotate({\n        title: \"ServerRequest/resolvedNotificationMethod\",\n      }),\n      params: ServerNotification__ServerRequestResolvedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/mcpToolCall/progress\").annotate({\n        title: \"Item/mcpToolCall/progressNotificationMethod\",\n      }),\n      params: ServerNotification__McpToolCallProgressNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"mcpServer/oauthLogin/completed\").annotate({\n        title: \"McpServer/oauthLogin/completedNotificationMethod\",\n      }),\n      params: ServerNotification__McpServerOauthLoginCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"mcpServer/startupStatus/updated\").annotate({\n        title: \"McpServer/startupStatus/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__McpServerStatusUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"account/updated\").annotate({\n        title: \"Account/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__AccountUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"account/rateLimits/updated\").annotate({\n        title: \"Account/rateLimits/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__AccountRateLimitsUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"app/list/updated\").annotate({\n        title: \"App/list/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__AppListUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"remoteControl/status/changed\").annotate({\n        title: \"RemoteControl/status/changedNotificationMethod\",\n      }),\n      params: ServerNotification__RemoteControlStatusChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"externalAgentConfig/import/progress\").annotate({\n        title: \"ExternalAgentConfig/import/progressNotificationMethod\",\n      }),\n      params: ServerNotification__ExternalAgentConfigImportProgressNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"externalAgentConfig/import/completed\").annotate({\n        title: \"ExternalAgentConfig/import/completedNotificationMethod\",\n      }),\n      params: ServerNotification__ExternalAgentConfigImportCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"fs/changed\").annotate({ title: \"Fs/changedNotificationMethod\" }),\n      params: ServerNotification__FsChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/reasoning/summaryTextDelta\").annotate({\n        title: \"Item/reasoning/summaryTextDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__ReasoningSummaryTextDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/reasoning/summaryPartAdded\").annotate({\n        title: \"Item/reasoning/summaryPartAddedNotificationMethod\",\n      }),\n      params: ServerNotification__ReasoningSummaryPartAddedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/reasoning/textDelta\").annotate({\n        title: \"Item/reasoning/textDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__ReasoningTextDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/compacted\").annotate({\n        title: \"Thread/compactedNotificationMethod\",\n      }),\n      params: ServerNotification__ContextCompactedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"model/rerouted\").annotate({\n        title: \"Model/reroutedNotificationMethod\",\n      }),\n      params: ServerNotification__ModelReroutedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"model/verification\").annotate({\n        title: \"Model/verificationNotificationMethod\",\n      }),\n      params: ServerNotification__ModelVerificationNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/moderationMetadata\").annotate({\n        title: \"Turn/moderationMetadataNotificationMethod\",\n      }),\n      params: ServerNotification__TurnModerationMetadataNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"model/safetyBuffering/updated\").annotate({\n        title: \"Model/safetyBuffering/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ModelSafetyBufferingUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"warning\").annotate({ title: \"WarningNotificationMethod\" }),\n      params: ServerNotification__WarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"guardianWarning\").annotate({\n        title: \"GuardianWarningNotificationMethod\",\n      }),\n      params: ServerNotification__GuardianWarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"deprecationNotice\").annotate({\n        title: \"DeprecationNoticeNotificationMethod\",\n      }),\n      params: ServerNotification__DeprecationNoticeNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"configWarning\").annotate({\n        title: \"ConfigWarningNotificationMethod\",\n      }),\n      params: ServerNotification__ConfigWarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"fuzzyFileSearch/sessionUpdated\").annotate({\n        title: \"FuzzyFileSearch/sessionUpdatedNotificationMethod\",\n      }),\n      params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"fuzzyFileSearch/sessionCompleted\").annotate({\n        title: \"FuzzyFileSearch/sessionCompletedNotificationMethod\",\n      }),\n      params: ServerNotification__FuzzyFileSearchSessionCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/started\").annotate({\n        title: \"Thread/realtime/startedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/itemAdded\").annotate({\n        title: \"Thread/realtime/itemAddedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeItemAddedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/transcript/delta\").annotate({\n        title: \"Thread/realtime/transcript/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeTranscriptDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/transcript/done\").annotate({\n        title: \"Thread/realtime/transcript/doneNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeTranscriptDoneNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/outputAudio/delta\").annotate({\n        title: \"Thread/realtime/outputAudio/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/sdp\").annotate({\n        title: \"Thread/realtime/sdpNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeSdpNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/error\").annotate({\n        title: \"Thread/realtime/errorNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeErrorNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/closed\").annotate({\n        title: \"Thread/realtime/closedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeClosedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"windows/worldWritableWarning\").annotate({\n        title: \"Windows/worldWritableWarningNotificationMethod\",\n      }),\n      params: ServerNotification__WindowsWorldWritableWarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"windowsSandbox/setupCompleted\").annotate({\n        title: \"WindowsSandbox/setupCompletedNotificationMethod\",\n      }),\n      params: ServerNotification__WindowsSandboxSetupCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"account/login/completed\").annotate({\n        title: \"Account/login/completedNotificationMethod\",\n      }),\n      params: ServerNotification__AccountLoginCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ByteRange = { readonly end: number; readonly start: number };\nexport const ServerNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type ServerNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const ServerNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type ServerNotification__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const ServerNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type ServerNotification__CommandExecOutputStream = \"stdout\" | \"stderr\";\nexport const ServerNotification__CommandExecOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `command/exec/outputDelta` notifications.\" });\n\nexport type ServerNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const ServerNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type ServerNotification__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const ServerNotification__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type ServerNotification__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const ServerNotification__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type ServerNotification__NetworkAccess = \"restricted\" | \"enabled\";\nexport const ServerNotification__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type ServerNotification__ProcessOutputStream = \"stdout\" | \"stderr\";\nexport const ServerNotification__ProcessOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `process/outputDelta` notifications.\" });\n\nexport type ServerNotification__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: ServerNotification__SubAgentSource };\nexport const ServerNotification__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ThreadExtra = {};\nexport const ServerNotification__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type ServerNotification__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const ServerNotification__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type ServerNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const ServerNotification__TurnItemsView = Schema.Literals([\"notLoaded\", \"summary\", \"full\"]);\n\nexport type ServerRequest =\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/commandExecution/requestApproval\";\n      readonly params: ServerRequest__CommandExecutionRequestApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/fileChange/requestApproval\";\n      readonly params: ServerRequest__FileChangeRequestApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/tool/requestUserInput\";\n      readonly params: ServerRequest__ToolRequestUserInputParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"mcpServer/elicitation/request\";\n      readonly params: ServerRequest__McpServerElicitationRequestParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/permissions/requestApproval\";\n      readonly params: ServerRequest__PermissionsRequestApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/tool/call\";\n      readonly params: ServerRequest__DynamicToolCallParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"account/chatgptAuthTokens/refresh\";\n      readonly params: ServerRequest__ChatgptAuthTokensRefreshParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"attestation/generate\";\n      readonly params: ServerRequest__AttestationGenerateParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"applyPatchApproval\";\n      readonly params: ServerRequest__ApplyPatchApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"execCommandApproval\";\n      readonly params: ServerRequest__ExecCommandApprovalParams;\n    };\nexport const ServerRequest = Schema.Union(\n  [\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/commandExecution/requestApproval\").annotate({\n        title: \"Item/commandExecution/requestApprovalRequestMethod\",\n      }),\n      params: ServerRequest__CommandExecutionRequestApprovalParams,\n    }).annotate({\n      title: \"Item/commandExecution/requestApprovalRequest\",\n      description:\n        \"NEW APIs Sent when approval is requested for a specific command execution. This request is used for Turns started via turn/start.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/fileChange/requestApproval\").annotate({\n        title: \"Item/fileChange/requestApprovalRequestMethod\",\n      }),\n      params: ServerRequest__FileChangeRequestApprovalParams,\n    }).annotate({\n      title: \"Item/fileChange/requestApprovalRequest\",\n      description:\n        \"Sent when approval is requested for a specific file change. This request is used for Turns started via turn/start.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/tool/requestUserInput\").annotate({\n        title: \"Item/tool/requestUserInputRequestMethod\",\n      }),\n      params: ServerRequest__ToolRequestUserInputParams,\n    }).annotate({\n      title: \"Item/tool/requestUserInputRequest\",\n      description: \"EXPERIMENTAL - Request input from the user for a tool call.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/elicitation/request\").annotate({\n        title: \"McpServer/elicitation/requestRequestMethod\",\n      }),\n      params: ServerRequest__McpServerElicitationRequestParams,\n    }).annotate({\n      title: \"McpServer/elicitation/requestRequest\",\n      description: \"Request input for an MCP server elicitation.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/permissions/requestApproval\").annotate({\n        title: \"Item/permissions/requestApprovalRequestMethod\",\n      }),\n      params: ServerRequest__PermissionsRequestApprovalParams,\n    }).annotate({\n      title: \"Item/permissions/requestApprovalRequest\",\n      description: \"Request approval for additional permissions from the user.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/tool/call\").annotate({ title: \"Item/tool/callRequestMethod\" }),\n      params: ServerRequest__DynamicToolCallParams,\n    }).annotate({\n      title: \"Item/tool/callRequest\",\n      description: \"Execute a dynamic tool call on the client.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"account/chatgptAuthTokens/refresh\").annotate({\n        title: \"Account/chatgptAuthTokens/refreshRequestMethod\",\n      }),\n      params: ServerRequest__ChatgptAuthTokensRefreshParams,\n    }).annotate({ title: \"Account/chatgptAuthTokens/refreshRequest\" }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"attestation/generate\").annotate({\n        title: \"Attestation/generateRequestMethod\",\n      }),\n      params: ServerRequest__AttestationGenerateParams,\n    }).annotate({\n      title: \"Attestation/generateRequest\",\n      description: \"Generate a fresh upstream attestation result on demand.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"applyPatchApproval\").annotate({\n        title: \"ApplyPatchApprovalRequestMethod\",\n      }),\n      params: ServerRequest__ApplyPatchApprovalParams,\n    }).annotate({\n      title: \"ApplyPatchApprovalRequest\",\n      description:\n        \"DEPRECATED APIs below Request to approve a patch. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"execCommandApproval\").annotate({\n        title: \"ExecCommandApprovalRequestMethod\",\n      }),\n      params: ServerRequest__ExecCommandApprovalParams,\n    }).annotate({\n      title: \"ExecCommandApprovalRequest\",\n      description:\n        \"Request to exec a command. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  title: \"ServerRequest\",\n  description: \"Request initiated from the server and sent to the client.\",\n});\n\nexport type ServerRequest__AdditionalPermissionProfile = {\n  readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null;\n  readonly network?: ServerRequest__AdditionalNetworkPermissions | null;\n};\nexport const ServerRequest__AdditionalPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]).annotate({\n      description: \"Partial overlay used for per-command permission requests.\",\n    }),\n  ),\n});\n\nexport type ServerRequest__CommandExecutionApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | {\n      readonly acceptWithExecpolicyAmendment: {\n        readonly execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | {\n      readonly applyNetworkPolicyAmendment: {\n        readonly network_policy_amendment: ServerRequest__NetworkPolicyAmendment;\n      };\n    }\n  | \"decline\"\n  | \"cancel\";\nexport const ServerRequest__CommandExecutionApprovalDecision = Schema.Union(\n  [\n    Schema.Literal(\"accept\").annotate({ description: \"User approved the command.\" }),\n    Schema.Literal(\"acceptForSession\").annotate({\n      description:\n        \"User approved the command and future prompts in the same session-scoped approval cache should run without prompting.\",\n    }),\n    Schema.Struct({\n      acceptWithExecpolicyAmendment: Schema.Struct({\n        execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision\",\n      description:\n        \"User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.\",\n    }),\n    Schema.Struct({\n      applyNetworkPolicyAmendment: Schema.Struct({\n        network_policy_amendment: ServerRequest__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision\",\n      description: \"User chose a persistent network policy rule (allow/deny) for this host.\",\n    }),\n    Schema.Literal(\"decline\").annotate({\n      description: \"User denied the command. The agent will continue the turn.\",\n    }),\n    Schema.Literal(\"cancel\").annotate({\n      description: \"User denied the command. The turn will also be immediately interrupted.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ToolRequestUserInputParams = {\n  readonly autoResolutionMs?: number | null;\n  readonly itemId: string;\n  readonly questions: ReadonlyArray<ToolRequestUserInputParams__ToolRequestUserInputQuestion>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ToolRequestUserInputParams = Schema.Struct({\n  autoResolutionMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  questions: Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputQuestion),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ToolRequestUserInputParams\",\n  description: \"EXPERIMENTAL. Params sent with a request_user_input event.\",\n});\n\nexport type ToolRequestUserInputResponse = {\n  readonly answers: {\n    readonly [x: string]: ToolRequestUserInputResponse__ToolRequestUserInputAnswer;\n  };\n};\nexport const ToolRequestUserInputResponse = Schema.Struct({\n  answers: Schema.Record(Schema.String, ToolRequestUserInputResponse__ToolRequestUserInputAnswer),\n}).annotate({\n  title: \"ToolRequestUserInputResponse\",\n  description: \"EXPERIMENTAL. Response payload mapping question ids to answers.\",\n});\n\nexport type V1InitializeParams = {\n  readonly capabilities?: V1InitializeParams__InitializeCapabilities | null;\n  readonly clientInfo: V1InitializeParams__ClientInfo;\n};\nexport const V1InitializeParams = Schema.Struct({\n  capabilities: Schema.optionalKey(\n    Schema.Union([V1InitializeParams__InitializeCapabilities, Schema.Null]),\n  ),\n  clientInfo: V1InitializeParams__ClientInfo,\n}).annotate({ title: \"InitializeParams\" });\n\nexport type V1InitializeResponse = {\n  readonly codexHome: string;\n  readonly platformFamily: string;\n  readonly platformOs: string;\n  readonly userAgent: string;\n};\nexport const V1InitializeResponse = Schema.Struct({\n  codexHome: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  platformFamily: Schema.String.annotate({\n    description:\n      'Platform family for the running app-server target, for example `\"unix\"` or `\"windows\"`.',\n  }),\n  platformOs: Schema.String.annotate({\n    description:\n      'Operating system for the running app-server target, for example `\"macos\"`, `\"linux\"`, or `\"windows\"`.',\n  }),\n  userAgent: Schema.String,\n}).annotate({ title: \"InitializeResponse\" });\n\nexport type V1InitializeResponse__AbsolutePathBuf = string;\nexport const V1InitializeResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2AccountLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly loginId?: string | null;\n  readonly success: boolean;\n};\nexport const V2AccountLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  success: Schema.Boolean,\n}).annotate({ title: \"AccountLoginCompletedNotification\" });\n\nexport type V2AccountRateLimitsUpdatedNotification = {\n  readonly rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot;\n};\nexport const V2AccountRateLimitsUpdatedNotification = Schema.Struct({\n  rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot,\n}).annotate({\n  title: \"AccountRateLimitsUpdatedNotification\",\n  description:\n    \"Sparse rolling rate-limit update.\\n\\nClients should merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and does not clear a previously observed value.\",\n});\n\nexport type V2AccountUpdatedNotification = {\n  readonly authMode?: V2AccountUpdatedNotification__AuthMode | null;\n  readonly planType?: V2AccountUpdatedNotification__PlanType | null;\n};\nexport const V2AccountUpdatedNotification = Schema.Struct({\n  authMode: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__AuthMode, Schema.Null])),\n  planType: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__PlanType, Schema.Null])),\n}).annotate({ title: \"AccountUpdatedNotification\" });\n\nexport type V2AgentMessageDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2AgentMessageDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"AgentMessageDeltaNotification\" });\n\nexport type V2AppListUpdatedNotification = {\n  readonly data: ReadonlyArray<V2AppListUpdatedNotification__AppInfo>;\n};\nexport const V2AppListUpdatedNotification = Schema.Struct({\n  data: Schema.Array(V2AppListUpdatedNotification__AppInfo),\n}).annotate({\n  title: \"AppListUpdatedNotification\",\n  description: \"EXPERIMENTAL - notification emitted when the app list changes.\",\n});\n\nexport type V2AppsInstalledParams = {\n  readonly forceRefresh?: boolean;\n  readonly threadId?: string | null;\n};\nexport const V2AppsInstalledParams = Schema.Struct({\n  forceRefresh: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true and Apps are permitted, refresh and publish the hosted connector runtime tool snapshot first.\",\n    }),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional loaded thread id used to evaluate effective app configuration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"AppsInstalledParams\",\n  description: \"Read the committed installed connector runtime snapshot.\",\n});\n\nexport type V2AppsInstalledResponse = {\n  readonly apps: ReadonlyArray<V2AppsInstalledResponse__InstalledApp>;\n};\nexport const V2AppsInstalledResponse = Schema.Struct({\n  apps: Schema.Array(V2AppsInstalledResponse__InstalledApp),\n}).annotate({\n  title: \"AppsInstalledResponse\",\n  description: \"The installed connectors in one committed runtime snapshot.\",\n});\n\nexport type V2AppsListParams = {\n  readonly cursor?: string | null;\n  readonly forceRefetch?: boolean;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const V2AppsListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  forceRefetch: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass app caches and fetch the latest data from sources.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional thread id used to evaluate app feature gating from that thread's config.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"AppsListParams\",\n  description: \"EXPERIMENTAL - list available apps/connectors.\",\n});\n\nexport type V2AppsListResponse = {\n  readonly data: ReadonlyArray<V2AppsListResponse__AppInfo>;\n  readonly nextCursor?: string | null;\n};\nexport const V2AppsListResponse = Schema.Struct({\n  data: Schema.Array(V2AppsListResponse__AppInfo),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"AppsListResponse\", description: \"EXPERIMENTAL - app list response.\" });\n\nexport type V2AppsReadParams = {\n  readonly appIds: ReadonlyArray<string>;\n  readonly includeTools?: boolean;\n};\nexport const V2AppsReadParams = Schema.Struct({\n  appIds: Schema.Array(Schema.String).annotate({\n    description:\n      \"App ids to read. The server accepts at most 100 ids and deduplicates repeated ids while preserving their first-request order.\",\n  }),\n  includeTools: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, include display-only public tool summaries in the returned metadata.\",\n    }),\n  ),\n}).annotate({\n  title: \"AppsReadParams\",\n  description: \"EXPERIMENTAL - read metadata for specific apps/connectors.\",\n});\n\nexport type V2AppsReadResponse = {\n  readonly apps: ReadonlyArray<V2AppsReadResponse__ConnectorMetadata>;\n  readonly missingAppIds: ReadonlyArray<string>;\n};\nexport const V2AppsReadResponse = Schema.Struct({\n  apps: Schema.Array(V2AppsReadResponse__ConnectorMetadata),\n  missingAppIds: Schema.Array(Schema.String),\n}).annotate({ title: \"AppsReadResponse\", description: \"EXPERIMENTAL - app/read response.\" });\n\nexport type V2CancelLoginAccountParams = { readonly loginId: string };\nexport const V2CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String }).annotate({\n  title: \"CancelLoginAccountParams\",\n});\n\nexport type V2CancelLoginAccountResponse = {\n  readonly status: V2CancelLoginAccountResponse__CancelLoginAccountStatus;\n};\nexport const V2CancelLoginAccountResponse = Schema.Struct({\n  status: V2CancelLoginAccountResponse__CancelLoginAccountStatus,\n}).annotate({ title: \"CancelLoginAccountResponse\" });\n\nexport type V2CommandExecOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processId: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const V2CommandExecOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `command/exec/outputDelta` notifications.\",\n  }),\n}).annotate({\n  title: \"CommandExecOutputDeltaNotification\",\n  description:\n    \"Base64-encoded output chunk emitted for a streaming `command/exec` request.\\n\\nThese notifications are connection-scoped. If the originating connection closes, the server terminates the process.\",\n});\n\nexport type V2CommandExecOutputDeltaNotification__CommandExecOutputStream = \"stdout\" | \"stderr\";\nexport const V2CommandExecOutputDeltaNotification__CommandExecOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `command/exec/outputDelta` notifications.\" });\n\nexport type V2CommandExecParams = {\n  readonly command: ReadonlyArray<string>;\n  readonly cwd?: string | null;\n  readonly disableOutputCap?: boolean;\n  readonly disableTimeout?: boolean;\n  readonly env?: { readonly [x: string]: string | null } | null;\n  readonly outputBytesCap?: number | null;\n  readonly processId?: string | null;\n  readonly sandboxPolicy?: V2CommandExecParams__SandboxPolicy | null;\n  readonly size?: V2CommandExecParams__CommandExecTerminalSize | null;\n  readonly streamStdin?: boolean;\n  readonly streamStdoutStderr?: boolean;\n  readonly timeoutMs?: number | null;\n  readonly tty?: boolean;\n};\nexport const V2CommandExecParams = Schema.Struct({\n  command: Schema.Array(Schema.String).annotate({\n    description: \"Command argv vector. Empty arrays are rejected.\",\n  }),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory. Defaults to the server cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  disableOutputCap: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable stdout/stderr capture truncation for this request.\\n\\nCannot be combined with `outputBytesCap`.\",\n    }),\n  ),\n  disableTimeout: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable the timeout entirely for this request.\\n\\nCannot be combined with `timeoutMs`.\",\n    }),\n  ),\n  env: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({\n        description:\n          \"Optional environment overrides merged into the server-computed environment.\\n\\nMatching names override inherited values. Set a key to `null` to unset an inherited variable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputBytesCap: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional per-stream stdout/stderr capture cap in bytes.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.\",\n        format: \"uint\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional client-supplied, connection-scoped process id.\\n\\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([V2CommandExecParams__SandboxPolicy, Schema.Null]).annotate({\n      description:\n        \"Optional sandbox policy for this command.\\n\\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted. Cannot be combined with `permissionProfile`.\",\n    }),\n  ),\n  size: Schema.optionalKey(\n    Schema.Union([V2CommandExecParams__CommandExecTerminalSize, Schema.Null]).annotate({\n      description: \"Optional initial PTY size in character cells. Only valid when `tty` is true.\",\n    }),\n  ),\n  streamStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Allow follow-up `command/exec/write` requests to write stdin bytes.\\n\\nRequires a client-supplied `processId`.\",\n    }),\n  ),\n  streamStdoutStderr: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Stream stdout/stderr via `command/exec/outputDelta` notifications.\\n\\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.\",\n    }),\n  ),\n  timeoutMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional timeout in milliseconds.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  tty: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Enable PTY mode.\\n\\nThis implies `streamStdin` and `streamStdoutStderr`.\",\n    }),\n  ),\n}).annotate({\n  title: \"CommandExecParams\",\n  description:\n    \"Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\\n\\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.\",\n});\n\nexport type V2CommandExecParams__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2CommandExecParams__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2CommandExecResizeParams = {\n  readonly processId: string;\n  readonly size: { readonly cols: number; readonly rows: number };\n};\nexport const V2CommandExecResizeParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  size: Schema.Struct({\n    cols: Schema.Number.annotate({\n      description: \"Terminal width in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    rows: Schema.Number.annotate({\n      description: \"Terminal height in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" }),\n}).annotate({\n  title: \"CommandExecResizeParams\",\n  description: \"Resize a running PTY-backed `command/exec` session.\",\n});\n\nexport type V2CommandExecResizeParams__CommandExecTerminalSize = {\n  readonly cols: number;\n  readonly rows: number;\n};\nexport const V2CommandExecResizeParams__CommandExecTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" });\n\nexport type V2CommandExecResizeResponse = {};\nexport const V2CommandExecResizeResponse = Schema.Struct({}).annotate({\n  title: \"CommandExecResizeResponse\",\n  description: \"Empty success response for `command/exec/resize`.\",\n});\n\nexport type V2CommandExecResponse = {\n  readonly exitCode: number;\n  readonly stderr: string;\n  readonly stdout: string;\n};\nexport const V2CommandExecResponse = Schema.Struct({\n  exitCode: Schema.Number.annotate({ description: \"Process exit code.\", format: \"int32\" }).check(\n    Schema.isInt(),\n  ),\n  stderr: Schema.String.annotate({\n    description:\n      \"Buffered stderr capture.\\n\\nEmpty when stderr was streamed via `command/exec/outputDelta`.\",\n  }),\n  stdout: Schema.String.annotate({\n    description:\n      \"Buffered stdout capture.\\n\\nEmpty when stdout was streamed via `command/exec/outputDelta`.\",\n  }),\n}).annotate({\n  title: \"CommandExecResponse\",\n  description: \"Final buffered result for `command/exec`.\",\n});\n\nexport type V2CommandExecTerminateParams = { readonly processId: string };\nexport const V2CommandExecTerminateParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({\n  title: \"CommandExecTerminateParams\",\n  description: \"Terminate a running `command/exec` session.\",\n});\n\nexport type V2CommandExecTerminateResponse = {};\nexport const V2CommandExecTerminateResponse = Schema.Struct({}).annotate({\n  title: \"CommandExecTerminateResponse\",\n  description: \"Empty success response for `command/exec/terminate`.\",\n});\n\nexport type V2CommandExecutionOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2CommandExecutionOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"CommandExecutionOutputDeltaNotification\" });\n\nexport type V2CommandExecWriteParams = {\n  readonly closeStdin?: boolean;\n  readonly deltaBase64?: string | null;\n  readonly processId: string;\n};\nexport const V2CommandExecWriteParams = Schema.Struct({\n  closeStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Close stdin after writing `deltaBase64`, if present.\",\n    }),\n  ),\n  deltaBase64: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional base64-encoded stdin bytes to write.\" }),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({\n  title: \"CommandExecWriteParams\",\n  description: \"Write stdin bytes to a running `command/exec` session, close stdin, or both.\",\n});\n\nexport type V2CommandExecWriteResponse = {};\nexport const V2CommandExecWriteResponse = Schema.Struct({}).annotate({\n  title: \"CommandExecWriteResponse\",\n  description: \"Empty success response for `command/exec/write`.\",\n});\n\nexport type V2ConfigBatchWriteParams = {\n  readonly edits: ReadonlyArray<V2ConfigBatchWriteParams__ConfigEdit>;\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly reloadUserConfig?: boolean;\n};\nexport const V2ConfigBatchWriteParams = Schema.Struct({\n  edits: Schema.Array(V2ConfigBatchWriteParams__ConfigEdit),\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reloadUserConfig: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, hot-reload the updated user config into all loaded threads after writing.\",\n    }),\n  ),\n}).annotate({ title: \"ConfigBatchWriteParams\" });\n\nexport type V2ConfigReadParams = { readonly cwd?: string | null; readonly includeLayers?: boolean };\nexport const V2ConfigReadParams = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeLayers: Schema.optionalKey(Schema.Boolean),\n}).annotate({ title: \"ConfigReadParams\" });\n\nexport type V2ConfigReadResponse = {\n  readonly config: V2ConfigReadResponse__Config;\n  readonly layers?: ReadonlyArray<V2ConfigReadResponse__ConfigLayer> | null;\n  readonly origins: { readonly [x: string]: V2ConfigReadResponse__ConfigLayerMetadata };\n};\nexport const V2ConfigReadResponse = Schema.Struct({\n  config: V2ConfigReadResponse__Config,\n  layers: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigReadResponse__ConfigLayer), Schema.Null]),\n  ),\n  origins: Schema.Record(Schema.String, V2ConfigReadResponse__ConfigLayerMetadata),\n}).annotate({ title: \"ConfigReadResponse\" });\n\nexport type V2ConfigReadResponse__AppConfig = {\n  readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;\n  readonly default_tools_approval_mode?: V2ConfigReadResponse__AppToolApproval | null;\n  readonly default_tools_enabled?: boolean | null;\n  readonly destructive_enabled?: boolean | null;\n  readonly enabled?: boolean;\n  readonly open_world_enabled?: boolean | null;\n  readonly tools?: V2ConfigReadResponse__AppToolsConfig | null;\n};\nexport const V2ConfigReadResponse__AppConfig = Schema.Struct({\n  approvals_reviewer: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]),\n  ),\n  default_tools_approval_mode: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),\n  ),\n  default_tools_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  destructive_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n  open_world_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__AppToolsConfig, Schema.Null])),\n});\n\nexport type V2ConfigReadResponse__AppsConfig = {\n  readonly _default?: V2ConfigReadResponse__AppsDefaultConfig | null;\n};\nexport const V2ConfigReadResponse__AppsConfig = Schema.Struct({\n  _default: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppsDefaultConfig, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigReadResponse__AppToolConfig = {\n  readonly approval_mode?: V2ConfigReadResponse__AppToolApproval | null;\n  readonly enabled?: boolean | null;\n};\nexport const V2ConfigReadResponse__AppToolConfig = Schema.Struct({\n  approval_mode: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),\n  ),\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse = {\n  readonly requirements?: V2ConfigRequirementsReadResponse__ConfigRequirements | null;\n};\nexport const V2ConfigRequirementsReadResponse = Schema.Struct({\n  requirements: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ConfigRequirements, Schema.Null]).annotate({\n      description:\n        \"Null if no requirements are configured (e.g. no requirements.toml/MDM entries).\",\n    }),\n  ),\n}).annotate({ title: \"ConfigRequirementsReadResponse\" });\n\nexport type V2ConfigRequirementsReadResponse__ApprovalsReviewer =\n  | \"user\"\n  | \"auto_review\"\n  | \"guardian_subagent\";\nexport const V2ConfigRequirementsReadResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ConfigRequirementsReadResponse__ManagedHooksRequirements = {\n  readonly PermissionRequest: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PostCompact: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PostToolUse: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PreCompact: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PreToolUse: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SessionEnd?: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SessionStart: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly Stop: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SubagentStart: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SubagentStop: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly UserPromptSubmit: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly managedDir?: string | null;\n  readonly windowsManagedDir?: string | null;\n};\nexport const V2ConfigRequirementsReadResponse__ManagedHooksRequirements = Schema.Struct({\n  PermissionRequest: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PostCompact: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PostToolUse: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PreCompact: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PreToolUse: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  SessionEnd: Schema.optionalKey(\n    Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup).annotate({\n      default: [],\n    }),\n  ),\n  SessionStart: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  Stop: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  SubagentStart: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  SubagentStop: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  UserPromptSubmit: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  managedDir: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  windowsManagedDir: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse__NetworkRequirements = {\n  readonly allowLocalBinding?: boolean | null;\n  readonly allowUnixSockets?: ReadonlyArray<string> | null;\n  readonly allowUpstreamProxy?: boolean | null;\n  readonly allowedDomains?: ReadonlyArray<string> | null;\n  readonly dangerouslyAllowAllUnixSockets?: boolean | null;\n  readonly dangerouslyAllowNonLoopbackProxy?: boolean | null;\n  readonly deniedDomains?: ReadonlyArray<string> | null;\n  readonly domains?: {\n    readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkDomainPermission;\n  } | null;\n  readonly enabled?: boolean | null;\n  readonly httpPort?: number | null;\n  readonly managedAllowedDomainsOnly?: boolean | null;\n  readonly socksPort?: number | null;\n  readonly unixSockets?: {\n    readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission;\n  } | null;\n};\nexport const V2ConfigRequirementsReadResponse__NetworkRequirements = Schema.Struct({\n  allowLocalBinding: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowUnixSockets: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Legacy compatibility view derived from `unix_sockets`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  allowUpstreamProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowedDomains: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Legacy compatibility view derived from `domains`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  dangerouslyAllowAllUnixSockets: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  dangerouslyAllowNonLoopbackProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  deniedDomains: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Legacy compatibility view derived from `domains`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  domains: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(\n        Schema.String,\n        V2ConfigRequirementsReadResponse__NetworkDomainPermission,\n      ).annotate({ description: \"Canonical network permission map for `experimental_network`.\" }),\n      Schema.Null,\n    ]),\n  ),\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  httpPort: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint16\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  managedAllowedDomainsOnly: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"When true, only managed allowlist entries are respected while managed network enforcement is active.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  socksPort: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint16\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  unixSockets: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(\n        Schema.String,\n        V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission,\n      ).annotate({\n        description: \"Canonical unix socket permission map for `experimental_network`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ConfigValueWriteParams = {\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly keyPath: string;\n  readonly mergeStrategy: V2ConfigValueWriteParams__MergeStrategy;\n  readonly value: unknown;\n};\nexport const V2ConfigValueWriteParams = Schema.Struct({\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  keyPath: Schema.String,\n  mergeStrategy: V2ConfigValueWriteParams__MergeStrategy,\n  value: Schema.Unknown,\n}).annotate({ title: \"ConfigValueWriteParams\" });\n\nexport type V2ConfigWarningNotification = {\n  readonly details?: string | null;\n  readonly path?: string | null;\n  readonly range?: V2ConfigWarningNotification__TextRange | null;\n  readonly summary: string;\n};\nexport const V2ConfigWarningNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional extra guidance or error details.\" }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional path to the config file that triggered the warning.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  range: Schema.optionalKey(\n    Schema.Union([V2ConfigWarningNotification__TextRange, Schema.Null]).annotate({\n      description: \"Optional range for the error location inside the config file.\",\n    }),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of the warning.\" }),\n}).annotate({ title: \"ConfigWarningNotification\" });\n\nexport type V2ConfigWriteResponse = {\n  readonly filePath: string;\n  readonly overriddenMetadata?: V2ConfigWriteResponse__OverriddenMetadata | null;\n  readonly status: V2ConfigWriteResponse__WriteStatus;\n  readonly version: string;\n};\nexport const V2ConfigWriteResponse = Schema.Struct({\n  filePath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  overriddenMetadata: Schema.optionalKey(\n    Schema.Union([V2ConfigWriteResponse__OverriddenMetadata, Schema.Null]),\n  ),\n  status: V2ConfigWriteResponse__WriteStatus,\n  version: Schema.String,\n}).annotate({ title: \"ConfigWriteResponse\" });\n\nexport type V2ConsumeAccountRateLimitResetCreditParams = {\n  readonly creditId?: string | null;\n  readonly idempotencyKey: string;\n};\nexport const V2ConsumeAccountRateLimitResetCreditParams = Schema.Struct({\n  creditId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque reset-credit identifier to redeem. When omitted, the backend selects the next available credit.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  idempotencyKey: Schema.String.annotate({\n    description:\n      \"Identifies one logical reset attempt. A UUID is recommended; reuse the same value when retrying that attempt.\",\n  }),\n}).annotate({ title: \"ConsumeAccountRateLimitResetCreditParams\" });\n\nexport type V2ConsumeAccountRateLimitResetCreditResponse = {\n  readonly outcome: V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome;\n};\nexport const V2ConsumeAccountRateLimitResetCreditResponse = Schema.Struct({\n  outcome: V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome,\n}).annotate({ title: \"ConsumeAccountRateLimitResetCreditResponse\" });\n\nexport type V2ContextCompactedNotification = { readonly threadId: string; readonly turnId: string };\nexport const V2ContextCompactedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ContextCompactedNotification\",\n  description: \"Deprecated: Use `ContextCompaction` item type instead.\",\n});\n\nexport type V2DeprecationNoticeNotification = {\n  readonly details?: string | null;\n  readonly summary: string;\n};\nexport const V2DeprecationNoticeNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional extra guidance, such as migration steps or rationale.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of what is deprecated.\" }),\n}).annotate({ title: \"DeprecationNoticeNotification\" });\n\nexport type V2EnvironmentConnectionNotification = {\n  readonly environmentId: string;\n  readonly threadId: string;\n};\nexport const V2EnvironmentConnectionNotification = Schema.Struct({\n  environmentId: Schema.String,\n  threadId: Schema.String,\n}).annotate({ title: \"EnvironmentConnectionNotification\" });\n\nexport type V2ErrorNotification = {\n  readonly error: V2ErrorNotification__TurnError;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly willRetry: boolean;\n};\nexport const V2ErrorNotification = Schema.Struct({\n  error: V2ErrorNotification__TurnError,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  willRetry: Schema.Boolean,\n}).annotate({ title: \"ErrorNotification\" });\n\nexport type V2ExperimentalFeatureEnablementSetParams = {\n  readonly enablement: { readonly [x: string]: boolean };\n};\nexport const V2ExperimentalFeatureEnablementSetParams = Schema.Struct({\n  enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({\n    description:\n      \"Process-wide runtime feature enablement keyed by canonical feature name.\\n\\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op.\",\n  }),\n}).annotate({ title: \"ExperimentalFeatureEnablementSetParams\" });\n\nexport type V2ExperimentalFeatureEnablementSetResponse = {\n  readonly enablement: { readonly [x: string]: boolean };\n};\nexport const V2ExperimentalFeatureEnablementSetResponse = Schema.Struct({\n  enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({\n    description: \"Feature enablement entries updated by this request.\",\n  }),\n}).annotate({ title: \"ExperimentalFeatureEnablementSetResponse\" });\n\nexport type V2ExperimentalFeatureListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const V2ExperimentalFeatureListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional loaded thread id. Pass this when showing feature state for an existing thread so enablement is computed from that thread's refreshed config, including project-local config for the thread's cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExperimentalFeatureListParams\" });\n\nexport type V2ExperimentalFeatureListResponse = {\n  readonly data: ReadonlyArray<V2ExperimentalFeatureListResponse__ExperimentalFeature>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ExperimentalFeatureListResponse = Schema.Struct({\n  data: Schema.Array(V2ExperimentalFeatureListResponse__ExperimentalFeature),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExperimentalFeatureListResponse\" });\n\nexport type V2ExperimentalFeatureListResponse__ExperimentalFeatureStage =\n  | \"beta\"\n  | \"underDevelopment\"\n  | \"stable\"\n  | \"deprecated\"\n  | \"removed\";\nexport const V2ExperimentalFeatureListResponse__ExperimentalFeatureStage = Schema.Literals([\n  \"beta\",\n  \"underDevelopment\",\n  \"stable\",\n  \"deprecated\",\n  \"removed\",\n]);\n\nexport type V2ExternalAgentConfigDetectParams = {\n  readonly cwds?: ReadonlyArray<string> | null;\n  readonly includeHome?: boolean;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const V2ExternalAgentConfigDetectParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Zero or more working directories to include for repo-scoped detection.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHome: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"If true, include detection under the user's home directory.\",\n    }),\n  ),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional migration-source selector. Missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Deprecated field retained for compatibility. This field is ignored; use `migrationSource` to select the migration source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExternalAgentConfigDetectParams\" });\n\nexport type V2ExternalAgentConfigDetectResponse = {\n  readonly items: ReadonlyArray<V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem>;\n};\nexport const V2ExternalAgentConfigDetectResponse = Schema.Struct({\n  items: Schema.Array(V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem),\n}).annotate({ title: \"ExternalAgentConfigDetectResponse\" });\n\nexport type V2ExternalAgentConfigImportCompletedNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const V2ExternalAgentConfigImportCompletedNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(\n    V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult,\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportCompletedNotification\" });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse = {\n  readonly connectors: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate>;\n  readonly data: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory>;\n};\nexport const V2ExternalAgentConfigImportHistoriesReadResponse = Schema.Struct({\n  connectors: Schema.Array(\n    V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate,\n  ),\n  data: Schema.Array(\n    V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory,\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportHistoriesReadResponse\" });\n\nexport type V2ExternalAgentConfigImportParams = {\n  readonly migrationItems: ReadonlyArray<V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem>;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const V2ExternalAgentConfigImportParams = Schema.Struct({\n  migrationItems: Schema.Array(V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Migration-source selector used to produce the migration items. Pass the same value to detection and import; missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional identifier for the product that initiated the import.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportParams\" });\n\nexport type V2ExternalAgentConfigImportProgressNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const V2ExternalAgentConfigImportProgressNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(\n    V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult,\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportProgressNotification\" });\n\nexport type V2ExternalAgentConfigImportResponse = { readonly importId: string };\nexport const V2ExternalAgentConfigImportResponse = Schema.Struct({\n  importId: Schema.String,\n}).annotate({ title: \"ExternalAgentConfigImportResponse\" });\n\nexport type V2FeedbackUploadParams = {\n  readonly classification: string;\n  readonly extraLogFiles?: ReadonlyArray<string> | null;\n  readonly includeLogs?: boolean;\n  readonly reason?: string | null;\n  readonly tags?: { readonly [x: string]: string } | null;\n  readonly threadId?: string | null;\n};\nexport const V2FeedbackUploadParams = Schema.Struct({\n  classification: Schema.String,\n  extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  includeLogs: Schema.optionalKey(Schema.Boolean),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tags: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"FeedbackUploadParams\" });\n\nexport type V2FeedbackUploadResponse = { readonly threadId: string };\nexport const V2FeedbackUploadResponse = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"FeedbackUploadResponse\",\n});\n\nexport type V2FileChangeOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2FileChangeOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"FileChangeOutputDeltaNotification\",\n  description:\n    \"Deprecated legacy notification for `apply_patch` textual output.\\n\\nThe server no longer emits this notification.\",\n});\n\nexport type V2FileChangePatchUpdatedNotification = {\n  readonly changes: ReadonlyArray<V2FileChangePatchUpdatedNotification__FileUpdateChange>;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2FileChangePatchUpdatedNotification = Schema.Struct({\n  changes: Schema.Array(V2FileChangePatchUpdatedNotification__FileUpdateChange),\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"FileChangePatchUpdatedNotification\" });\n\nexport type V2FsChangedNotification = {\n  readonly changedPaths: ReadonlyArray<V2FsChangedNotification__AbsolutePathBuf>;\n  readonly watchId: string;\n};\nexport const V2FsChangedNotification = Schema.Struct({\n  changedPaths: Schema.Array(V2FsChangedNotification__AbsolutePathBuf).annotate({\n    description: \"File or directory paths associated with this event.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({\n  title: \"FsChangedNotification\",\n  description: \"Filesystem watch notification emitted for `fs/watch` subscribers.\",\n});\n\nexport type V2FsCopyParams = {\n  readonly destinationPath: string;\n  readonly recursive?: boolean;\n  readonly sourcePath: string;\n};\nexport const V2FsCopyParams = Schema.Struct({\n  destinationPath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Required for directory copies; ignored for file copies.\",\n    }),\n  ),\n  sourcePath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({\n  title: \"FsCopyParams\",\n  description: \"Copy a file or directory tree on the host filesystem.\",\n});\n\nexport type V2FsCopyParams__AbsolutePathBuf = string;\nexport const V2FsCopyParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsCopyResponse = {};\nexport const V2FsCopyResponse = Schema.Struct({}).annotate({\n  title: \"FsCopyResponse\",\n  description: \"Successful response for `fs/copy`.\",\n});\n\nexport type V2FsCreateDirectoryParams = {\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const V2FsCreateDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether parent directories should also be created. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"FsCreateDirectoryParams\",\n  description: \"Create a directory on the host filesystem.\",\n});\n\nexport type V2FsCreateDirectoryParams__AbsolutePathBuf = string;\nexport const V2FsCreateDirectoryParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsCreateDirectoryResponse = {};\nexport const V2FsCreateDirectoryResponse = Schema.Struct({}).annotate({\n  title: \"FsCreateDirectoryResponse\",\n  description: \"Successful response for `fs/createDirectory`.\",\n});\n\nexport type V2FsGetMetadataParams = { readonly path: string };\nexport const V2FsGetMetadataParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({\n  title: \"FsGetMetadataParams\",\n  description: \"Request metadata for an absolute path.\",\n});\n\nexport type V2FsGetMetadataParams__AbsolutePathBuf = string;\nexport const V2FsGetMetadataParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsGetMetadataResponse = {\n  readonly createdAtMs: number;\n  readonly isDirectory: boolean;\n  readonly isFile: boolean;\n  readonly isSymlink: boolean;\n  readonly modifiedAtMs: number;\n};\nexport const V2FsGetMetadataResponse = Schema.Struct({\n  createdAtMs: Schema.Number.annotate({\n    description: \"File creation time in Unix milliseconds when available, otherwise `0`.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  isDirectory: Schema.Boolean.annotate({\n    description: \"Whether the path resolves to a directory.\",\n  }),\n  isFile: Schema.Boolean.annotate({ description: \"Whether the path resolves to a regular file.\" }),\n  isSymlink: Schema.Boolean.annotate({\n    description: \"Whether the path itself is a symbolic link.\",\n  }),\n  modifiedAtMs: Schema.Number.annotate({\n    description: \"File modification time in Unix milliseconds when available, otherwise `0`.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n}).annotate({\n  title: \"FsGetMetadataResponse\",\n  description: \"Metadata returned by `fs/getMetadata`.\",\n});\n\nexport type V2FsReadDirectoryParams = { readonly path: string };\nexport const V2FsReadDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({\n  title: \"FsReadDirectoryParams\",\n  description: \"List direct child names for a directory.\",\n});\n\nexport type V2FsReadDirectoryParams__AbsolutePathBuf = string;\nexport const V2FsReadDirectoryParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsReadDirectoryResponse = {\n  readonly entries: ReadonlyArray<V2FsReadDirectoryResponse__FsReadDirectoryEntry>;\n};\nexport const V2FsReadDirectoryResponse = Schema.Struct({\n  entries: Schema.Array(V2FsReadDirectoryResponse__FsReadDirectoryEntry).annotate({\n    description: \"Direct child entries in the requested directory.\",\n  }),\n}).annotate({\n  title: \"FsReadDirectoryResponse\",\n  description: \"Directory entries returned by `fs/readDirectory`.\",\n});\n\nexport type V2FsReadFileParams = { readonly path: string };\nexport const V2FsReadFileParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ title: \"FsReadFileParams\", description: \"Read a file from the host filesystem.\" });\n\nexport type V2FsReadFileParams__AbsolutePathBuf = string;\nexport const V2FsReadFileParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsReadFileResponse = { readonly dataBase64: string };\nexport const V2FsReadFileResponse = Schema.Struct({\n  dataBase64: Schema.String.annotate({ description: \"File contents encoded as base64.\" }),\n}).annotate({\n  title: \"FsReadFileResponse\",\n  description: \"Base64-encoded file contents returned by `fs/readFile`.\",\n});\n\nexport type V2FsRemoveParams = {\n  readonly force?: boolean | null;\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const V2FsRemoveParams = Schema.Struct({\n  force: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether missing paths should be ignored. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether directory removal should recurse. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"FsRemoveParams\",\n  description: \"Remove a file or directory tree from the host filesystem.\",\n});\n\nexport type V2FsRemoveParams__AbsolutePathBuf = string;\nexport const V2FsRemoveParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsRemoveResponse = {};\nexport const V2FsRemoveResponse = Schema.Struct({}).annotate({\n  title: \"FsRemoveResponse\",\n  description: \"Successful response for `fs/remove`.\",\n});\n\nexport type V2FsUnwatchParams = { readonly watchId: string };\nexport const V2FsUnwatchParams = Schema.Struct({\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({\n  title: \"FsUnwatchParams\",\n  description: \"Stop filesystem watch notifications for a prior `fs/watch`.\",\n});\n\nexport type V2FsUnwatchResponse = {};\nexport const V2FsUnwatchResponse = Schema.Struct({}).annotate({\n  title: \"FsUnwatchResponse\",\n  description: \"Successful response for `fs/unwatch`.\",\n});\n\nexport type V2FsWatchParams = { readonly path: string; readonly watchId: string };\nexport const V2FsWatchParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.\",\n  }),\n}).annotate({\n  title: \"FsWatchParams\",\n  description: \"Start filesystem watch notifications for an absolute path.\",\n});\n\nexport type V2FsWatchParams__AbsolutePathBuf = string;\nexport const V2FsWatchParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsWatchResponse = { readonly path: string };\nexport const V2FsWatchResponse = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ title: \"FsWatchResponse\", description: \"Successful response for `fs/watch`.\" });\n\nexport type V2FsWatchResponse__AbsolutePathBuf = string;\nexport const V2FsWatchResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsWriteFileParams = { readonly dataBase64: string; readonly path: string };\nexport const V2FsWriteFileParams = Schema.Struct({\n  dataBase64: Schema.String.annotate({ description: \"File contents encoded as base64.\" }),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ title: \"FsWriteFileParams\", description: \"Write a file on the host filesystem.\" });\n\nexport type V2FsWriteFileParams__AbsolutePathBuf = string;\nexport const V2FsWriteFileParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsWriteFileResponse = {};\nexport const V2FsWriteFileResponse = Schema.Struct({}).annotate({\n  title: \"FsWriteFileResponse\",\n  description: \"Successful response for `fs/writeFile`.\",\n});\n\nexport type V2GetAccountParams = { readonly refreshToken?: boolean };\nexport const V2GetAccountParams = Schema.Struct({\n  refreshToken: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When `true`, requests a proactive token refresh before returning.\\n\\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.\",\n    }),\n  ),\n}).annotate({ title: \"GetAccountParams\" });\n\nexport type V2GetAccountRateLimitsResponse = {\n  readonly rateLimitResetCredits?: V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary | null;\n  readonly rateLimits: {\n    readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null;\n    readonly individualLimit?: V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot | null;\n    readonly limitId?: string | null;\n    readonly limitName?: string | null;\n    readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null;\n    readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n    readonly rateLimitReachedType?: V2GetAccountRateLimitsResponse__RateLimitReachedType | null;\n    readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n    readonly spendControlReached?: boolean | null;\n  };\n  readonly rateLimitsByLimitId?: {\n    readonly [x: string]: V2GetAccountRateLimitsResponse__RateLimitSnapshot;\n  } | null;\n};\nexport const V2GetAccountRateLimitsResponse = Schema.Struct({\n  rateLimitResetCredits: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary, Schema.Null]),\n  ),\n  rateLimits: Schema.Struct({\n    credits: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]),\n    ),\n    individualLimit: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot, Schema.Null]),\n    ),\n    limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    planType: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]),\n    ),\n    primary: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n    ),\n    rateLimitReachedType: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__RateLimitReachedType, Schema.Null]),\n    ),\n    secondary: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n    ),\n    spendControlReached: Schema.optionalKey(\n      Schema.Union([\n        Schema.Boolean.annotate({\n          description:\n            \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n  }).annotate({\n    description: \"Backward-compatible single-bucket view; mirrors the historical payload.\",\n  }),\n  rateLimitsByLimitId: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, V2GetAccountRateLimitsResponse__RateLimitSnapshot).annotate({\n        description: \"Multi-bucket view keyed by metered `limit_id` (for example, `codex`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"GetAccountRateLimitsResponse\" });\n\nexport type V2GetAccountResponse = {\n  readonly account?: V2GetAccountResponse__Account | null;\n  readonly requiresOpenaiAuth: boolean;\n};\nexport const V2GetAccountResponse = Schema.Struct({\n  account: Schema.optionalKey(Schema.Union([V2GetAccountResponse__Account, Schema.Null])),\n  requiresOpenaiAuth: Schema.Boolean,\n}).annotate({ title: \"GetAccountResponse\" });\n\nexport type V2GetAccountTokenUsageResponse = {\n  readonly dailyUsageBuckets?: ReadonlyArray<V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket> | null;\n  readonly summary: V2GetAccountTokenUsageResponse__AccountTokenUsageSummary;\n};\nexport const V2GetAccountTokenUsageResponse = Schema.Struct({\n  dailyUsageBuckets: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket),\n      Schema.Null,\n    ]),\n  ),\n  summary: V2GetAccountTokenUsageResponse__AccountTokenUsageSummary,\n}).annotate({ title: \"GetAccountTokenUsageResponse\" });\n\nexport type V2GetWorkspaceMessagesResponse = {\n  readonly featureEnabled: boolean;\n  readonly messages: ReadonlyArray<V2GetWorkspaceMessagesResponse__WorkspaceMessage>;\n};\nexport const V2GetWorkspaceMessagesResponse = Schema.Struct({\n  featureEnabled: Schema.Boolean.annotate({\n    description: \"Whether the workspace-message backend route is available for this client.\",\n  }),\n  messages: Schema.Array(V2GetWorkspaceMessagesResponse__WorkspaceMessage).annotate({\n    description: \"Active workspace messages returned by the backend.\",\n  }),\n}).annotate({ title: \"GetWorkspaceMessagesResponse\" });\n\nexport type V2GuardianWarningNotification = { readonly message: string; readonly threadId: string };\nexport const V2GuardianWarningNotification = Schema.Struct({\n  message: Schema.String.annotate({\n    description: \"Concise guardian warning message for the user.\",\n  }),\n  threadId: Schema.String.annotate({ description: \"Thread target for the guardian warning.\" }),\n}).annotate({ title: \"GuardianWarningNotification\" });\n\nexport type V2HookCompletedNotification = {\n  readonly run: V2HookCompletedNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const V2HookCompletedNotification = Schema.Struct({\n  run: V2HookCompletedNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"HookCompletedNotification\" });\n\nexport type V2HookCompletedNotification__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const V2HookCompletedNotification__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type V2HooksListParams = { readonly cwds?: ReadonlyArray<string> };\nexport const V2HooksListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n}).annotate({ title: \"HooksListParams\" });\n\nexport type V2HooksListResponse = {\n  readonly data: ReadonlyArray<V2HooksListResponse__HooksListEntry>;\n};\nexport const V2HooksListResponse = Schema.Struct({\n  data: Schema.Array(V2HooksListResponse__HooksListEntry),\n}).annotate({ title: \"HooksListResponse\" });\n\nexport type V2HookStartedNotification = {\n  readonly run: V2HookStartedNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const V2HookStartedNotification = Schema.Struct({\n  run: V2HookStartedNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"HookStartedNotification\" });\n\nexport type V2HookStartedNotification__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const V2HookStartedNotification__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type V2ItemCompletedNotification = {\n  readonly completedAtMs: number;\n  readonly item: V2ItemCompletedNotification__ThreadItem;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemCompletedNotification = Schema.Struct({\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  item: V2ItemCompletedNotification__ThreadItem,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ItemCompletedNotification\" });\n\nexport type V2ItemCompletedNotification__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2ItemCompletedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ItemCompletedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ItemCompletedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ItemCompletedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemCompletedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ItemCompletedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification = {\n  readonly action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction;\n  readonly completedAtMs: number;\n  readonly decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource;\n  readonly review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({\n  action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction,\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource,\n  review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ItemGuardianApprovalReviewCompletedNotification\",\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type V2ItemGuardianApprovalReviewStartedNotification = {\n  readonly action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction;\n  readonly review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification = Schema.Struct({\n  action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction,\n  review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ItemGuardianApprovalReviewStartedNotification\",\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type V2ItemStartedNotification = {\n  readonly item: V2ItemStartedNotification__ThreadItem;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemStartedNotification = Schema.Struct({\n  item: V2ItemStartedNotification__ThreadItem,\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ItemStartedNotification\" });\n\nexport type V2ItemStartedNotification__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ItemStartedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ItemStartedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ItemStartedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ItemStartedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemStartedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemStartedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ItemStartedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ListMcpServerStatusParams = {\n  readonly cursor?: string | null;\n  readonly detail?: V2ListMcpServerStatusParams__McpServerStatusDetail | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const V2ListMcpServerStatusParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  detail: Schema.optionalKey(\n    Schema.Union([V2ListMcpServerStatusParams__McpServerStatusDetail, Schema.Null]).annotate({\n      description:\n        \"Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a server-defined value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ListMcpServerStatusParams\" });\n\nexport type V2ListMcpServerStatusResponse = {\n  readonly data: ReadonlyArray<V2ListMcpServerStatusResponse__McpServerStatus>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ListMcpServerStatusResponse = Schema.Struct({\n  data: Schema.Array(V2ListMcpServerStatusResponse__McpServerStatus),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ListMcpServerStatusResponse\" });\n\nexport type V2LoginAccountParams =\n  | { readonly apiKey: string; readonly type: \"apiKey\" }\n  | {\n      readonly appBrand?: V2LoginAccountParams__LoginAppBrand | null;\n      readonly codexStreamlinedLogin?: boolean;\n      readonly type: \"chatgpt\";\n      readonly useHostedLoginSuccessPage?: boolean;\n    }\n  | { readonly type: \"chatgptDeviceCode\" }\n  | {\n      readonly accessToken: string;\n      readonly chatgptAccountId: string;\n      readonly chatgptPlanType?: string | null;\n      readonly type: \"chatgptAuthTokens\";\n    }\n  | { readonly apiKey: string; readonly region: string; readonly type: \"amazonBedrock\" };\nexport const V2LoginAccountParams = Schema.Union(\n  [\n    Schema.Struct({\n      apiKey: Schema.String,\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyv2::LoginAccountParamsType\" }),\n    }).annotate({ title: \"ApiKeyv2::LoginAccountParams\" }),\n    Schema.Struct({\n      appBrand: Schema.optionalKey(\n        Schema.Union([V2LoginAccountParams__LoginAppBrand, Schema.Null]),\n      ),\n      codexStreamlinedLogin: Schema.optionalKey(Schema.Boolean),\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"Chatgptv2::LoginAccountParamsType\" }),\n      useHostedLoginSuccessPage: Schema.optionalKey(Schema.Boolean),\n    }).annotate({ title: \"Chatgptv2::LoginAccountParams\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"chatgptDeviceCode\").annotate({\n        title: \"ChatgptDeviceCodev2::LoginAccountParamsType\",\n      }),\n    }).annotate({ title: \"ChatgptDeviceCodev2::LoginAccountParams\" }),\n    Schema.Struct({\n      accessToken: Schema.String.annotate({\n        description:\n          \"Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.\",\n      }),\n      chatgptAccountId: Schema.String.annotate({\n        description: \"Workspace/account identifier supplied by the client.\",\n      }),\n      chatgptPlanType: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional plan type supplied by the client.\\n\\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"chatgptAuthTokens\").annotate({\n        title: \"ChatgptAuthTokensv2::LoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"ChatgptAuthTokensv2::LoginAccountParams\",\n      description:\n        \"[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.\",\n    }),\n    Schema.Struct({\n      apiKey: Schema.String,\n      region: Schema.String,\n      type: Schema.Literal(\"amazonBedrock\").annotate({\n        title: \"AmazonBedrockv2::LoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"AmazonBedrockv2::LoginAccountParams\",\n      description: \"[UNSTABLE] Managed Amazon Bedrock login is experimental.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"LoginAccountParams\" });\n\nexport type V2LoginAccountResponse =\n  | { readonly type: \"apiKey\" }\n  | { readonly authUrl: string; readonly loginId: string; readonly type: \"chatgpt\" }\n  | {\n      readonly loginId: string;\n      readonly type: \"chatgptDeviceCode\";\n      readonly userCode: string;\n      readonly verificationUrl: string;\n    }\n  | { readonly type: \"chatgptAuthTokens\" }\n  | { readonly type: \"amazonBedrock\" };\nexport const V2LoginAccountResponse = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyv2::LoginAccountResponseType\" }),\n    }).annotate({ title: \"ApiKeyv2::LoginAccountResponse\" }),\n    Schema.Struct({\n      authUrl: Schema.String.annotate({\n        description: \"URL the client should open in a browser to initiate the OAuth flow.\",\n      }),\n      loginId: Schema.String,\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"Chatgptv2::LoginAccountResponseType\" }),\n    }).annotate({ title: \"Chatgptv2::LoginAccountResponse\" }),\n    Schema.Struct({\n      loginId: Schema.String,\n      type: Schema.Literal(\"chatgptDeviceCode\").annotate({\n        title: \"ChatgptDeviceCodev2::LoginAccountResponseType\",\n      }),\n      userCode: Schema.String.annotate({\n        description: \"One-time code the user must enter after signing in.\",\n      }),\n      verificationUrl: Schema.String.annotate({\n        description:\n          \"URL the client should open in a browser to complete device code authorization.\",\n      }),\n    }).annotate({ title: \"ChatgptDeviceCodev2::LoginAccountResponse\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"chatgptAuthTokens\").annotate({\n        title: \"ChatgptAuthTokensv2::LoginAccountResponseType\",\n      }),\n    }).annotate({ title: \"ChatgptAuthTokensv2::LoginAccountResponse\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"amazonBedrock\").annotate({\n        title: \"AmazonBedrockv2::LoginAccountResponseType\",\n      }),\n    }).annotate({ title: \"AmazonBedrockv2::LoginAccountResponse\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"LoginAccountResponse\" });\n\nexport type V2LogoutAccountResponse = {};\nexport const V2LogoutAccountResponse = Schema.Struct({}).annotate({\n  title: \"LogoutAccountResponse\",\n});\n\nexport type V2MarketplaceAddParams = {\n  readonly refName?: string | null;\n  readonly source: string;\n  readonly sparsePaths?: ReadonlyArray<string> | null;\n};\nexport const V2MarketplaceAddParams = Schema.Struct({\n  refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  source: Schema.String,\n  sparsePaths: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n}).annotate({ title: \"MarketplaceAddParams\" });\n\nexport type V2MarketplaceAddResponse = {\n  readonly alreadyAdded: boolean;\n  readonly installedRoot: V2MarketplaceAddResponse__AbsolutePathBuf;\n  readonly marketplaceName: string;\n};\nexport const V2MarketplaceAddResponse = Schema.Struct({\n  alreadyAdded: Schema.Boolean,\n  installedRoot: V2MarketplaceAddResponse__AbsolutePathBuf,\n  marketplaceName: Schema.String,\n}).annotate({ title: \"MarketplaceAddResponse\" });\n\nexport type V2MarketplaceRemoveParams = { readonly marketplaceName: string };\nexport const V2MarketplaceRemoveParams = Schema.Struct({ marketplaceName: Schema.String }).annotate(\n  { title: \"MarketplaceRemoveParams\" },\n);\n\nexport type V2MarketplaceRemoveResponse = {\n  readonly installedRoot?: V2MarketplaceRemoveResponse__AbsolutePathBuf | null;\n  readonly marketplaceName: string;\n};\nexport const V2MarketplaceRemoveResponse = Schema.Struct({\n  installedRoot: Schema.optionalKey(\n    Schema.Union([V2MarketplaceRemoveResponse__AbsolutePathBuf, Schema.Null]),\n  ),\n  marketplaceName: Schema.String,\n}).annotate({ title: \"MarketplaceRemoveResponse\" });\n\nexport type V2MarketplaceUpgradeParams = { readonly marketplaceName?: string | null };\nexport const V2MarketplaceUpgradeParams = Schema.Struct({\n  marketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"MarketplaceUpgradeParams\" });\n\nexport type V2MarketplaceUpgradeResponse = {\n  readonly errors: ReadonlyArray<V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo>;\n  readonly selectedMarketplaces: ReadonlyArray<string>;\n  readonly upgradedRoots: ReadonlyArray<V2MarketplaceUpgradeResponse__AbsolutePathBuf>;\n};\nexport const V2MarketplaceUpgradeResponse = Schema.Struct({\n  errors: Schema.Array(V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo),\n  selectedMarketplaces: Schema.Array(Schema.String),\n  upgradedRoots: Schema.Array(V2MarketplaceUpgradeResponse__AbsolutePathBuf),\n}).annotate({ title: \"MarketplaceUpgradeResponse\" });\n\nexport type V2McpResourceReadParams = {\n  readonly server: string;\n  readonly threadId?: string | null;\n  readonly uri: string;\n};\nexport const V2McpResourceReadParams = Schema.Struct({\n  server: Schema.String,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({ title: \"McpResourceReadParams\" });\n\nexport type V2McpResourceReadResponse = {\n  readonly contents: ReadonlyArray<V2McpResourceReadResponse__ResourceContent>;\n};\nexport const V2McpResourceReadResponse = Schema.Struct({\n  contents: Schema.Array(V2McpResourceReadResponse__ResourceContent),\n}).annotate({ title: \"McpResourceReadResponse\" });\n\nexport type V2McpServerOauthLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly name: string;\n  readonly success: boolean;\n  readonly threadId?: string | null;\n};\nexport const V2McpServerOauthLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  success: Schema.Boolean,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"McpServerOauthLoginCompletedNotification\" });\n\nexport type V2McpServerOauthLoginParams = {\n  readonly name: string;\n  readonly scopes?: ReadonlyArray<string> | null;\n  readonly threadId?: string | null;\n  readonly timeoutSecs?: number | null;\n};\nexport const V2McpServerOauthLoginParams = Schema.Struct({\n  name: Schema.String,\n  scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timeoutSecs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n}).annotate({ title: \"McpServerOauthLoginParams\" });\n\nexport type V2McpServerOauthLoginResponse = { readonly authorizationUrl: string };\nexport const V2McpServerOauthLoginResponse = Schema.Struct({\n  authorizationUrl: Schema.String,\n}).annotate({ title: \"McpServerOauthLoginResponse\" });\n\nexport type V2McpServerRefreshResponse = {};\nexport const V2McpServerRefreshResponse = Schema.Struct({}).annotate({\n  title: \"McpServerRefreshResponse\",\n});\n\nexport type V2McpServerStatusUpdatedNotification = {\n  readonly error?: string | null;\n  readonly failureReason?: V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason | null;\n  readonly name: string;\n  readonly status: V2McpServerStatusUpdatedNotification__McpServerStartupState;\n  readonly threadId?: string | null;\n};\nexport const V2McpServerStatusUpdatedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  failureReason: Schema.optionalKey(\n    Schema.Union([\n      V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason,\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String,\n  status: V2McpServerStatusUpdatedNotification__McpServerStartupState,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"McpServerStatusUpdatedNotification\" });\n\nexport type V2McpServerToolCallParams = {\n  readonly _meta?: unknown;\n  readonly arguments?: unknown;\n  readonly server: string;\n  readonly threadId: string;\n  readonly tool: string;\n};\nexport const V2McpServerToolCallParams = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  arguments: Schema.optionalKey(Schema.Unknown),\n  server: Schema.String,\n  threadId: Schema.String,\n  tool: Schema.String,\n}).annotate({ title: \"McpServerToolCallParams\" });\n\nexport type V2McpServerToolCallResponse = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly isError?: boolean | null;\n  readonly structuredContent?: unknown;\n};\nexport const V2McpServerToolCallResponse = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  isError: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n}).annotate({ title: \"McpServerToolCallResponse\" });\n\nexport type V2McpToolCallProgressNotification = {\n  readonly itemId: string;\n  readonly message: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2McpToolCallProgressNotification = Schema.Struct({\n  itemId: Schema.String,\n  message: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"McpToolCallProgressNotification\" });\n\nexport type V2ModelListParams = {\n  readonly cursor?: string | null;\n  readonly includeHidden?: boolean | null;\n  readonly limit?: number | null;\n};\nexport const V2ModelListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHidden: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"When true, include models that are hidden from the default picker list.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ModelListParams\" });\n\nexport type V2ModelListResponse = {\n  readonly data: ReadonlyArray<V2ModelListResponse__Model>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ModelListResponse = Schema.Struct({\n  data: Schema.Array(V2ModelListResponse__Model),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ModelListResponse\" });\n\nexport type V2ModelProviderCapabilitiesReadParams = {};\nexport const V2ModelProviderCapabilitiesReadParams = Schema.Struct({}).annotate({\n  title: \"ModelProviderCapabilitiesReadParams\",\n});\n\nexport type V2ModelProviderCapabilitiesReadResponse = {\n  readonly imageGeneration: boolean;\n  readonly namespaceTools: boolean;\n  readonly webSearch: boolean;\n};\nexport const V2ModelProviderCapabilitiesReadResponse = Schema.Struct({\n  imageGeneration: Schema.Boolean,\n  namespaceTools: Schema.Boolean,\n  webSearch: Schema.Boolean,\n}).annotate({ title: \"ModelProviderCapabilitiesReadResponse\" });\n\nexport type V2ModelReroutedNotification = {\n  readonly fromModel: string;\n  readonly reason: V2ModelReroutedNotification__ModelRerouteReason;\n  readonly threadId: string;\n  readonly toModel: string;\n  readonly turnId: string;\n};\nexport const V2ModelReroutedNotification = Schema.Struct({\n  fromModel: Schema.String,\n  reason: V2ModelReroutedNotification__ModelRerouteReason,\n  threadId: Schema.String,\n  toModel: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ModelReroutedNotification\" });\n\nexport type V2ModelSafetyBufferingUpdatedNotification = {\n  readonly fasterModel?: string | null;\n  readonly model: string;\n  readonly reasons: ReadonlyArray<string>;\n  readonly showBufferingUi: boolean;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly useCases: ReadonlyArray<string>;\n};\nexport const V2ModelSafetyBufferingUpdatedNotification = Schema.Struct({\n  fasterModel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasons: Schema.Array(Schema.String),\n  showBufferingUi: Schema.Boolean,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  useCases: Schema.Array(Schema.String),\n}).annotate({ title: \"ModelSafetyBufferingUpdatedNotification\" });\n\nexport type V2ModelVerificationNotification = {\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly verifications: ReadonlyArray<V2ModelVerificationNotification__ModelVerification>;\n};\nexport const V2ModelVerificationNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n  verifications: Schema.Array(V2ModelVerificationNotification__ModelVerification),\n}).annotate({ title: \"ModelVerificationNotification\" });\n\nexport type V2PermissionProfileListParams = {\n  readonly cursor?: string | null;\n  readonly cwd?: string | null;\n  readonly limit?: number | null;\n};\nexport const V2PermissionProfileListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory to resolve project config layers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to the full result set.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PermissionProfileListParams\" });\n\nexport type V2PermissionProfileListResponse = {\n  readonly data: ReadonlyArray<V2PermissionProfileListResponse__PermissionProfileSummary>;\n  readonly nextCursor?: string | null;\n};\nexport const V2PermissionProfileListResponse = Schema.Struct({\n  data: Schema.Array(V2PermissionProfileListResponse__PermissionProfileSummary),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PermissionProfileListResponse\" });\n\nexport type V2PlanDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2PlanDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"PlanDeltaNotification\",\n  description:\n    \"EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.\",\n});\n\nexport type V2PluginInstalledParams = {\n  readonly cwds?: ReadonlyArray<V2PluginInstalledParams__AbsolutePathBuf> | null;\n  readonly installSuggestionPluginNames?: ReadonlyArray<string> | null;\n};\nexport const V2PluginInstalledParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2PluginInstalledParams__AbsolutePathBuf).annotate({\n        description: \"Optional working directories used to discover repo marketplaces.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  installSuggestionPluginNames: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Additional uninstalled plugin names that should be returned when present locally. This is used by mention surfaces that intentionally expose install entrypoints.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PluginInstalledParams\" });\n\nexport type V2PluginInstalledResponse = {\n  readonly marketplaceLoadErrors?: ReadonlyArray<V2PluginInstalledResponse__MarketplaceLoadErrorInfo>;\n  readonly marketplaces: ReadonlyArray<V2PluginInstalledResponse__PluginMarketplaceEntry>;\n};\nexport const V2PluginInstalledResponse = Schema.Struct({\n  marketplaceLoadErrors: Schema.optionalKey(\n    Schema.Array(V2PluginInstalledResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }),\n  ),\n  marketplaces: Schema.Array(V2PluginInstalledResponse__PluginMarketplaceEntry),\n}).annotate({ title: \"PluginInstalledResponse\" });\n\nexport type V2PluginInstalledResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginInstalledResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginInstallParams = {\n  readonly marketplacePath?: V2PluginInstallParams__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const V2PluginInstallParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(\n    Schema.Union([V2PluginInstallParams__AbsolutePathBuf, Schema.Null]),\n  ),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginInstallParams\" });\n\nexport type V2PluginInstallResponse = {\n  readonly appsNeedingAuth: ReadonlyArray<V2PluginInstallResponse__AppSummary>;\n  readonly authPolicy: V2PluginInstallResponse__PluginAuthPolicy;\n};\nexport const V2PluginInstallResponse = Schema.Struct({\n  appsNeedingAuth: Schema.Array(V2PluginInstallResponse__AppSummary),\n  authPolicy: V2PluginInstallResponse__PluginAuthPolicy,\n}).annotate({ title: \"PluginInstallResponse\" });\n\nexport type V2PluginListParams = {\n  readonly cwds?: ReadonlyArray<V2PluginListParams__AbsolutePathBuf> | null;\n  readonly marketplaceKinds?: ReadonlyArray<V2PluginListParams__PluginListMarketplaceKind> | null;\n};\nexport const V2PluginListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2PluginListParams__AbsolutePathBuf).annotate({\n        description:\n          \"Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  marketplaceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2PluginListParams__PluginListMarketplaceKind).annotate({\n        description:\n          \"Optional marketplace kind filter. When omitted, only local marketplaces are queried, plus the default remote catalog when enabled by feature flag.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PluginListParams\" });\n\nexport type V2PluginListResponse = {\n  readonly featuredPluginIds?: ReadonlyArray<string>;\n  readonly marketplaceLoadErrors?: ReadonlyArray<V2PluginListResponse__MarketplaceLoadErrorInfo>;\n  readonly marketplaces: ReadonlyArray<V2PluginListResponse__PluginMarketplaceEntry>;\n};\nexport const V2PluginListResponse = Schema.Struct({\n  featuredPluginIds: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  marketplaceLoadErrors: Schema.optionalKey(\n    Schema.Array(V2PluginListResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }),\n  ),\n  marketplaces: Schema.Array(V2PluginListResponse__PluginMarketplaceEntry),\n}).annotate({ title: \"PluginListResponse\" });\n\nexport type V2PluginListResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginListResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginReadParams = {\n  readonly marketplacePath?: V2PluginReadParams__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const V2PluginReadParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(\n    Schema.Union([V2PluginReadParams__AbsolutePathBuf, Schema.Null]),\n  ),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginReadParams\" });\n\nexport type V2PluginReadResponse = { readonly plugin: V2PluginReadResponse__PluginDetail };\nexport const V2PluginReadResponse = Schema.Struct({\n  plugin: V2PluginReadResponse__PluginDetail,\n}).annotate({ title: \"PluginReadResponse\" });\n\nexport type V2PluginReadResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginReadResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginShareCheckoutParams = { readonly remotePluginId: string };\nexport const V2PluginShareCheckoutParams = Schema.Struct({\n  remotePluginId: Schema.String,\n}).annotate({ title: \"PluginShareCheckoutParams\" });\n\nexport type V2PluginShareCheckoutResponse = {\n  readonly marketplaceName: string;\n  readonly marketplacePath: V2PluginShareCheckoutResponse__AbsolutePathBuf;\n  readonly pluginId: string;\n  readonly pluginName: string;\n  readonly pluginPath: V2PluginShareCheckoutResponse__AbsolutePathBuf;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n};\nexport const V2PluginShareCheckoutResponse = Schema.Struct({\n  marketplaceName: Schema.String,\n  marketplacePath: V2PluginShareCheckoutResponse__AbsolutePathBuf,\n  pluginId: Schema.String,\n  pluginName: Schema.String,\n  pluginPath: V2PluginShareCheckoutResponse__AbsolutePathBuf,\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginShareCheckoutResponse\" });\n\nexport type V2PluginShareDeleteParams = { readonly remotePluginId: string };\nexport const V2PluginShareDeleteParams = Schema.Struct({ remotePluginId: Schema.String }).annotate({\n  title: \"PluginShareDeleteParams\",\n});\n\nexport type V2PluginShareDeleteResponse = {};\nexport const V2PluginShareDeleteResponse = Schema.Struct({}).annotate({\n  title: \"PluginShareDeleteResponse\",\n});\n\nexport type V2PluginShareListParams = {};\nexport const V2PluginShareListParams = Schema.Struct({}).annotate({\n  title: \"PluginShareListParams\",\n});\n\nexport type V2PluginShareListResponse = {\n  readonly data: ReadonlyArray<V2PluginShareListResponse__PluginShareListItem>;\n};\nexport const V2PluginShareListResponse = Schema.Struct({\n  data: Schema.Array(V2PluginShareListResponse__PluginShareListItem),\n}).annotate({ title: \"PluginShareListResponse\" });\n\nexport type V2PluginShareListResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginShareListResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginShareSaveParams = {\n  readonly discoverability?: V2PluginShareSaveParams__PluginShareDiscoverability | null;\n  readonly pluginPath: V2PluginShareSaveParams__AbsolutePathBuf;\n  readonly remotePluginId?: string | null;\n  readonly shareTargets?: ReadonlyArray<V2PluginShareSaveParams__PluginShareTarget> | null;\n};\nexport const V2PluginShareSaveParams = Schema.Struct({\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginShareSaveParams__PluginShareDiscoverability, Schema.Null]),\n  ),\n  pluginPath: V2PluginShareSaveParams__AbsolutePathBuf,\n  remotePluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  shareTargets: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginShareSaveParams__PluginShareTarget), Schema.Null]),\n  ),\n}).annotate({ title: \"PluginShareSaveParams\" });\n\nexport type V2PluginShareSaveResponse = {\n  readonly remotePluginId: string;\n  readonly shareUrl: string;\n};\nexport const V2PluginShareSaveResponse = Schema.Struct({\n  remotePluginId: Schema.String,\n  shareUrl: Schema.String,\n}).annotate({ title: \"PluginShareSaveResponse\" });\n\nexport type V2PluginShareUpdateTargetsParams = {\n  readonly discoverability: V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability;\n  readonly remotePluginId: string;\n  readonly shareTargets: ReadonlyArray<V2PluginShareUpdateTargetsParams__PluginShareTarget>;\n};\nexport const V2PluginShareUpdateTargetsParams = Schema.Struct({\n  discoverability: V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability,\n  remotePluginId: Schema.String,\n  shareTargets: Schema.Array(V2PluginShareUpdateTargetsParams__PluginShareTarget),\n}).annotate({ title: \"PluginShareUpdateTargetsParams\" });\n\nexport type V2PluginShareUpdateTargetsResponse = {\n  readonly discoverability: V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability;\n  readonly principals: ReadonlyArray<V2PluginShareUpdateTargetsResponse__PluginSharePrincipal>;\n};\nexport const V2PluginShareUpdateTargetsResponse = Schema.Struct({\n  discoverability: V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability,\n  principals: Schema.Array(V2PluginShareUpdateTargetsResponse__PluginSharePrincipal),\n}).annotate({ title: \"PluginShareUpdateTargetsResponse\" });\n\nexport type V2PluginSkillReadParams = {\n  readonly remoteMarketplaceName: string;\n  readonly remotePluginId: string;\n  readonly skillName: string;\n};\nexport const V2PluginSkillReadParams = Schema.Struct({\n  remoteMarketplaceName: Schema.String,\n  remotePluginId: Schema.String,\n  skillName: Schema.String,\n}).annotate({ title: \"PluginSkillReadParams\" });\n\nexport type V2PluginSkillReadResponse = { readonly contents?: string | null };\nexport const V2PluginSkillReadResponse = Schema.Struct({\n  contents: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginSkillReadResponse\" });\n\nexport type V2PluginUninstallParams = { readonly pluginId: string };\nexport const V2PluginUninstallParams = Schema.Struct({ pluginId: Schema.String }).annotate({\n  title: \"PluginUninstallParams\",\n});\n\nexport type V2PluginUninstallResponse = {};\nexport const V2PluginUninstallResponse = Schema.Struct({}).annotate({\n  title: \"PluginUninstallResponse\",\n});\n\nexport type V2ProcessExitedNotification = {\n  readonly exitCode: number;\n  readonly processHandle: string;\n  readonly stderr: string;\n  readonly stderrCapReached: boolean;\n  readonly stdout: string;\n  readonly stdoutCapReached: boolean;\n};\nexport const V2ProcessExitedNotification = Schema.Struct({\n  exitCode: Schema.Number.annotate({ description: \"Process exit code.\", format: \"int32\" }).check(\n    Schema.isInt(),\n  ),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stderr: Schema.String.annotate({\n    description:\n      \"Buffered stderr capture.\\n\\nEmpty when stderr was streamed via `process/outputDelta`.\",\n  }),\n  stderrCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stderr reached `outputBytesCap`.\\n\\nIn streaming mode, stderr is empty and cap state is also reported on the final stderr `process/outputDelta` notification.\",\n  }),\n  stdout: Schema.String.annotate({\n    description:\n      \"Buffered stdout capture.\\n\\nEmpty when stdout was streamed via `process/outputDelta`.\",\n  }),\n  stdoutCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stdout reached `outputBytesCap`.\\n\\nIn streaming mode, stdout is empty and cap state is also reported on the final stdout `process/outputDelta` notification.\",\n  }),\n}).annotate({\n  title: \"ProcessExitedNotification\",\n  description: \"Final process exit notification for `process/spawn`.\",\n});\n\nexport type V2ProcessOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processHandle: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const V2ProcessOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"True on the final streamed chunk for this stream when output was truncated by `outputBytesCap`.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `process/outputDelta` notifications.\",\n  }),\n}).annotate({\n  title: \"ProcessOutputDeltaNotification\",\n  description: \"Base64-encoded output chunk emitted for a streaming `process/spawn` request.\",\n});\n\nexport type V2ProcessOutputDeltaNotification__ProcessOutputStream = \"stdout\" | \"stderr\";\nexport const V2ProcessOutputDeltaNotification__ProcessOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `process/outputDelta` notifications.\" });\n\nexport type V2RawResponseCompletedNotification = {\n  readonly responseId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly usage?: V2RawResponseCompletedNotification__TokenUsageBreakdown | null;\n};\nexport const V2RawResponseCompletedNotification = Schema.Struct({\n  responseId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  usage: Schema.optionalKey(\n    Schema.Union([V2RawResponseCompletedNotification__TokenUsageBreakdown, Schema.Null]),\n  ),\n}).annotate({\n  title: \"RawResponseCompletedNotification\",\n  description:\n    \"Internal-only notification containing the exact usage from one upstream Responses API completion.\",\n});\n\nexport type V2RawResponseItemCompletedNotification = {\n  readonly item: V2RawResponseItemCompletedNotification__ResponseItem;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2RawResponseItemCompletedNotification = Schema.Struct({\n  item: V2RawResponseItemCompletedNotification__ResponseItem,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"RawResponseItemCompletedNotification\" });\n\nexport type V2ReasoningSummaryPartAddedNotification = {\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ReasoningSummaryPartAddedNotification = Schema.Struct({\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ReasoningSummaryPartAddedNotification\" });\n\nexport type V2ReasoningSummaryTextDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ReasoningSummaryTextDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ReasoningSummaryTextDeltaNotification\" });\n\nexport type V2ReasoningTextDeltaNotification = {\n  readonly contentIndex: number;\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ReasoningTextDeltaNotification = Schema.Struct({\n  contentIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ReasoningTextDeltaNotification\" });\n\nexport type V2RemoteControlStatusChangedNotification = {\n  readonly environmentId?: string | null;\n  readonly installationId: string;\n  readonly serverName: string;\n  readonly status: V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus;\n};\nexport const V2RemoteControlStatusChangedNotification = Schema.Struct({\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  installationId: Schema.String,\n  serverName: Schema.String,\n  status: V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus,\n}).annotate({\n  title: \"RemoteControlStatusChangedNotification\",\n  description: \"Current remote-control connection status and remote identity exposed to clients.\",\n});\n\nexport type V2ReviewStartParams = {\n  readonly delivery?: V2ReviewStartParams__ReviewDelivery | null;\n  readonly target: V2ReviewStartParams__ReviewTarget;\n  readonly threadId: string;\n};\nexport const V2ReviewStartParams = Schema.Struct({\n  delivery: Schema.optionalKey(\n    Schema.Union([V2ReviewStartParams__ReviewDelivery, Schema.Null]).annotate({\n      description:\n        \"Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).\",\n    }),\n  ),\n  target: V2ReviewStartParams__ReviewTarget,\n  threadId: Schema.String,\n}).annotate({ title: \"ReviewStartParams\" });\n\nexport type V2ReviewStartResponse = {\n  readonly reviewThreadId: string;\n  readonly turn: V2ReviewStartResponse__Turn;\n};\nexport const V2ReviewStartResponse = Schema.Struct({\n  reviewThreadId: Schema.String.annotate({\n    description:\n      \"Identifies the thread where the review runs.\\n\\nFor inline reviews, this is the original thread id. For detached reviews, this is the id of the new review thread.\",\n  }),\n  turn: V2ReviewStartResponse__Turn,\n}).annotate({ title: \"ReviewStartResponse\" });\n\nexport type V2ReviewStartResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ReviewStartResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ReviewStartResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ReviewStartResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ReviewStartResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ReviewStartResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ReviewStartResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ReviewStartResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ReviewStartResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ReviewStartResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2SendAddCreditsNudgeEmailParams = {\n  readonly creditType: V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType;\n};\nexport const V2SendAddCreditsNudgeEmailParams = Schema.Struct({\n  creditType: V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType,\n}).annotate({ title: \"SendAddCreditsNudgeEmailParams\" });\n\nexport type V2SendAddCreditsNudgeEmailResponse = {\n  readonly status: V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus;\n};\nexport const V2SendAddCreditsNudgeEmailResponse = Schema.Struct({\n  status: V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus,\n}).annotate({ title: \"SendAddCreditsNudgeEmailResponse\" });\n\nexport type V2ServerRequestResolvedNotification = {\n  readonly requestId: V2ServerRequestResolvedNotification__RequestId;\n  readonly threadId: string;\n};\nexport const V2ServerRequestResolvedNotification = Schema.Struct({\n  requestId: V2ServerRequestResolvedNotification__RequestId,\n  threadId: Schema.String,\n}).annotate({ title: \"ServerRequestResolvedNotification\" });\n\nexport type V2SkillsChangedNotification = {};\nexport const V2SkillsChangedNotification = Schema.Struct({}).annotate({\n  title: \"SkillsChangedNotification\",\n  description:\n    \"Notification emitted when watched local skill files change.\\n\\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.\",\n});\n\nexport type V2SkillsConfigWriteParams = {\n  readonly enabled: boolean;\n  readonly name?: string | null;\n  readonly path?: V2SkillsConfigWriteParams__AbsolutePathBuf | null;\n};\nexport const V2SkillsConfigWriteParams = Schema.Struct({\n  enabled: Schema.Boolean,\n  name: Schema.optionalKey(\n    Schema.Union([Schema.String.annotate({ description: \"Name-based selector.\" }), Schema.Null]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([V2SkillsConfigWriteParams__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Path-based selector.\",\n    }),\n  ),\n}).annotate({ title: \"SkillsConfigWriteParams\" });\n\nexport type V2SkillsConfigWriteResponse = { readonly effectiveEnabled: boolean };\nexport const V2SkillsConfigWriteResponse = Schema.Struct({\n  effectiveEnabled: Schema.Boolean,\n}).annotate({ title: \"SkillsConfigWriteResponse\" });\n\nexport type V2SkillsExtraRootsSetParams = {\n  readonly extraRoots: ReadonlyArray<V2SkillsExtraRootsSetParams__AbsolutePathBuf>;\n};\nexport const V2SkillsExtraRootsSetParams = Schema.Struct({\n  extraRoots: Schema.Array(V2SkillsExtraRootsSetParams__AbsolutePathBuf),\n}).annotate({ title: \"SkillsExtraRootsSetParams\" });\n\nexport type V2SkillsExtraRootsSetResponse = {};\nexport const V2SkillsExtraRootsSetResponse = Schema.Struct({}).annotate({\n  title: \"SkillsExtraRootsSetResponse\",\n});\n\nexport type V2SkillsListParams = {\n  readonly cwds?: ReadonlyArray<string>;\n  readonly forceReload?: boolean;\n};\nexport const V2SkillsListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n  forceReload: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass the skills cache and re-scan skills from disk.\",\n    }),\n  ),\n}).annotate({ title: \"SkillsListParams\" });\n\nexport type V2SkillsListResponse = {\n  readonly data: ReadonlyArray<V2SkillsListResponse__SkillsListEntry>;\n};\nexport const V2SkillsListResponse = Schema.Struct({\n  data: Schema.Array(V2SkillsListResponse__SkillsListEntry),\n}).annotate({ title: \"SkillsListResponse\" });\n\nexport type V2TerminalInteractionNotification = {\n  readonly itemId: string;\n  readonly processId: string;\n  readonly stdin: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TerminalInteractionNotification = Schema.Struct({\n  itemId: Schema.String,\n  processId: Schema.String,\n  stdin: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TerminalInteractionNotification\" });\n\nexport type V2ThreadApproveGuardianDeniedActionParams = {\n  readonly event: unknown;\n  readonly threadId: string;\n};\nexport const V2ThreadApproveGuardianDeniedActionParams = Schema.Struct({\n  event: Schema.Unknown.annotate({\n    description: \"Serialized `codex_protocol::protocol::GuardianAssessmentEvent`.\",\n  }),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadApproveGuardianDeniedActionParams\" });\n\nexport type V2ThreadApproveGuardianDeniedActionResponse = {};\nexport const V2ThreadApproveGuardianDeniedActionResponse = Schema.Struct({}).annotate({\n  title: \"ThreadApproveGuardianDeniedActionResponse\",\n});\n\nexport type V2ThreadArchivedNotification = { readonly threadId: string };\nexport const V2ThreadArchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadArchivedNotification\",\n});\n\nexport type V2ThreadArchiveParams = { readonly threadId: string };\nexport const V2ThreadArchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadArchiveParams\",\n});\n\nexport type V2ThreadArchiveResponse = {};\nexport const V2ThreadArchiveResponse = Schema.Struct({}).annotate({\n  title: \"ThreadArchiveResponse\",\n});\n\nexport type V2ThreadClosedNotification = { readonly threadId: string };\nexport const V2ThreadClosedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadClosedNotification\",\n});\n\nexport type V2ThreadCompactStartParams = { readonly threadId: string };\nexport const V2ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadCompactStartParams\",\n});\n\nexport type V2ThreadCompactStartResponse = {};\nexport const V2ThreadCompactStartResponse = Schema.Struct({}).annotate({\n  title: \"ThreadCompactStartResponse\",\n});\n\nexport type V2ThreadDeletedNotification = { readonly threadId: string };\nexport const V2ThreadDeletedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadDeletedNotification\",\n});\n\nexport type V2ThreadDeleteParams = { readonly threadId: string };\nexport const V2ThreadDeleteParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadDeleteParams\",\n});\n\nexport type V2ThreadDeleteResponse = {};\nexport const V2ThreadDeleteResponse = Schema.Struct({}).annotate({ title: \"ThreadDeleteResponse\" });\n\nexport type V2ThreadForkParams = {\n  readonly approvalPolicy?: V2ThreadForkParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2ThreadForkParams__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean;\n  readonly lastTurnId?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly sandbox?: V2ThreadForkParams__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n  readonly threadSource?: V2ThreadForkParams__ThreadSource | null;\n};\nexport const V2ThreadForkParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2ThreadForkParams__AskForApproval, Schema.Null]),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2ThreadForkParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n  lastTurnId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional last turn id to fork through, inclusive.\\n\\nWhen specified, turns after `last_turn_id` are omitted from the fork. The referenced turn cannot be in progress.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the forked thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([V2ThreadForkParams__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadForkParams__ThreadSource, Schema.Null]).annotate({\n      description:\n        \"Optional client-supplied analytics source classification for this forked thread.\",\n    }),\n  ),\n}).annotate({\n  title: \"ThreadForkParams\",\n  description:\n    \"There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\\n\\nIf using a non-empty path, the thread_id param will be ignored. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type V2ThreadForkParams__AbsolutePathBuf = string;\nexport const V2ThreadForkParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadForkResponse = {\n  readonly approvalPolicy: V2ThreadForkResponse__AskForApproval;\n  readonly approvalsReviewer: \"user\" | \"auto_review\" | \"guardian_subagent\";\n  readonly cwd: V2ThreadForkResponse__AbsolutePathBuf;\n  readonly instructionSources?: ReadonlyArray<V2ThreadForkResponse__LegacyAppPathString>;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null;\n  readonly sandbox:\n    | { readonly type: \"dangerFullAccess\" }\n    | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n    | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n    | {\n        readonly excludeSlashTmp?: boolean;\n        readonly excludeTmpdirEnvVar?: boolean;\n        readonly networkAccess?: boolean;\n        readonly type: \"workspaceWrite\";\n        readonly writableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;\n      };\n  readonly serviceTier?: string | null;\n  readonly thread: V2ThreadForkResponse__Thread;\n};\nexport const V2ThreadForkResponse = Schema.Struct({\n  approvalPolicy: V2ThreadForkResponse__AskForApproval,\n  approvalsReviewer: Schema.Literals([\"user\", \"auto_review\", \"guardian_subagent\"]).annotate({\n    description:\n      \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n  }),\n  cwd: V2ThreadForkResponse__AbsolutePathBuf,\n  instructionSources: Schema.optionalKey(\n    Schema.Array(V2ThreadForkResponse__LegacyAppPathString).annotate({\n      description:\n        \"Environment-native paths to instruction source files currently loaded for this thread.\",\n      default: [],\n    }),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  reasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]),\n  ),\n  sandbox: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"dangerFullAccess\").annotate({\n          title: \"DangerFullAccessSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n      }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(\n          Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n        ),\n        type: Schema.Literal(\"externalSandbox\").annotate({\n          title: \"ExternalSandboxSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n      Schema.Struct({\n        excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"workspaceWrite\").annotate({\n          title: \"WorkspaceWriteSandboxPolicyType\",\n        }),\n        writableRoots: Schema.optionalKey(\n          Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),\n        ),\n      }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance.\",\n  }),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  thread: V2ThreadForkResponse__Thread,\n}).annotate({ title: \"ThreadForkResponse\" });\n\nexport type V2ThreadForkResponse__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadForkResponse__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadForkResponse__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadForkResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadForkResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadForkResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadForkResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadForkResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadForkResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadForkResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadForkResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadForkResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadForkResponse__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadForkResponse__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadForkResponse__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadForkResponse__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2ThreadForkResponse__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;\n    };\nexport const V2ThreadForkResponse__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadForkResponse__SubAgentSource };\nexport const V2ThreadForkResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__ThreadExtra = {};\nexport const V2ThreadForkResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadForkResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadForkResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadForkResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadForkResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadForkResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadForkResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadGoalClearedNotification = { readonly threadId: string };\nexport const V2ThreadGoalClearedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadGoalClearedNotification\",\n});\n\nexport type V2ThreadGoalClearParams = { readonly threadId: string };\nexport const V2ThreadGoalClearParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadGoalClearParams\",\n});\n\nexport type V2ThreadGoalClearResponse = { readonly cleared: boolean };\nexport const V2ThreadGoalClearResponse = Schema.Struct({ cleared: Schema.Boolean }).annotate({\n  title: \"ThreadGoalClearResponse\",\n});\n\nexport type V2ThreadGoalGetParams = { readonly threadId: string };\nexport const V2ThreadGoalGetParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadGoalGetParams\",\n});\n\nexport type V2ThreadGoalGetResponse = {\n  readonly goal?: V2ThreadGoalGetResponse__ThreadGoal | null;\n};\nexport const V2ThreadGoalGetResponse = Schema.Struct({\n  goal: Schema.optionalKey(Schema.Union([V2ThreadGoalGetResponse__ThreadGoal, Schema.Null])),\n}).annotate({ title: \"ThreadGoalGetResponse\" });\n\nexport type V2ThreadGoalSetParams = {\n  readonly objective?: string | null;\n  readonly status?: V2ThreadGoalSetParams__ThreadGoalStatus | null;\n  readonly threadId: string;\n  readonly tokenBudget?: number | null;\n};\nexport const V2ThreadGoalSetParams = Schema.Struct({\n  objective: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: Schema.optionalKey(Schema.Union([V2ThreadGoalSetParams__ThreadGoalStatus, Schema.Null])),\n  threadId: Schema.String,\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n}).annotate({ title: \"ThreadGoalSetParams\" });\n\nexport type V2ThreadGoalSetResponse = { readonly goal: V2ThreadGoalSetResponse__ThreadGoal };\nexport const V2ThreadGoalSetResponse = Schema.Struct({\n  goal: V2ThreadGoalSetResponse__ThreadGoal,\n}).annotate({ title: \"ThreadGoalSetResponse\" });\n\nexport type V2ThreadGoalUpdatedNotification = {\n  readonly goal: V2ThreadGoalUpdatedNotification__ThreadGoal;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const V2ThreadGoalUpdatedNotification = Schema.Struct({\n  goal: V2ThreadGoalUpdatedNotification__ThreadGoal,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ThreadGoalUpdatedNotification\" });\n\nexport type V2ThreadInjectItemsParams = {\n  readonly items: ReadonlyArray<unknown>;\n  readonly threadId: string;\n};\nexport const V2ThreadInjectItemsParams = Schema.Struct({\n  items: Schema.Array(Schema.Unknown).annotate({\n    description: \"Raw Responses API items to append to the thread's model-visible history.\",\n  }),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadInjectItemsParams\" });\n\nexport type V2ThreadInjectItemsResponse = {};\nexport const V2ThreadInjectItemsResponse = Schema.Struct({}).annotate({\n  title: \"ThreadInjectItemsResponse\",\n});\n\nexport type V2ThreadListParams = {\n  readonly archived?: boolean | null;\n  readonly cursor?: string | null;\n  readonly cwd?: V2ThreadListParams__ThreadListCwdFilter | null;\n  readonly limit?: number | null;\n  readonly modelProviders?: ReadonlyArray<string> | null;\n  readonly searchTerm?: string | null;\n  readonly sortDirection?: V2ThreadListParams__SortDirection | null;\n  readonly sortKey?: V2ThreadListParams__ThreadSortKey | null;\n  readonly sourceKinds?: ReadonlyArray<V2ThreadListParams__ThreadSourceKind> | null;\n  readonly useStateDbOnly?: boolean;\n};\nexport const V2ThreadListParams = Schema.Struct({\n  archived: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([V2ThreadListParams__ThreadListCwdFilter, Schema.Null]).annotate({\n      description:\n        \"Optional cwd filter or filters; when set, only threads whose session cwd exactly matches one of these paths are returned.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  modelProviders: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  searchTerm: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional substring filter for the extracted thread title.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([V2ThreadListParams__SortDirection, Schema.Null]).annotate({\n      description: \"Optional sort direction; defaults to descending (newest first).\",\n    }),\n  ),\n  sortKey: Schema.optionalKey(\n    Schema.Union([V2ThreadListParams__ThreadSortKey, Schema.Null]).annotate({\n      description: \"Optional sort key; defaults to created_at.\",\n    }),\n  ),\n  sourceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2ThreadListParams__ThreadSourceKind).annotate({\n        description:\n          \"Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  useStateDbOnly: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"If true, return from the state DB without scanning JSONL rollouts to repair thread metadata. Omitted or false preserves scan-and-repair behavior.\",\n    }),\n  ),\n}).annotate({ title: \"ThreadListParams\" });\n\nexport type V2ThreadListResponse = {\n  readonly backwardsCursor?: string | null;\n  readonly data: ReadonlyArray<V2ThreadListResponse__Thread>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ThreadListResponse = Schema.Struct({\n  backwardsCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass as `cursor` when reversing `sortDirection`. This is only populated when the page contains at least one thread. Use it with the opposite `sortDirection`; for timestamp sorts it anchors at the start of the page timestamp so same-second updates are not skipped.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  data: Schema.Array(V2ThreadListResponse__Thread),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ThreadListResponse\" });\n\nexport type V2ThreadListResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadListResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadListResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadListResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadListResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadListResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadListResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadListResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadListResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadListResponse__SubAgentSource };\nexport const V2ThreadListResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__ThreadExtra = {};\nexport const V2ThreadListResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadListResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadListResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadListResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadListResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadListResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadListResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadLoadedListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n};\nexport const V2ThreadLoadedListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to no limit.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ThreadLoadedListParams\" });\n\nexport type V2ThreadLoadedListResponse = {\n  readonly data: ReadonlyArray<string>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ThreadLoadedListResponse = Schema.Struct({\n  data: Schema.Array(Schema.String).annotate({\n    description: \"Thread ids for sessions currently loaded in memory.\",\n  }),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ThreadLoadedListResponse\" });\n\nexport type V2ThreadMetadataUpdateParams = {\n  readonly gitInfo?: V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams | null;\n  readonly threadId: string;\n};\nexport const V2ThreadMetadataUpdateParams = Schema.Struct({\n  gitInfo: Schema.optionalKey(\n    Schema.Union([\n      V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams,\n      Schema.Null,\n    ]).annotate({\n      description:\n        \"Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.\",\n    }),\n  ),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadMetadataUpdateParams\" });\n\nexport type V2ThreadMetadataUpdateResponse = {\n  readonly thread: V2ThreadMetadataUpdateResponse__Thread;\n};\nexport const V2ThreadMetadataUpdateResponse = Schema.Struct({\n  thread: V2ThreadMetadataUpdateResponse__Thread,\n}).annotate({ title: \"ThreadMetadataUpdateResponse\" });\n\nexport type V2ThreadMetadataUpdateResponse__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2ThreadMetadataUpdateResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadMetadataUpdateResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadMetadataUpdateResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource };\nexport const V2ThreadMetadataUpdateResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__ThreadExtra = {};\nexport const V2ThreadMetadataUpdateResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadMetadataUpdateResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadMetadataUpdateResponse__ThreadHistoryMode = Schema.Literals([\n  \"legacy\",\n  \"paginated\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadMetadataUpdateResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadMetadataUpdateResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadNameUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadName?: string | null;\n};\nexport const V2ThreadNameUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ThreadNameUpdatedNotification\" });\n\nexport type V2ThreadReadParams = { readonly includeTurns?: boolean; readonly threadId: string };\nexport const V2ThreadReadParams = Schema.Struct({\n  includeTurns: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, include turns and their items from rollout history.\",\n    }),\n  ),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadReadParams\" });\n\nexport type V2ThreadReadResponse = { readonly thread: V2ThreadReadResponse__Thread };\nexport const V2ThreadReadResponse = Schema.Struct({\n  thread: V2ThreadReadResponse__Thread,\n}).annotate({ title: \"ThreadReadResponse\" });\n\nexport type V2ThreadReadResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadReadResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadReadResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadReadResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadReadResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadReadResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadReadResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadReadResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadReadResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadReadResponse__SubAgentSource };\nexport const V2ThreadReadResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__ThreadExtra = {};\nexport const V2ThreadReadResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadReadResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadReadResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadReadResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadReadResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadReadResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadReadResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadRealtimeClosedNotification = {\n  readonly reason?: string | null;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeClosedNotification = Schema.Struct({\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeClosedNotification\",\n  description: \"EXPERIMENTAL - emitted when thread realtime transport closes.\",\n});\n\nexport type V2ThreadRealtimeErrorNotification = {\n  readonly message: string;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeErrorNotification = Schema.Struct({\n  message: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeErrorNotification\",\n  description: \"EXPERIMENTAL - emitted when thread realtime encounters an error.\",\n});\n\nexport type V2ThreadRealtimeItemAddedNotification = {\n  readonly item: unknown;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeItemAddedNotification = Schema.Struct({\n  item: Schema.Unknown,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeItemAddedNotification\",\n  description: \"EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.\",\n});\n\nexport type V2ThreadRealtimeOutputAudioDeltaNotification = {\n  readonly audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({\n  audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeOutputAudioDeltaNotification\",\n  description: \"EXPERIMENTAL - streamed output audio emitted by thread realtime.\",\n});\n\nexport type V2ThreadRealtimeSdpNotification = { readonly sdp: string; readonly threadId: string };\nexport const V2ThreadRealtimeSdpNotification = Schema.Struct({\n  sdp: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeSdpNotification\",\n  description: \"EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.\",\n});\n\nexport type V2ThreadRealtimeStartedNotification = {\n  readonly realtimeSessionId?: string | null;\n  readonly threadId: string;\n  readonly version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion;\n};\nexport const V2ThreadRealtimeStartedNotification = Schema.Struct({\n  realtimeSessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion,\n}).annotate({\n  title: \"ThreadRealtimeStartedNotification\",\n  description: \"EXPERIMENTAL - emitted when thread realtime startup is accepted.\",\n});\n\nexport type V2ThreadRealtimeTranscriptDeltaNotification = {\n  readonly delta: string;\n  readonly role: string;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeTranscriptDeltaNotification = Schema.Struct({\n  delta: Schema.String.annotate({ description: \"Live transcript delta from the realtime event.\" }),\n  role: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeTranscriptDeltaNotification\",\n  description:\n    \"EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.\",\n});\n\nexport type V2ThreadRealtimeTranscriptDoneNotification = {\n  readonly role: string;\n  readonly text: string;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeTranscriptDoneNotification = Schema.Struct({\n  role: Schema.String,\n  text: Schema.String.annotate({ description: \"Final complete text for the transcript part.\" }),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeTranscriptDoneNotification\",\n  description:\n    \"EXPERIMENTAL - final transcript text emitted when realtime completes a transcript part.\",\n});\n\nexport type V2ThreadResumeParams = {\n  readonly approvalPolicy?: V2ThreadResumeParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2ThreadResumeParams__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: V2ThreadResumeParams__Personality | null;\n  readonly sandbox?: V2ThreadResumeParams__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n};\nexport const V2ThreadResumeParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__AskForApproval, Schema.Null]),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the resumed thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadResumeParams\",\n  description:\n    \"There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\\n\\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\\n\\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type V2ThreadResumeParams__AbsolutePathBuf = string;\nexport const V2ThreadResumeParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadResumeParams__ResponseItem =\n  | {\n      readonly content: ReadonlyArray<V2ThreadResumeParams__ContentItem>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly phase?: V2ThreadResumeParams__MessagePhase | null;\n      readonly role: string;\n      readonly type: \"message\";\n    }\n  | {\n      readonly author: string;\n      readonly content: ReadonlyArray<V2ThreadResumeParams__AgentMessageInputContent>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly recipient: string;\n      readonly type: \"agent_message\";\n    }\n  | {\n      readonly content?: ReadonlyArray<V2ThreadResumeParams__ReasoningItemContent> | null;\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly summary: ReadonlyArray<V2ThreadResumeParams__ReasoningItemReasoningSummary>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly action: V2ThreadResumeParams__LocalShellAction;\n      readonly call_id?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status: V2ThreadResumeParams__LocalShellStatus;\n      readonly type: \"local_shell_call\";\n    }\n  | {\n      readonly arguments: string;\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly type: \"function_call\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"tool_search_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly output: V2ThreadResumeParams__FunctionCallOutputBody;\n      readonly type: \"function_call_output\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly input: string;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly status?: string | null;\n      readonly type: \"custom_tool_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly name?: string | null;\n      readonly output: V2ThreadResumeParams__FunctionCallOutputBody;\n      readonly type: \"custom_tool_call_output\";\n    }\n  | {\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status: string;\n      readonly tools: ReadonlyArray<unknown>;\n      readonly type: \"tool_search_output\";\n    }\n  | {\n      readonly action?: V2ThreadResumeParams__ResponsesApiWebSearchAction | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"web_search_call\";\n    }\n  | {\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly result: string;\n      readonly revised_prompt?: string | null;\n      readonly status: string;\n      readonly type: \"image_generation_call\";\n    }\n  | {\n      readonly encrypted_content: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"compaction\";\n    }\n  | { readonly type: \"compaction_trigger\" }\n  | {\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"context_compaction\";\n    }\n  | { readonly type: \"other\" };\nexport const V2ThreadResumeParams__ResponseItem = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.Array(V2ThreadResumeParams__ContentItem),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__MessagePhase, Schema.Null])),\n      role: Schema.String,\n      type: Schema.Literal(\"message\").annotate({ title: \"MessageResponseItemType\" }),\n    }).annotate({ title: \"MessageResponseItem\" }),\n    Schema.Struct({\n      author: Schema.String,\n      content: Schema.Array(V2ThreadResumeParams__AgentMessageInputContent),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      recipient: Schema.String,\n      type: Schema.Literal(\"agent_message\").annotate({ title: \"AgentMessageResponseItemType\" }),\n    }).annotate({ title: \"AgentMessageResponseItem\" }),\n    Schema.Struct({\n      content: Schema.optionalKey(\n        Schema.Union([Schema.Array(V2ThreadResumeParams__ReasoningItemContent), Schema.Null]),\n      ),\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      summary: Schema.Array(V2ThreadResumeParams__ReasoningItemReasoningSummary),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningResponseItemType\" }),\n    }).annotate({ title: \"ReasoningResponseItem\" }),\n    Schema.Struct({\n      action: V2ThreadResumeParams__LocalShellAction,\n      call_id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Set when using the Responses API.\" }),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Legacy id field retained for compatibility with older payloads.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: V2ThreadResumeParams__LocalShellStatus,\n      type: Schema.Literal(\"local_shell_call\").annotate({\n        title: \"LocalShellCallResponseItemType\",\n      }),\n    }).annotate({ title: \"LocalShellCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.String,\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"function_call\").annotate({ title: \"FunctionCallResponseItemType\" }),\n    }).annotate({ title: \"FunctionCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"tool_search_call\").annotate({\n        title: \"ToolSearchCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      output: V2ThreadResumeParams__FunctionCallOutputBody,\n      type: Schema.Literal(\"function_call_output\").annotate({\n        title: \"FunctionCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"FunctionCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      input: Schema.String,\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"custom_tool_call\").annotate({\n        title: \"CustomToolCallResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      output: V2ThreadResumeParams__FunctionCallOutputBody,\n      type: Schema.Literal(\"custom_tool_call_output\").annotate({\n        title: \"CustomToolCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.String,\n      tools: Schema.Array(Schema.Unknown),\n      type: Schema.Literal(\"tool_search_output\").annotate({\n        title: \"ToolSearchOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchOutputResponseItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__ResponsesApiWebSearchAction, Schema.Null]),\n      ),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"web_search_call\").annotate({ title: \"WebSearchCallResponseItemType\" }),\n    }).annotate({ title: \"WebSearchCallResponseItem\" }),\n    Schema.Struct({\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      result: Schema.String,\n      revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.String,\n      type: Schema.Literal(\"image_generation_call\").annotate({\n        title: \"ImageGenerationCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ImageGenerationCallResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"compaction\").annotate({ title: \"CompactionResponseItemType\" }),\n    }).annotate({ title: \"CompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"compaction_trigger\").annotate({\n        title: \"CompactionTriggerResponseItemType\",\n      }),\n    }).annotate({ title: \"CompactionTriggerResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"context_compaction\").annotate({\n        title: \"ContextCompactionResponseItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponseItemType\" }),\n    }).annotate({ title: \"OtherResponseItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ThreadResumeInitialTurnsPageParams = {\n  readonly itemsView?: V2ThreadResumeParams__TurnItemsView | null;\n  readonly limit?: number | null;\n  readonly sortDirection?: V2ThreadResumeParams__SortDirection | null;\n};\nexport const V2ThreadResumeParams__ThreadResumeInitialTurnsPageParams = Schema.Struct({\n  itemsView: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__TurnItemsView, Schema.Null]).annotate({\n      description: \"How much item detail to include for each returned turn; defaults to summary.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Optional turn page size.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__SortDirection, Schema.Null]).annotate({\n      description: \"Optional turn pagination direction; defaults to descending.\",\n    }),\n  ),\n});\n\nexport type V2ThreadResumeResponse = {\n  readonly approvalPolicy: V2ThreadResumeResponse__AskForApproval;\n  readonly approvalsReviewer: \"user\" | \"auto_review\" | \"guardian_subagent\";\n  readonly cwd: V2ThreadResumeResponse__AbsolutePathBuf;\n  readonly instructionSources?: ReadonlyArray<V2ThreadResumeResponse__LegacyAppPathString>;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null;\n  readonly sandbox:\n    | { readonly type: \"dangerFullAccess\" }\n    | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n    | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n    | {\n        readonly excludeSlashTmp?: boolean;\n        readonly excludeTmpdirEnvVar?: boolean;\n        readonly networkAccess?: boolean;\n        readonly type: \"workspaceWrite\";\n        readonly writableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;\n      };\n  readonly serviceTier?: string | null;\n  readonly thread: V2ThreadResumeResponse__Thread;\n};\nexport const V2ThreadResumeResponse = Schema.Struct({\n  approvalPolicy: V2ThreadResumeResponse__AskForApproval,\n  approvalsReviewer: Schema.Literals([\"user\", \"auto_review\", \"guardian_subagent\"]).annotate({\n    description:\n      \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n  }),\n  cwd: V2ThreadResumeResponse__AbsolutePathBuf,\n  instructionSources: Schema.optionalKey(\n    Schema.Array(V2ThreadResumeResponse__LegacyAppPathString).annotate({\n      description:\n        \"Environment-native paths to instruction source files currently loaded for this thread.\",\n      default: [],\n    }),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  reasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]),\n  ),\n  sandbox: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"dangerFullAccess\").annotate({\n          title: \"DangerFullAccessSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n      }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(\n          Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n        ),\n        type: Schema.Literal(\"externalSandbox\").annotate({\n          title: \"ExternalSandboxSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n      Schema.Struct({\n        excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"workspaceWrite\").annotate({\n          title: \"WorkspaceWriteSandboxPolicyType\",\n        }),\n        writableRoots: Schema.optionalKey(\n          Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),\n        ),\n      }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance.\",\n  }),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  thread: V2ThreadResumeResponse__Thread,\n}).annotate({ title: \"ThreadResumeResponse\" });\n\nexport type V2ThreadResumeResponse__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadResumeResponse__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadResumeResponse__ApprovalsReviewer =\n  | \"user\"\n  | \"auto_review\"\n  | \"guardian_subagent\";\nexport const V2ThreadResumeResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadResumeResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadResumeResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadResumeResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadResumeResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadResumeResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadResumeResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadResumeResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadResumeResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadResumeResponse__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadResumeResponse__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadResumeResponse__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadResumeResponse__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2ThreadResumeResponse__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;\n    };\nexport const V2ThreadResumeResponse__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource };\nexport const V2ThreadResumeResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__ThreadExtra = {};\nexport const V2ThreadResumeResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadResumeResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadResumeResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadResumeResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadResumeResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadResumeResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadResumeResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadResumeResponse__TurnsPage = {\n  readonly backwardsCursor?: string | null;\n  readonly data: ReadonlyArray<V2ThreadResumeResponse__Turn>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ThreadResumeResponse__TurnsPage = Schema.Struct({\n  backwardsCursor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  data: Schema.Array(V2ThreadResumeResponse__Turn),\n  nextCursor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadRollbackParams = { readonly numTurns: number; readonly threadId: string };\nexport const V2ThreadRollbackParams = Schema.Struct({\n  numTurns: Schema.Number.annotate({\n    description:\n      \"The number of turns to drop from the end of the thread. Must be >= 1.\\n\\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.\",\n    format: \"uint32\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRollbackParams\",\n  description: \"DEPRECATED: `thread/rollback` will be removed soon.\",\n});\n\nexport type V2ThreadRollbackResponse = {\n  readonly thread: {\n    readonly agentNickname?: string | null;\n    readonly agentRole?: string | null;\n    readonly cliVersion: string;\n    readonly createdAt: number;\n    readonly cwd: string;\n    readonly ephemeral: boolean;\n    readonly forkedFromId?: string | null;\n    readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null;\n    readonly id: string;\n    readonly modelProvider: string;\n    readonly name?: string | null;\n    readonly parentThreadId?: string | null;\n    readonly path?: string | null;\n    readonly preview: string;\n    readonly recencyAt?: number | null;\n    readonly sessionId: string;\n    readonly source:\n      | \"cli\"\n      | \"vscode\"\n      | \"exec\"\n      | \"appServer\"\n      | \"unknown\"\n      | { readonly custom: string }\n      | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };\n    readonly status:\n      | { readonly type: \"notLoaded\" }\n      | { readonly type: \"idle\" }\n      | { readonly type: \"systemError\" }\n      | {\n          readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;\n          readonly type: \"active\";\n        };\n    readonly threadSource?: V2ThreadRollbackResponse__ThreadSource | null;\n    readonly turns: ReadonlyArray<V2ThreadRollbackResponse__Turn>;\n    readonly updatedAt: number;\n  };\n};\nexport const V2ThreadRollbackResponse = Schema.Struct({\n  thread: Schema.Struct({\n    agentNickname: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    agentRole: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    cliVersion: Schema.String.annotate({\n      description: \"Version of the CLI that created the thread.\",\n    }),\n    createdAt: Schema.Number.annotate({\n      description: \"Unix timestamp (in seconds) when the thread was created.\",\n      format: \"int64\",\n    }).check(Schema.isInt()),\n    cwd: Schema.String.annotate({\n      description:\n        \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n    }),\n    ephemeral: Schema.Boolean.annotate({\n      description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n    }),\n    forkedFromId: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Source thread id when this thread was created by forking another thread.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    gitInfo: Schema.optionalKey(\n      Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({\n        description: \"Optional Git metadata captured when the thread was created.\",\n      }),\n    ),\n    id: Schema.String.annotate({\n      description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n    }),\n    modelProvider: Schema.String.annotate({\n      description: \"Model provider used for this thread (for example, 'openai').\",\n    }),\n    name: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n        Schema.Null,\n      ]),\n    ),\n    parentThreadId: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    path: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n        Schema.Null,\n      ]),\n    ),\n    preview: Schema.String.annotate({\n      description: \"Usually the first user message in the thread, if available.\",\n    }),\n    recencyAt: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({\n          description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n        Schema.Null,\n      ]),\n    ),\n    sessionId: Schema.String.annotate({\n      description: \"Session id shared by threads that belong to the same session tree.\",\n    }),\n    source: Schema.Union(\n      [\n        Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n        Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n        Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({\n          title: \"SubAgentSessionSource\",\n        }),\n      ],\n      { mode: \"oneOf\" },\n    ).annotate({\n      description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n    }),\n    status: Schema.Union(\n      [\n        Schema.Struct({\n          type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n        }).annotate({ title: \"NotLoadedThreadStatus\" }),\n        Schema.Struct({\n          type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n        }).annotate({ title: \"IdleThreadStatus\" }),\n        Schema.Struct({\n          type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n        }).annotate({ title: \"SystemErrorThreadStatus\" }),\n        Schema.Struct({\n          activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),\n          type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n        }).annotate({ title: \"ActiveThreadStatus\" }),\n      ],\n      { mode: \"oneOf\" },\n    ).annotate({ description: \"Current runtime status for the thread.\" }),\n    threadSource: Schema.optionalKey(\n      Schema.Union([V2ThreadRollbackResponse__ThreadSource, Schema.Null]).annotate({\n        description: \"Optional analytics source classification for this thread.\",\n      }),\n    ),\n    turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({\n      description:\n        \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n    }),\n    updatedAt: Schema.Number.annotate({\n      description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n      format: \"int64\",\n    }).check(Schema.isInt()),\n  }).annotate({\n    description:\n      \"The updated thread after applying the rollback, with `turns` populated.\\n\\nThe ThreadItems stored in each Turn are lossy since we explicitly do not persist all agent interactions, such as command executions. This is the same behavior as `thread/resume`.\",\n  }),\n}).annotate({ title: \"ThreadRollbackResponse\" });\n\nexport type V2ThreadRollbackResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadRollbackResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadRollbackResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadRollbackResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadRollbackResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadRollbackResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadRollbackResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadRollbackResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadRollbackResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };\nexport const V2ThreadRollbackResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadRollbackResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadRollbackResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadRollbackResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadRollbackResponse__ThreadExtra = {};\nexport const V2ThreadRollbackResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadRollbackResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadRollbackResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadRollbackResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadRollbackResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadRollbackResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadSetNameParams = { readonly name: string; readonly threadId: string };\nexport const V2ThreadSetNameParams = Schema.Struct({\n  name: Schema.String,\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadSetNameParams\" });\n\nexport type V2ThreadSetNameResponse = {};\nexport const V2ThreadSetNameResponse = Schema.Struct({}).annotate({\n  title: \"ThreadSetNameResponse\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadSettings: V2ThreadSettingsUpdatedNotification__ThreadSettings;\n};\nexport const V2ThreadSettingsUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadSettings: V2ThreadSettingsUpdatedNotification__ThreadSettings,\n}).annotate({ title: \"ThreadSettingsUpdatedNotification\" });\n\nexport type V2ThreadSettingsUpdatedNotification__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadSettingsUpdatedNotification__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadSettingsUpdatedNotification__NetworkAccess = Schema.Literals([\n  \"restricted\",\n  \"enabled\",\n]);\n\nexport type V2ThreadShellCommandParams = { readonly command: string; readonly threadId: string };\nexport const V2ThreadShellCommandParams = Schema.Struct({\n  command: Schema.String.annotate({\n    description:\n      \"Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy.\",\n  }),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadShellCommandParams\" });\n\nexport type V2ThreadShellCommandResponse = {};\nexport const V2ThreadShellCommandResponse = Schema.Struct({}).annotate({\n  title: \"ThreadShellCommandResponse\",\n});\n\nexport type V2ThreadStartedNotification = { readonly thread: V2ThreadStartedNotification__Thread };\nexport const V2ThreadStartedNotification = Schema.Struct({\n  thread: V2ThreadStartedNotification__Thread,\n}).annotate({ title: \"ThreadStartedNotification\" });\n\nexport type V2ThreadStartedNotification__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2ThreadStartedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadStartedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadStartedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadStartedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadStartedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadStartedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadStartedNotification__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource };\nexport const V2ThreadStartedNotification__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__ThreadExtra = {};\nexport const V2ThreadStartedNotification__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadStartedNotification__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadStartedNotification__ThreadHistoryMode = Schema.Literals([\n  \"legacy\",\n  \"paginated\",\n]);\n\nexport type V2ThreadStartedNotification__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadStartedNotification__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadStartedNotification__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadStartedNotification__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadStartParams = {\n  readonly approvalPolicy?: V2ThreadStartParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2ThreadStartParams__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: V2ThreadStartParams__Personality | null;\n  readonly sandbox?: V2ThreadStartParams__SandboxMode | null;\n  readonly serviceName?: string | null;\n  readonly serviceTier?: string | null;\n  readonly sessionStartSource?: V2ThreadStartParams__ThreadStartSource | null;\n  readonly threadSource?: V2ThreadStartParams__ThreadSource | null;\n};\nexport const V2ThreadStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__AskForApproval, Schema.Null]),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([V2ThreadStartParams__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([V2ThreadStartParams__SandboxMode, Schema.Null])),\n  serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sessionStartSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__ThreadStartSource, Schema.Null]),\n  ),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional client-supplied analytics source classification for this thread.\",\n    }),\n  ),\n}).annotate({ title: \"ThreadStartParams\" });\n\nexport type V2ThreadStartParams__AbsolutePathBuf = string;\nexport const V2ThreadStartParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadStartParams__CapabilityRootLocation = {\n  readonly environmentId: string;\n  readonly path: string;\n  readonly type: \"environment\";\n};\nexport const V2ThreadStartParams__CapabilityRootLocation = Schema.Union(\n  [\n    Schema.Struct({\n      environmentId: Schema.String,\n      path: Schema.String.annotate({\n        description: \"Absolute path for the root in the selected environment.\",\n      }),\n      type: Schema.Literal(\"environment\").annotate({\n        title: \"EnvironmentCapabilityRootLocationType\",\n      }),\n    }).annotate({\n      title: \"EnvironmentCapabilityRootLocation\",\n      description: \"A path owned by an execution environment.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"Location used to resolve a selected capability root.\" });\n\nexport type V2ThreadStartParams__DynamicToolSpec =\n  | {\n      readonly deferLoading?: boolean;\n      readonly description: string;\n      readonly inputSchema: unknown;\n      readonly name: string;\n      readonly type: \"function\";\n    }\n  | {\n      readonly description: string;\n      readonly name: string;\n      readonly tools: ReadonlyArray<V2ThreadStartParams__DynamicToolNamespaceTool>;\n      readonly type: \"namespace\";\n    };\nexport const V2ThreadStartParams__DynamicToolSpec = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolSpecType\" }),\n    }).annotate({ title: \"FunctionDynamicToolSpec\" }),\n    Schema.Struct({\n      description: Schema.String,\n      name: Schema.String,\n      tools: Schema.Array(V2ThreadStartParams__DynamicToolNamespaceTool),\n      type: Schema.Literal(\"namespace\").annotate({ title: \"NamespaceDynamicToolSpecType\" }),\n    }).annotate({ title: \"NamespaceDynamicToolSpec\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadStartParams__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadStartParams__SelectedCapabilityRoot = {\n  readonly id: string;\n  readonly location: {\n    readonly environmentId: string;\n    readonly path: string;\n    readonly type: \"environment\";\n  };\n};\nexport const V2ThreadStartParams__SelectedCapabilityRoot = Schema.Struct({\n  id: Schema.String.annotate({\n    description: \"Stable identifier supplied by the capability selection platform.\",\n  }),\n  location: Schema.Union(\n    [\n      Schema.Struct({\n        environmentId: Schema.String,\n        path: Schema.String.annotate({\n          description: \"Absolute path for the root in the selected environment.\",\n        }),\n        type: Schema.Literal(\"environment\").annotate({\n          title: \"EnvironmentCapabilityRootLocationType\",\n        }),\n      }).annotate({\n        title: \"EnvironmentCapabilityRootLocation\",\n        description: \"A path owned by an execution environment.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Location used to resolve a selected capability root.\" }),\n}).annotate({\n  description: \"A user-selected root that can expose one or more runtime capabilities.\",\n});\n\nexport type V2ThreadStartParams__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadStartParams__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadStartParams__TurnEnvironmentParams = {\n  readonly cwd: V2ThreadStartParams__LegacyAppPathString;\n  readonly environmentId: string;\n  readonly runtimeWorkspaceRoots?: ReadonlyArray<V2ThreadStartParams__LegacyAppPathString> | null;\n};\nexport const V2ThreadStartParams__TurnEnvironmentParams = Schema.Struct({\n  cwd: V2ThreadStartParams__LegacyAppPathString,\n  environmentId: Schema.String,\n  runtimeWorkspaceRoots: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2ThreadStartParams__LegacyAppPathString).annotate({\n        description: \"Environment-native runtime workspace roots. Omitted defaults to `cwd`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadStartResponse = {\n  readonly approvalPolicy: V2ThreadStartResponse__AskForApproval;\n  readonly approvalsReviewer: \"user\" | \"auto_review\" | \"guardian_subagent\";\n  readonly cwd: V2ThreadStartResponse__AbsolutePathBuf;\n  readonly instructionSources?: ReadonlyArray<V2ThreadStartResponse__LegacyAppPathString>;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null;\n  readonly sandbox:\n    | { readonly type: \"dangerFullAccess\" }\n    | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n    | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n    | {\n        readonly excludeSlashTmp?: boolean;\n        readonly excludeTmpdirEnvVar?: boolean;\n        readonly networkAccess?: boolean;\n        readonly type: \"workspaceWrite\";\n        readonly writableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;\n      };\n  readonly serviceTier?: string | null;\n  readonly thread: V2ThreadStartResponse__Thread;\n};\nexport const V2ThreadStartResponse = Schema.Struct({\n  approvalPolicy: V2ThreadStartResponse__AskForApproval,\n  approvalsReviewer: Schema.Literals([\"user\", \"auto_review\", \"guardian_subagent\"]).annotate({\n    description:\n      \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n  }),\n  cwd: V2ThreadStartResponse__AbsolutePathBuf,\n  instructionSources: Schema.optionalKey(\n    Schema.Array(V2ThreadStartResponse__LegacyAppPathString).annotate({\n      description:\n        \"Environment-native paths to instruction source files currently loaded for this thread.\",\n      default: [],\n    }),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  reasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]),\n  ),\n  sandbox: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"dangerFullAccess\").annotate({\n          title: \"DangerFullAccessSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n      }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(\n          Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n        ),\n        type: Schema.Literal(\"externalSandbox\").annotate({\n          title: \"ExternalSandboxSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n      Schema.Struct({\n        excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"workspaceWrite\").annotate({\n          title: \"WorkspaceWriteSandboxPolicyType\",\n        }),\n        writableRoots: Schema.optionalKey(\n          Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),\n        ),\n      }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance.\",\n  }),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  thread: V2ThreadStartResponse__Thread,\n}).annotate({ title: \"ThreadStartResponse\" });\n\nexport type V2ThreadStartResponse__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadStartResponse__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadStartResponse__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadStartResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadStartResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadStartResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadStartResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadStartResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadStartResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadStartResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadStartResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadStartResponse__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadStartResponse__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadStartResponse__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadStartResponse__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2ThreadStartResponse__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;\n    };\nexport const V2ThreadStartResponse__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadStartResponse__SubAgentSource };\nexport const V2ThreadStartResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__ThreadExtra = {};\nexport const V2ThreadStartResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadStartResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadStartResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadStartResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadStartResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadStartResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadStartResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadStatusChangedNotification = {\n  readonly status: V2ThreadStatusChangedNotification__ThreadStatus;\n  readonly threadId: string;\n};\nexport const V2ThreadStatusChangedNotification = Schema.Struct({\n  status: V2ThreadStatusChangedNotification__ThreadStatus,\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadStatusChangedNotification\" });\n\nexport type V2ThreadTokenUsageUpdatedNotification = {\n  readonly threadId: string;\n  readonly tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage;\n  readonly turnId: string;\n};\nexport const V2ThreadTokenUsageUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage,\n  turnId: Schema.String,\n}).annotate({ title: \"ThreadTokenUsageUpdatedNotification\" });\n\nexport type V2ThreadUnarchivedNotification = { readonly threadId: string };\nexport const V2ThreadUnarchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadUnarchivedNotification\",\n});\n\nexport type V2ThreadUnarchiveParams = { readonly threadId: string };\nexport const V2ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadUnarchiveParams\",\n});\n\nexport type V2ThreadUnarchiveResponse = { readonly thread: V2ThreadUnarchiveResponse__Thread };\nexport const V2ThreadUnarchiveResponse = Schema.Struct({\n  thread: V2ThreadUnarchiveResponse__Thread,\n}).annotate({ title: \"ThreadUnarchiveResponse\" });\n\nexport type V2ThreadUnarchiveResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadUnarchiveResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadUnarchiveResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadUnarchiveResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadUnarchiveResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadUnarchiveResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadUnarchiveResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadUnarchiveResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadUnarchiveResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource };\nexport const V2ThreadUnarchiveResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__ThreadExtra = {};\nexport const V2ThreadUnarchiveResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadUnarchiveResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadUnarchiveResponse__ThreadHistoryMode = Schema.Literals([\n  \"legacy\",\n  \"paginated\",\n]);\n\nexport type V2ThreadUnarchiveResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadUnarchiveResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadUnarchiveResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadUnsubscribeParams = { readonly threadId: string };\nexport const V2ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadUnsubscribeParams\",\n});\n\nexport type V2ThreadUnsubscribeResponse = {\n  readonly status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus;\n};\nexport const V2ThreadUnsubscribeResponse = Schema.Struct({\n  status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus,\n}).annotate({ title: \"ThreadUnsubscribeResponse\" });\n\nexport type V2TurnCompletedNotification = {\n  readonly threadId: string;\n  readonly turn: V2TurnCompletedNotification__Turn;\n};\nexport const V2TurnCompletedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: V2TurnCompletedNotification__Turn,\n}).annotate({ title: \"TurnCompletedNotification\" });\n\nexport type V2TurnCompletedNotification__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2TurnCompletedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnCompletedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2TurnCompletedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2TurnCompletedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnCompletedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2TurnCompletedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2TurnCompletedNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2TurnCompletedNotification__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2TurnDiffUpdatedNotification = {\n  readonly diff: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TurnDiffUpdatedNotification = Schema.Struct({\n  diff: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"TurnDiffUpdatedNotification\",\n  description:\n    \"Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.\",\n});\n\nexport type V2TurnInterruptParams = { readonly threadId: string; readonly turnId: string };\nexport const V2TurnInterruptParams = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TurnInterruptParams\" });\n\nexport type V2TurnInterruptResponse = {};\nexport const V2TurnInterruptResponse = Schema.Struct({}).annotate({\n  title: \"TurnInterruptResponse\",\n});\n\nexport type V2TurnModerationMetadataNotification = {\n  readonly metadata: unknown;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TurnModerationMetadataNotification = Schema.Struct({\n  metadata: Schema.Unknown,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TurnModerationMetadataNotification\" });\n\nexport type V2TurnPlanUpdatedNotification = {\n  readonly explanation?: string | null;\n  readonly plan: ReadonlyArray<V2TurnPlanUpdatedNotification__TurnPlanStep>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TurnPlanUpdatedNotification = Schema.Struct({\n  explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  plan: Schema.Array(V2TurnPlanUpdatedNotification__TurnPlanStep),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TurnPlanUpdatedNotification\" });\n\nexport type V2TurnStartedNotification = {\n  readonly threadId: string;\n  readonly turn: V2TurnStartedNotification__Turn;\n};\nexport const V2TurnStartedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: V2TurnStartedNotification__Turn,\n}).annotate({ title: \"TurnStartedNotification\" });\n\nexport type V2TurnStartedNotification__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnStartedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnStartedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2TurnStartedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2TurnStartedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnStartedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2TurnStartedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2TurnStartedNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2TurnStartedNotification__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2TurnStartParams = {\n  readonly approvalPolicy?: V2TurnStartParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2TurnStartParams__ApprovalsReviewer | null;\n  readonly clientUserMessageId?: string | null;\n  readonly cwd?: string | null;\n  readonly effort?: V2TurnStartParams__ReasoningEffort | null;\n  readonly input: ReadonlyArray<V2TurnStartParams__UserInput>;\n  readonly model?: string | null;\n  readonly outputSchema?: unknown;\n  readonly personality?: V2TurnStartParams__Personality | null;\n  readonly sandboxPolicy?: V2TurnStartParams__SandboxPolicy | null;\n  readonly serviceTier?: string | null;\n  readonly summary?: V2TurnStartParams__ReasoningSummary | null;\n  readonly threadId: string;\n};\nexport const V2TurnStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__AskForApproval, Schema.Null]).annotate({\n      description: \"Override the approval policy for this turn and subsequent turns.\",\n    }),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this turn and subsequent turns.\",\n    }),\n  ),\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the working directory for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  effort: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]).annotate({\n      description: \"Override the reasoning effort for this turn and subsequent turns.\",\n    }),\n  ),\n  input: Schema.Array(V2TurnStartParams__UserInput),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the model for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputSchema: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Optional JSON Schema used to constrain the final assistant message for this turn.\",\n    }),\n  ),\n  personality: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__Personality, Schema.Null]).annotate({\n      description: \"Override the personality for this turn and subsequent turns.\",\n    }),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__SandboxPolicy, Schema.Null]).annotate({\n      description: \"Override the sandbox policy for this turn and subsequent turns.\",\n    }),\n  ),\n  serviceTier: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the service tier for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ReasoningSummary, Schema.Null]).annotate({\n      description: \"Override the reasoning summary for this turn and subsequent turns.\",\n    }),\n  ),\n  threadId: Schema.String,\n}).annotate({ title: \"TurnStartParams\" });\n\nexport type V2TurnStartParams__AdditionalContextEntry = {\n  readonly kind: V2TurnStartParams__AdditionalContextKind;\n  readonly value: string;\n};\nexport const V2TurnStartParams__AdditionalContextEntry = Schema.Struct({\n  kind: V2TurnStartParams__AdditionalContextKind,\n  value: Schema.String,\n});\n\nexport type V2TurnStartParams__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnStartParams__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnStartParams__CollaborationMode = {\n  readonly mode: V2TurnStartParams__ModeKind;\n  readonly settings: V2TurnStartParams__Settings;\n};\nexport const V2TurnStartParams__CollaborationMode = Schema.Struct({\n  mode: V2TurnStartParams__ModeKind,\n  settings: V2TurnStartParams__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type V2TurnStartParams__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2TurnStartParams__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2TurnStartParams__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2TurnStartParams__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2TurnStartParams__TurnEnvironmentParams = {\n  readonly cwd: V2TurnStartParams__LegacyAppPathString;\n  readonly environmentId: string;\n  readonly runtimeWorkspaceRoots?: ReadonlyArray<V2TurnStartParams__LegacyAppPathString> | null;\n};\nexport const V2TurnStartParams__TurnEnvironmentParams = Schema.Struct({\n  cwd: V2TurnStartParams__LegacyAppPathString,\n  environmentId: Schema.String,\n  runtimeWorkspaceRoots: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2TurnStartParams__LegacyAppPathString).annotate({\n        description: \"Environment-native runtime workspace roots. Omitted defaults to `cwd`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartResponse = { readonly turn: V2TurnStartResponse__Turn };\nexport const V2TurnStartResponse = Schema.Struct({ turn: V2TurnStartResponse__Turn }).annotate({\n  title: \"TurnStartResponse\",\n});\n\nexport type V2TurnStartResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnStartResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnStartResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2TurnStartResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2TurnStartResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2TurnStartResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2TurnStartResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2TurnStartResponse__TurnItemsView = Schema.Literals([\"notLoaded\", \"summary\", \"full\"]);\n\nexport type V2TurnSteerParams = {\n  readonly clientUserMessageId?: string | null;\n  readonly expectedTurnId: string;\n  readonly input: ReadonlyArray<V2TurnSteerParams__UserInput>;\n  readonly threadId: string;\n};\nexport const V2TurnSteerParams = Schema.Struct({\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  expectedTurnId: Schema.String.annotate({\n    description:\n      \"Required active turn id precondition. The request fails when it does not match the currently active turn.\",\n  }),\n  input: Schema.Array(V2TurnSteerParams__UserInput),\n  threadId: Schema.String,\n}).annotate({ title: \"TurnSteerParams\" });\n\nexport type V2TurnSteerParams__AdditionalContextEntry = {\n  readonly kind: V2TurnSteerParams__AdditionalContextKind;\n  readonly value: string;\n};\nexport const V2TurnSteerParams__AdditionalContextEntry = Schema.Struct({\n  kind: V2TurnSteerParams__AdditionalContextKind,\n  value: Schema.String,\n});\n\nexport type V2TurnSteerParams__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnSteerParams__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnSteerResponse = { readonly turnId: string };\nexport const V2TurnSteerResponse = Schema.Struct({ turnId: Schema.String }).annotate({\n  title: \"TurnSteerResponse\",\n});\n\nexport type V2WarningNotification = { readonly message: string; readonly threadId?: string | null };\nexport const V2WarningNotification = Schema.Struct({\n  message: Schema.String.annotate({ description: \"Concise warning message for the user.\" }),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional thread target when the warning applies to a specific thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"WarningNotification\" });\n\nexport type V2WindowsSandboxReadinessResponse = {\n  readonly status: V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness;\n};\nexport const V2WindowsSandboxReadinessResponse = Schema.Struct({\n  status: V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness,\n}).annotate({ title: \"WindowsSandboxReadinessResponse\" });\n\nexport type V2WindowsSandboxSetupCompletedNotification = {\n  readonly error?: string | null;\n  readonly mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode;\n  readonly success: boolean;\n};\nexport const V2WindowsSandboxSetupCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode,\n  success: Schema.Boolean,\n}).annotate({ title: \"WindowsSandboxSetupCompletedNotification\" });\n\nexport type V2WindowsSandboxSetupStartParams = {\n  readonly cwd?: V2WindowsSandboxSetupStartParams__AbsolutePathBuf | null;\n  readonly mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode;\n};\nexport const V2WindowsSandboxSetupStartParams = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([V2WindowsSandboxSetupStartParams__AbsolutePathBuf, Schema.Null]),\n  ),\n  mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode,\n}).annotate({ title: \"WindowsSandboxSetupStartParams\" });\n\nexport type V2WindowsSandboxSetupStartResponse = { readonly started: boolean };\nexport const V2WindowsSandboxSetupStartResponse = Schema.Struct({\n  started: Schema.Boolean,\n}).annotate({ title: \"WindowsSandboxSetupStartResponse\" });\n\nexport type V2WindowsWorldWritableWarningNotification = {\n  readonly extraCount: number;\n  readonly failedScan: boolean;\n  readonly samplePaths: ReadonlyArray<string>;\n};\nexport const V2WindowsWorldWritableWarningNotification = Schema.Struct({\n  extraCount: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  failedScan: Schema.Boolean,\n  samplePaths: Schema.Array(Schema.String),\n}).annotate({ title: \"WindowsWorldWritableWarningNotification\" });\n","// This file is generated by the effect-codex-app-server package. Do not edit manually.\n// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461\n\nimport * as CodexSchema from \"./schema.gen.ts\";\n\nexport const CLIENT_REQUEST_METHODS = {\n  initialize: \"initialize\",\n  \"thread/start\": \"thread/start\",\n  \"thread/resume\": \"thread/resume\",\n  \"thread/fork\": \"thread/fork\",\n  \"thread/archive\": \"thread/archive\",\n  \"thread/delete\": \"thread/delete\",\n  \"thread/unsubscribe\": \"thread/unsubscribe\",\n  \"thread/name/set\": \"thread/name/set\",\n  \"thread/goal/set\": \"thread/goal/set\",\n  \"thread/goal/get\": \"thread/goal/get\",\n  \"thread/goal/clear\": \"thread/goal/clear\",\n  \"thread/metadata/update\": \"thread/metadata/update\",\n  \"thread/unarchive\": \"thread/unarchive\",\n  \"thread/compact/start\": \"thread/compact/start\",\n  \"thread/shellCommand\": \"thread/shellCommand\",\n  \"thread/approveGuardianDeniedAction\": \"thread/approveGuardianDeniedAction\",\n  \"thread/rollback\": \"thread/rollback\",\n  \"thread/list\": \"thread/list\",\n  \"thread/loaded/list\": \"thread/loaded/list\",\n  \"thread/read\": \"thread/read\",\n  \"thread/inject_items\": \"thread/inject_items\",\n  \"skills/list\": \"skills/list\",\n  \"skills/extraRoots/set\": \"skills/extraRoots/set\",\n  \"hooks/list\": \"hooks/list\",\n  \"marketplace/add\": \"marketplace/add\",\n  \"marketplace/remove\": \"marketplace/remove\",\n  \"marketplace/upgrade\": \"marketplace/upgrade\",\n  \"plugin/list\": \"plugin/list\",\n  \"plugin/installed\": \"plugin/installed\",\n  \"plugin/read\": \"plugin/read\",\n  \"plugin/skill/read\": \"plugin/skill/read\",\n  \"plugin/share/save\": \"plugin/share/save\",\n  \"plugin/share/updateTargets\": \"plugin/share/updateTargets\",\n  \"plugin/share/list\": \"plugin/share/list\",\n  \"plugin/share/checkout\": \"plugin/share/checkout\",\n  \"plugin/share/delete\": \"plugin/share/delete\",\n  \"app/read\": \"app/read\",\n  \"app/list\": \"app/list\",\n  \"app/installed\": \"app/installed\",\n  \"fs/readFile\": \"fs/readFile\",\n  \"fs/writeFile\": \"fs/writeFile\",\n  \"fs/createDirectory\": \"fs/createDirectory\",\n  \"fs/getMetadata\": \"fs/getMetadata\",\n  \"fs/readDirectory\": \"fs/readDirectory\",\n  \"fs/remove\": \"fs/remove\",\n  \"fs/copy\": \"fs/copy\",\n  \"fs/watch\": \"fs/watch\",\n  \"fs/unwatch\": \"fs/unwatch\",\n  \"skills/config/write\": \"skills/config/write\",\n  \"plugin/install\": \"plugin/install\",\n  \"plugin/uninstall\": \"plugin/uninstall\",\n  \"turn/start\": \"turn/start\",\n  \"turn/steer\": \"turn/steer\",\n  \"turn/interrupt\": \"turn/interrupt\",\n  \"review/start\": \"review/start\",\n  \"model/list\": \"model/list\",\n  \"modelProvider/capabilities/read\": \"modelProvider/capabilities/read\",\n  \"experimentalFeature/list\": \"experimentalFeature/list\",\n  \"permissionProfile/list\": \"permissionProfile/list\",\n  \"experimentalFeature/enablement/set\": \"experimentalFeature/enablement/set\",\n  \"mcpServer/oauth/login\": \"mcpServer/oauth/login\",\n  \"config/mcpServer/reload\": \"config/mcpServer/reload\",\n  \"mcpServerStatus/list\": \"mcpServerStatus/list\",\n  \"mcpServer/resource/read\": \"mcpServer/resource/read\",\n  \"mcpServer/tool/call\": \"mcpServer/tool/call\",\n  \"windowsSandbox/setupStart\": \"windowsSandbox/setupStart\",\n  \"windowsSandbox/readiness\": \"windowsSandbox/readiness\",\n  \"account/login/start\": \"account/login/start\",\n  \"account/login/cancel\": \"account/login/cancel\",\n  \"account/logout\": \"account/logout\",\n  \"account/rateLimits/read\": \"account/rateLimits/read\",\n  \"account/rateLimitResetCredit/consume\": \"account/rateLimitResetCredit/consume\",\n  \"account/usage/read\": \"account/usage/read\",\n  \"account/workspaceMessages/read\": \"account/workspaceMessages/read\",\n  \"account/sendAddCreditsNudgeEmail\": \"account/sendAddCreditsNudgeEmail\",\n  \"feedback/upload\": \"feedback/upload\",\n  \"command/exec\": \"command/exec\",\n  \"command/exec/write\": \"command/exec/write\",\n  \"command/exec/terminate\": \"command/exec/terminate\",\n  \"command/exec/resize\": \"command/exec/resize\",\n  \"config/read\": \"config/read\",\n  \"externalAgentConfig/detect\": \"externalAgentConfig/detect\",\n  \"externalAgentConfig/import\": \"externalAgentConfig/import\",\n  \"externalAgentConfig/import/readHistories\": \"externalAgentConfig/import/readHistories\",\n  \"config/value/write\": \"config/value/write\",\n  \"config/batchWrite\": \"config/batchWrite\",\n  \"configRequirements/read\": \"configRequirements/read\",\n  \"account/read\": \"account/read\",\n  getConversationSummary: \"getConversationSummary\",\n  gitDiffToRemote: \"gitDiffToRemote\",\n  getAuthStatus: \"getAuthStatus\",\n  fuzzyFileSearch: \"fuzzyFileSearch\",\n} as const;\n\nexport const CLIENT_NOTIFICATION_METHODS = {\n  initialized: \"initialized\",\n} as const;\n\nexport const SERVER_REQUEST_METHODS = {\n  \"item/commandExecution/requestApproval\": \"item/commandExecution/requestApproval\",\n  \"item/fileChange/requestApproval\": \"item/fileChange/requestApproval\",\n  \"item/tool/requestUserInput\": \"item/tool/requestUserInput\",\n  \"mcpServer/elicitation/request\": \"mcpServer/elicitation/request\",\n  \"item/permissions/requestApproval\": \"item/permissions/requestApproval\",\n  \"item/tool/call\": \"item/tool/call\",\n  \"account/chatgptAuthTokens/refresh\": \"account/chatgptAuthTokens/refresh\",\n  \"attestation/generate\": \"attestation/generate\",\n  applyPatchApproval: \"applyPatchApproval\",\n  execCommandApproval: \"execCommandApproval\",\n} as const;\n\nexport const SERVER_NOTIFICATION_METHODS = {\n  error: \"error\",\n  \"thread/started\": \"thread/started\",\n  \"thread/status/changed\": \"thread/status/changed\",\n  \"thread/archived\": \"thread/archived\",\n  \"thread/deleted\": \"thread/deleted\",\n  \"thread/unarchived\": \"thread/unarchived\",\n  \"thread/closed\": \"thread/closed\",\n  \"skills/changed\": \"skills/changed\",\n  \"thread/name/updated\": \"thread/name/updated\",\n  \"thread/goal/updated\": \"thread/goal/updated\",\n  \"thread/goal/cleared\": \"thread/goal/cleared\",\n  \"thread/environment/connected\": \"thread/environment/connected\",\n  \"thread/environment/disconnected\": \"thread/environment/disconnected\",\n  \"thread/settings/updated\": \"thread/settings/updated\",\n  \"thread/tokenUsage/updated\": \"thread/tokenUsage/updated\",\n  \"turn/started\": \"turn/started\",\n  \"hook/started\": \"hook/started\",\n  \"turn/completed\": \"turn/completed\",\n  \"hook/completed\": \"hook/completed\",\n  \"turn/diff/updated\": \"turn/diff/updated\",\n  \"turn/plan/updated\": \"turn/plan/updated\",\n  \"item/started\": \"item/started\",\n  \"item/autoApprovalReview/started\": \"item/autoApprovalReview/started\",\n  \"item/autoApprovalReview/completed\": \"item/autoApprovalReview/completed\",\n  \"item/completed\": \"item/completed\",\n  \"rawResponseItem/completed\": \"rawResponseItem/completed\",\n  \"rawResponse/completed\": \"rawResponse/completed\",\n  \"item/agentMessage/delta\": \"item/agentMessage/delta\",\n  \"item/plan/delta\": \"item/plan/delta\",\n  \"command/exec/outputDelta\": \"command/exec/outputDelta\",\n  \"process/outputDelta\": \"process/outputDelta\",\n  \"process/exited\": \"process/exited\",\n  \"item/commandExecution/outputDelta\": \"item/commandExecution/outputDelta\",\n  \"item/commandExecution/terminalInteraction\": \"item/commandExecution/terminalInteraction\",\n  \"item/fileChange/outputDelta\": \"item/fileChange/outputDelta\",\n  \"item/fileChange/patchUpdated\": \"item/fileChange/patchUpdated\",\n  \"serverRequest/resolved\": \"serverRequest/resolved\",\n  \"item/mcpToolCall/progress\": \"item/mcpToolCall/progress\",\n  \"mcpServer/oauthLogin/completed\": \"mcpServer/oauthLogin/completed\",\n  \"mcpServer/startupStatus/updated\": \"mcpServer/startupStatus/updated\",\n  \"account/updated\": \"account/updated\",\n  \"account/rateLimits/updated\": \"account/rateLimits/updated\",\n  \"app/list/updated\": \"app/list/updated\",\n  \"remoteControl/status/changed\": \"remoteControl/status/changed\",\n  \"externalAgentConfig/import/progress\": \"externalAgentConfig/import/progress\",\n  \"externalAgentConfig/import/completed\": \"externalAgentConfig/import/completed\",\n  \"fs/changed\": \"fs/changed\",\n  \"item/reasoning/summaryTextDelta\": \"item/reasoning/summaryTextDelta\",\n  \"item/reasoning/summaryPartAdded\": \"item/reasoning/summaryPartAdded\",\n  \"item/reasoning/textDelta\": \"item/reasoning/textDelta\",\n  \"thread/compacted\": \"thread/compacted\",\n  \"model/rerouted\": \"model/rerouted\",\n  \"model/verification\": \"model/verification\",\n  \"turn/moderationMetadata\": \"turn/moderationMetadata\",\n  \"model/safetyBuffering/updated\": \"model/safetyBuffering/updated\",\n  warning: \"warning\",\n  guardianWarning: \"guardianWarning\",\n  deprecationNotice: \"deprecationNotice\",\n  configWarning: \"configWarning\",\n  \"fuzzyFileSearch/sessionUpdated\": \"fuzzyFileSearch/sessionUpdated\",\n  \"fuzzyFileSearch/sessionCompleted\": \"fuzzyFileSearch/sessionCompleted\",\n  \"thread/realtime/started\": \"thread/realtime/started\",\n  \"thread/realtime/itemAdded\": \"thread/realtime/itemAdded\",\n  \"thread/realtime/transcript/delta\": \"thread/realtime/transcript/delta\",\n  \"thread/realtime/transcript/done\": \"thread/realtime/transcript/done\",\n  \"thread/realtime/outputAudio/delta\": \"thread/realtime/outputAudio/delta\",\n  \"thread/realtime/sdp\": \"thread/realtime/sdp\",\n  \"thread/realtime/error\": \"thread/realtime/error\",\n  \"thread/realtime/closed\": \"thread/realtime/closed\",\n  \"windows/worldWritableWarning\": \"windows/worldWritableWarning\",\n  \"windowsSandbox/setupCompleted\": \"windowsSandbox/setupCompleted\",\n  \"account/login/completed\": \"account/login/completed\",\n} as const;\n\nexport type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;\nexport type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;\nexport type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;\nexport type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;\n\nexport interface ClientRequestParamsByMethod {\n  readonly initialize: CodexSchema.V1InitializeParams;\n  readonly \"thread/start\": CodexSchema.V2ThreadStartParams;\n  readonly \"thread/resume\": CodexSchema.V2ThreadResumeParams;\n  readonly \"thread/fork\": CodexSchema.V2ThreadForkParams;\n  readonly \"thread/archive\": CodexSchema.V2ThreadArchiveParams;\n  readonly \"thread/delete\": CodexSchema.V2ThreadDeleteParams;\n  readonly \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeParams;\n  readonly \"thread/name/set\": CodexSchema.V2ThreadSetNameParams;\n  readonly \"thread/goal/set\": CodexSchema.V2ThreadGoalSetParams;\n  readonly \"thread/goal/get\": CodexSchema.V2ThreadGoalGetParams;\n  readonly \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearParams;\n  readonly \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateParams;\n  readonly \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveParams;\n  readonly \"thread/compact/start\": CodexSchema.V2ThreadCompactStartParams;\n  readonly \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandParams;\n  readonly \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionParams;\n  readonly \"thread/rollback\": CodexSchema.V2ThreadRollbackParams;\n  readonly \"thread/list\": CodexSchema.V2ThreadListParams;\n  readonly \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListParams;\n  readonly \"thread/read\": CodexSchema.V2ThreadReadParams;\n  readonly \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsParams;\n  readonly \"skills/list\": CodexSchema.V2SkillsListParams;\n  readonly \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetParams;\n  readonly \"hooks/list\": CodexSchema.V2HooksListParams;\n  readonly \"marketplace/add\": CodexSchema.V2MarketplaceAddParams;\n  readonly \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveParams;\n  readonly \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeParams;\n  readonly \"plugin/list\": CodexSchema.V2PluginListParams;\n  readonly \"plugin/installed\": CodexSchema.V2PluginInstalledParams;\n  readonly \"plugin/read\": CodexSchema.V2PluginReadParams;\n  readonly \"plugin/skill/read\": CodexSchema.V2PluginSkillReadParams;\n  readonly \"plugin/share/save\": CodexSchema.V2PluginShareSaveParams;\n  readonly \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsParams;\n  readonly \"plugin/share/list\": CodexSchema.V2PluginShareListParams;\n  readonly \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutParams;\n  readonly \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteParams;\n  readonly \"app/read\": CodexSchema.V2AppsReadParams;\n  readonly \"app/list\": CodexSchema.V2AppsListParams;\n  readonly \"app/installed\": CodexSchema.V2AppsInstalledParams;\n  readonly \"fs/readFile\": CodexSchema.V2FsReadFileParams;\n  readonly \"fs/writeFile\": CodexSchema.V2FsWriteFileParams;\n  readonly \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryParams;\n  readonly \"fs/getMetadata\": CodexSchema.V2FsGetMetadataParams;\n  readonly \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryParams;\n  readonly \"fs/remove\": CodexSchema.V2FsRemoveParams;\n  readonly \"fs/copy\": CodexSchema.V2FsCopyParams;\n  readonly \"fs/watch\": CodexSchema.V2FsWatchParams;\n  readonly \"fs/unwatch\": CodexSchema.V2FsUnwatchParams;\n  readonly \"skills/config/write\": CodexSchema.V2SkillsConfigWriteParams;\n  readonly \"plugin/install\": CodexSchema.V2PluginInstallParams;\n  readonly \"plugin/uninstall\": CodexSchema.V2PluginUninstallParams;\n  readonly \"turn/start\": CodexSchema.V2TurnStartParams;\n  readonly \"turn/steer\": CodexSchema.V2TurnSteerParams;\n  readonly \"turn/interrupt\": CodexSchema.V2TurnInterruptParams;\n  readonly \"review/start\": CodexSchema.V2ReviewStartParams;\n  readonly \"model/list\": CodexSchema.V2ModelListParams;\n  readonly \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadParams;\n  readonly \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListParams;\n  readonly \"permissionProfile/list\": CodexSchema.V2PermissionProfileListParams;\n  readonly \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetParams;\n  readonly \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginParams;\n  readonly \"config/mcpServer/reload\": undefined;\n  readonly \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusParams;\n  readonly \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadParams;\n  readonly \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallParams;\n  readonly \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartParams;\n  readonly \"windowsSandbox/readiness\": undefined;\n  readonly \"account/login/start\": CodexSchema.V2LoginAccountParams;\n  readonly \"account/login/cancel\": CodexSchema.V2CancelLoginAccountParams;\n  readonly \"account/logout\": undefined;\n  readonly \"account/rateLimits/read\": undefined;\n  readonly \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditParams;\n  readonly \"account/usage/read\": undefined;\n  readonly \"account/workspaceMessages/read\": undefined;\n  readonly \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailParams;\n  readonly \"feedback/upload\": CodexSchema.V2FeedbackUploadParams;\n  readonly \"command/exec\": CodexSchema.V2CommandExecParams;\n  readonly \"command/exec/write\": CodexSchema.V2CommandExecWriteParams;\n  readonly \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateParams;\n  readonly \"command/exec/resize\": CodexSchema.V2CommandExecResizeParams;\n  readonly \"config/read\": CodexSchema.V2ConfigReadParams;\n  readonly \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectParams;\n  readonly \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportParams;\n  readonly \"externalAgentConfig/import/readHistories\": undefined;\n  readonly \"config/value/write\": CodexSchema.V2ConfigValueWriteParams;\n  readonly \"config/batchWrite\": CodexSchema.V2ConfigBatchWriteParams;\n  readonly \"configRequirements/read\": undefined;\n  readonly \"account/read\": CodexSchema.V2GetAccountParams;\n  readonly getConversationSummary: CodexSchema.GetConversationSummaryParams;\n  readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteParams;\n  readonly getAuthStatus: CodexSchema.GetAuthStatusParams;\n  readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams;\n}\n\nexport interface ClientRequestResponsesByMethod {\n  readonly initialize: CodexSchema.V1InitializeResponse;\n  readonly \"thread/start\": CodexSchema.V2ThreadStartResponse;\n  readonly \"thread/resume\": CodexSchema.V2ThreadResumeResponse;\n  readonly \"thread/fork\": CodexSchema.V2ThreadForkResponse;\n  readonly \"thread/archive\": CodexSchema.V2ThreadArchiveResponse;\n  readonly \"thread/delete\": CodexSchema.V2ThreadDeleteResponse;\n  readonly \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeResponse;\n  readonly \"thread/name/set\": CodexSchema.V2ThreadSetNameResponse;\n  readonly \"thread/goal/set\": CodexSchema.V2ThreadGoalSetResponse;\n  readonly \"thread/goal/get\": CodexSchema.V2ThreadGoalGetResponse;\n  readonly \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearResponse;\n  readonly \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateResponse;\n  readonly \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveResponse;\n  readonly \"thread/compact/start\": CodexSchema.V2ThreadCompactStartResponse;\n  readonly \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandResponse;\n  readonly \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionResponse;\n  readonly \"thread/rollback\": CodexSchema.V2ThreadRollbackResponse;\n  readonly \"thread/list\": CodexSchema.V2ThreadListResponse;\n  readonly \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListResponse;\n  readonly \"thread/read\": CodexSchema.V2ThreadReadResponse;\n  readonly \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsResponse;\n  readonly \"skills/list\": CodexSchema.V2SkillsListResponse;\n  readonly \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetResponse;\n  readonly \"hooks/list\": CodexSchema.V2HooksListResponse;\n  readonly \"marketplace/add\": CodexSchema.V2MarketplaceAddResponse;\n  readonly \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveResponse;\n  readonly \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeResponse;\n  readonly \"plugin/list\": CodexSchema.V2PluginListResponse;\n  readonly \"plugin/installed\": CodexSchema.V2PluginInstalledResponse;\n  readonly \"plugin/read\": CodexSchema.V2PluginReadResponse;\n  readonly \"plugin/skill/read\": CodexSchema.V2PluginSkillReadResponse;\n  readonly \"plugin/share/save\": CodexSchema.V2PluginShareSaveResponse;\n  readonly \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsResponse;\n  readonly \"plugin/share/list\": CodexSchema.V2PluginShareListResponse;\n  readonly \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutResponse;\n  readonly \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteResponse;\n  readonly \"app/read\": CodexSchema.V2AppsReadResponse;\n  readonly \"app/list\": CodexSchema.V2AppsListResponse;\n  readonly \"app/installed\": CodexSchema.V2AppsInstalledResponse;\n  readonly \"fs/readFile\": CodexSchema.V2FsReadFileResponse;\n  readonly \"fs/writeFile\": CodexSchema.V2FsWriteFileResponse;\n  readonly \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryResponse;\n  readonly \"fs/getMetadata\": CodexSchema.V2FsGetMetadataResponse;\n  readonly \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryResponse;\n  readonly \"fs/remove\": CodexSchema.V2FsRemoveResponse;\n  readonly \"fs/copy\": CodexSchema.V2FsCopyResponse;\n  readonly \"fs/watch\": CodexSchema.V2FsWatchResponse;\n  readonly \"fs/unwatch\": CodexSchema.V2FsUnwatchResponse;\n  readonly \"skills/config/write\": CodexSchema.V2SkillsConfigWriteResponse;\n  readonly \"plugin/install\": CodexSchema.V2PluginInstallResponse;\n  readonly \"plugin/uninstall\": CodexSchema.V2PluginUninstallResponse;\n  readonly \"turn/start\": CodexSchema.V2TurnStartResponse;\n  readonly \"turn/steer\": CodexSchema.V2TurnSteerResponse;\n  readonly \"turn/interrupt\": CodexSchema.V2TurnInterruptResponse;\n  readonly \"review/start\": CodexSchema.V2ReviewStartResponse;\n  readonly \"model/list\": CodexSchema.V2ModelListResponse;\n  readonly \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadResponse;\n  readonly \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListResponse;\n  readonly \"permissionProfile/list\": CodexSchema.V2PermissionProfileListResponse;\n  readonly \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetResponse;\n  readonly \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginResponse;\n  readonly \"config/mcpServer/reload\": CodexSchema.V2McpServerRefreshResponse;\n  readonly \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusResponse;\n  readonly \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadResponse;\n  readonly \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallResponse;\n  readonly \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartResponse;\n  readonly \"windowsSandbox/readiness\": CodexSchema.V2WindowsSandboxReadinessResponse;\n  readonly \"account/login/start\": CodexSchema.V2LoginAccountResponse;\n  readonly \"account/login/cancel\": CodexSchema.V2CancelLoginAccountResponse;\n  readonly \"account/logout\": CodexSchema.V2LogoutAccountResponse;\n  readonly \"account/rateLimits/read\": CodexSchema.V2GetAccountRateLimitsResponse;\n  readonly \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse;\n  readonly \"account/usage/read\": CodexSchema.V2GetAccountTokenUsageResponse;\n  readonly \"account/workspaceMessages/read\": CodexSchema.V2GetWorkspaceMessagesResponse;\n  readonly \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailResponse;\n  readonly \"feedback/upload\": CodexSchema.V2FeedbackUploadResponse;\n  readonly \"command/exec\": CodexSchema.V2CommandExecResponse;\n  readonly \"command/exec/write\": CodexSchema.V2CommandExecWriteResponse;\n  readonly \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateResponse;\n  readonly \"command/exec/resize\": CodexSchema.V2CommandExecResizeResponse;\n  readonly \"config/read\": CodexSchema.V2ConfigReadResponse;\n  readonly \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectResponse;\n  readonly \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportResponse;\n  readonly \"externalAgentConfig/import/readHistories\": CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse;\n  readonly \"config/value/write\": CodexSchema.V2ConfigWriteResponse;\n  readonly \"config/batchWrite\": CodexSchema.V2ConfigWriteResponse;\n  readonly \"configRequirements/read\": CodexSchema.V2ConfigRequirementsReadResponse;\n  readonly \"account/read\": CodexSchema.V2GetAccountResponse;\n  readonly getConversationSummary: CodexSchema.GetConversationSummaryResponse;\n  readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse;\n  readonly getAuthStatus: CodexSchema.GetAuthStatusResponse;\n  readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse;\n}\n\nexport interface ClientNotificationParamsByMethod {\n  readonly initialized: undefined;\n}\n\nexport interface ServerRequestParamsByMethod {\n  readonly \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalParams;\n  readonly \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalParams;\n  readonly \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputParams;\n  readonly \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestParams;\n  readonly \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalParams;\n  readonly \"item/tool/call\": CodexSchema.DynamicToolCallParams;\n  readonly \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshParams;\n  readonly \"attestation/generate\": CodexSchema.AttestationGenerateParams;\n  readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalParams;\n  readonly execCommandApproval: CodexSchema.ExecCommandApprovalParams;\n}\n\nexport interface ServerRequestResponsesByMethod {\n  readonly \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalResponse;\n  readonly \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalResponse;\n  readonly \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputResponse;\n  readonly \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestResponse;\n  readonly \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalResponse;\n  readonly \"item/tool/call\": CodexSchema.DynamicToolCallResponse;\n  readonly \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshResponse;\n  readonly \"attestation/generate\": CodexSchema.AttestationGenerateResponse;\n  readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse;\n  readonly execCommandApproval: CodexSchema.ExecCommandApprovalResponse;\n}\n\nexport interface ServerNotificationParamsByMethod {\n  readonly error: CodexSchema.V2ErrorNotification;\n  readonly \"thread/started\": CodexSchema.V2ThreadStartedNotification;\n  readonly \"thread/status/changed\": CodexSchema.V2ThreadStatusChangedNotification;\n  readonly \"thread/archived\": CodexSchema.V2ThreadArchivedNotification;\n  readonly \"thread/deleted\": CodexSchema.V2ThreadDeletedNotification;\n  readonly \"thread/unarchived\": CodexSchema.V2ThreadUnarchivedNotification;\n  readonly \"thread/closed\": CodexSchema.V2ThreadClosedNotification;\n  readonly \"skills/changed\": CodexSchema.V2SkillsChangedNotification;\n  readonly \"thread/name/updated\": CodexSchema.V2ThreadNameUpdatedNotification;\n  readonly \"thread/goal/updated\": CodexSchema.V2ThreadGoalUpdatedNotification;\n  readonly \"thread/goal/cleared\": CodexSchema.V2ThreadGoalClearedNotification;\n  readonly \"thread/environment/connected\": CodexSchema.V2EnvironmentConnectionNotification;\n  readonly \"thread/environment/disconnected\": CodexSchema.V2EnvironmentConnectionNotification;\n  readonly \"thread/settings/updated\": CodexSchema.V2ThreadSettingsUpdatedNotification;\n  readonly \"thread/tokenUsage/updated\": CodexSchema.V2ThreadTokenUsageUpdatedNotification;\n  readonly \"turn/started\": CodexSchema.V2TurnStartedNotification;\n  readonly \"hook/started\": CodexSchema.V2HookStartedNotification;\n  readonly \"turn/completed\": CodexSchema.V2TurnCompletedNotification;\n  readonly \"hook/completed\": CodexSchema.V2HookCompletedNotification;\n  readonly \"turn/diff/updated\": CodexSchema.V2TurnDiffUpdatedNotification;\n  readonly \"turn/plan/updated\": CodexSchema.V2TurnPlanUpdatedNotification;\n  readonly \"item/started\": CodexSchema.V2ItemStartedNotification;\n  readonly \"item/autoApprovalReview/started\": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification;\n  readonly \"item/autoApprovalReview/completed\": CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification;\n  readonly \"item/completed\": CodexSchema.V2ItemCompletedNotification;\n  readonly \"rawResponseItem/completed\": CodexSchema.V2RawResponseItemCompletedNotification;\n  readonly \"rawResponse/completed\": CodexSchema.V2RawResponseCompletedNotification;\n  readonly \"item/agentMessage/delta\": CodexSchema.V2AgentMessageDeltaNotification;\n  readonly \"item/plan/delta\": CodexSchema.V2PlanDeltaNotification;\n  readonly \"command/exec/outputDelta\": CodexSchema.V2CommandExecOutputDeltaNotification;\n  readonly \"process/outputDelta\": CodexSchema.V2ProcessOutputDeltaNotification;\n  readonly \"process/exited\": CodexSchema.V2ProcessExitedNotification;\n  readonly \"item/commandExecution/outputDelta\": CodexSchema.V2CommandExecutionOutputDeltaNotification;\n  readonly \"item/commandExecution/terminalInteraction\": CodexSchema.V2TerminalInteractionNotification;\n  readonly \"item/fileChange/outputDelta\": CodexSchema.V2FileChangeOutputDeltaNotification;\n  readonly \"item/fileChange/patchUpdated\": CodexSchema.V2FileChangePatchUpdatedNotification;\n  readonly \"serverRequest/resolved\": CodexSchema.V2ServerRequestResolvedNotification;\n  readonly \"item/mcpToolCall/progress\": CodexSchema.V2McpToolCallProgressNotification;\n  readonly \"mcpServer/oauthLogin/completed\": CodexSchema.V2McpServerOauthLoginCompletedNotification;\n  readonly \"mcpServer/startupStatus/updated\": CodexSchema.V2McpServerStatusUpdatedNotification;\n  readonly \"account/updated\": CodexSchema.V2AccountUpdatedNotification;\n  readonly \"account/rateLimits/updated\": CodexSchema.V2AccountRateLimitsUpdatedNotification;\n  readonly \"app/list/updated\": CodexSchema.V2AppListUpdatedNotification;\n  readonly \"remoteControl/status/changed\": CodexSchema.V2RemoteControlStatusChangedNotification;\n  readonly \"externalAgentConfig/import/progress\": CodexSchema.V2ExternalAgentConfigImportProgressNotification;\n  readonly \"externalAgentConfig/import/completed\": CodexSchema.V2ExternalAgentConfigImportCompletedNotification;\n  readonly \"fs/changed\": CodexSchema.V2FsChangedNotification;\n  readonly \"item/reasoning/summaryTextDelta\": CodexSchema.V2ReasoningSummaryTextDeltaNotification;\n  readonly \"item/reasoning/summaryPartAdded\": CodexSchema.V2ReasoningSummaryPartAddedNotification;\n  readonly \"item/reasoning/textDelta\": CodexSchema.V2ReasoningTextDeltaNotification;\n  readonly \"thread/compacted\": CodexSchema.V2ContextCompactedNotification;\n  readonly \"model/rerouted\": CodexSchema.V2ModelReroutedNotification;\n  readonly \"model/verification\": CodexSchema.V2ModelVerificationNotification;\n  readonly \"turn/moderationMetadata\": CodexSchema.V2TurnModerationMetadataNotification;\n  readonly \"model/safetyBuffering/updated\": CodexSchema.V2ModelSafetyBufferingUpdatedNotification;\n  readonly warning: CodexSchema.V2WarningNotification;\n  readonly guardianWarning: CodexSchema.V2GuardianWarningNotification;\n  readonly deprecationNotice: CodexSchema.V2DeprecationNoticeNotification;\n  readonly configWarning: CodexSchema.V2ConfigWarningNotification;\n  readonly \"fuzzyFileSearch/sessionUpdated\": CodexSchema.FuzzyFileSearchSessionUpdatedNotification;\n  readonly \"fuzzyFileSearch/sessionCompleted\": CodexSchema.FuzzyFileSearchSessionCompletedNotification;\n  readonly \"thread/realtime/started\": CodexSchema.V2ThreadRealtimeStartedNotification;\n  readonly \"thread/realtime/itemAdded\": CodexSchema.V2ThreadRealtimeItemAddedNotification;\n  readonly \"thread/realtime/transcript/delta\": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification;\n  readonly \"thread/realtime/transcript/done\": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification;\n  readonly \"thread/realtime/outputAudio/delta\": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification;\n  readonly \"thread/realtime/sdp\": CodexSchema.V2ThreadRealtimeSdpNotification;\n  readonly \"thread/realtime/error\": CodexSchema.V2ThreadRealtimeErrorNotification;\n  readonly \"thread/realtime/closed\": CodexSchema.V2ThreadRealtimeClosedNotification;\n  readonly \"windows/worldWritableWarning\": CodexSchema.V2WindowsWorldWritableWarningNotification;\n  readonly \"windowsSandbox/setupCompleted\": CodexSchema.V2WindowsSandboxSetupCompletedNotification;\n  readonly \"account/login/completed\": CodexSchema.V2AccountLoginCompletedNotification;\n}\n\nexport const CLIENT_REQUEST_PARAMS = {\n  initialize: CodexSchema.V1InitializeParams,\n  \"thread/start\": CodexSchema.V2ThreadStartParams,\n  \"thread/resume\": CodexSchema.V2ThreadResumeParams,\n  \"thread/fork\": CodexSchema.V2ThreadForkParams,\n  \"thread/archive\": CodexSchema.V2ThreadArchiveParams,\n  \"thread/delete\": CodexSchema.V2ThreadDeleteParams,\n  \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeParams,\n  \"thread/name/set\": CodexSchema.V2ThreadSetNameParams,\n  \"thread/goal/set\": CodexSchema.V2ThreadGoalSetParams,\n  \"thread/goal/get\": CodexSchema.V2ThreadGoalGetParams,\n  \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearParams,\n  \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateParams,\n  \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveParams,\n  \"thread/compact/start\": CodexSchema.V2ThreadCompactStartParams,\n  \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandParams,\n  \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionParams,\n  \"thread/rollback\": CodexSchema.V2ThreadRollbackParams,\n  \"thread/list\": CodexSchema.V2ThreadListParams,\n  \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListParams,\n  \"thread/read\": CodexSchema.V2ThreadReadParams,\n  \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsParams,\n  \"skills/list\": CodexSchema.V2SkillsListParams,\n  \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetParams,\n  \"hooks/list\": CodexSchema.V2HooksListParams,\n  \"marketplace/add\": CodexSchema.V2MarketplaceAddParams,\n  \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveParams,\n  \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeParams,\n  \"plugin/list\": CodexSchema.V2PluginListParams,\n  \"plugin/installed\": CodexSchema.V2PluginInstalledParams,\n  \"plugin/read\": CodexSchema.V2PluginReadParams,\n  \"plugin/skill/read\": CodexSchema.V2PluginSkillReadParams,\n  \"plugin/share/save\": CodexSchema.V2PluginShareSaveParams,\n  \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsParams,\n  \"plugin/share/list\": CodexSchema.V2PluginShareListParams,\n  \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutParams,\n  \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteParams,\n  \"app/read\": CodexSchema.V2AppsReadParams,\n  \"app/list\": CodexSchema.V2AppsListParams,\n  \"app/installed\": CodexSchema.V2AppsInstalledParams,\n  \"fs/readFile\": CodexSchema.V2FsReadFileParams,\n  \"fs/writeFile\": CodexSchema.V2FsWriteFileParams,\n  \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryParams,\n  \"fs/getMetadata\": CodexSchema.V2FsGetMetadataParams,\n  \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryParams,\n  \"fs/remove\": CodexSchema.V2FsRemoveParams,\n  \"fs/copy\": CodexSchema.V2FsCopyParams,\n  \"fs/watch\": CodexSchema.V2FsWatchParams,\n  \"fs/unwatch\": CodexSchema.V2FsUnwatchParams,\n  \"skills/config/write\": CodexSchema.V2SkillsConfigWriteParams,\n  \"plugin/install\": CodexSchema.V2PluginInstallParams,\n  \"plugin/uninstall\": CodexSchema.V2PluginUninstallParams,\n  \"turn/start\": CodexSchema.V2TurnStartParams,\n  \"turn/steer\": CodexSchema.V2TurnSteerParams,\n  \"turn/interrupt\": CodexSchema.V2TurnInterruptParams,\n  \"review/start\": CodexSchema.V2ReviewStartParams,\n  \"model/list\": CodexSchema.V2ModelListParams,\n  \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadParams,\n  \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListParams,\n  \"permissionProfile/list\": CodexSchema.V2PermissionProfileListParams,\n  \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetParams,\n  \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginParams,\n  \"config/mcpServer/reload\": undefined,\n  \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusParams,\n  \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadParams,\n  \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallParams,\n  \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartParams,\n  \"windowsSandbox/readiness\": undefined,\n  \"account/login/start\": CodexSchema.V2LoginAccountParams,\n  \"account/login/cancel\": CodexSchema.V2CancelLoginAccountParams,\n  \"account/logout\": undefined,\n  \"account/rateLimits/read\": undefined,\n  \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,\n  \"account/usage/read\": undefined,\n  \"account/workspaceMessages/read\": undefined,\n  \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailParams,\n  \"feedback/upload\": CodexSchema.V2FeedbackUploadParams,\n  \"command/exec\": CodexSchema.V2CommandExecParams,\n  \"command/exec/write\": CodexSchema.V2CommandExecWriteParams,\n  \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateParams,\n  \"command/exec/resize\": CodexSchema.V2CommandExecResizeParams,\n  \"config/read\": CodexSchema.V2ConfigReadParams,\n  \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectParams,\n  \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportParams,\n  \"externalAgentConfig/import/readHistories\": undefined,\n  \"config/value/write\": CodexSchema.V2ConfigValueWriteParams,\n  \"config/batchWrite\": CodexSchema.V2ConfigBatchWriteParams,\n  \"configRequirements/read\": undefined,\n  \"account/read\": CodexSchema.V2GetAccountParams,\n  getConversationSummary: CodexSchema.GetConversationSummaryParams,\n  gitDiffToRemote: CodexSchema.GitDiffToRemoteParams,\n  getAuthStatus: CodexSchema.GetAuthStatusParams,\n  fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams,\n} as const;\n\nexport const CLIENT_REQUEST_RESPONSES = {\n  initialize: CodexSchema.V1InitializeResponse,\n  \"thread/start\": CodexSchema.V2ThreadStartResponse,\n  \"thread/resume\": CodexSchema.V2ThreadResumeResponse,\n  \"thread/fork\": CodexSchema.V2ThreadForkResponse,\n  \"thread/archive\": CodexSchema.V2ThreadArchiveResponse,\n  \"thread/delete\": CodexSchema.V2ThreadDeleteResponse,\n  \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeResponse,\n  \"thread/name/set\": CodexSchema.V2ThreadSetNameResponse,\n  \"thread/goal/set\": CodexSchema.V2ThreadGoalSetResponse,\n  \"thread/goal/get\": CodexSchema.V2ThreadGoalGetResponse,\n  \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearResponse,\n  \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateResponse,\n  \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveResponse,\n  \"thread/compact/start\": CodexSchema.V2ThreadCompactStartResponse,\n  \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandResponse,\n  \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionResponse,\n  \"thread/rollback\": CodexSchema.V2ThreadRollbackResponse,\n  \"thread/list\": CodexSchema.V2ThreadListResponse,\n  \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListResponse,\n  \"thread/read\": CodexSchema.V2ThreadReadResponse,\n  \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsResponse,\n  \"skills/list\": CodexSchema.V2SkillsListResponse,\n  \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetResponse,\n  \"hooks/list\": CodexSchema.V2HooksListResponse,\n  \"marketplace/add\": CodexSchema.V2MarketplaceAddResponse,\n  \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveResponse,\n  \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeResponse,\n  \"plugin/list\": CodexSchema.V2PluginListResponse,\n  \"plugin/installed\": CodexSchema.V2PluginInstalledResponse,\n  \"plugin/read\": CodexSchema.V2PluginReadResponse,\n  \"plugin/skill/read\": CodexSchema.V2PluginSkillReadResponse,\n  \"plugin/share/save\": CodexSchema.V2PluginShareSaveResponse,\n  \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsResponse,\n  \"plugin/share/list\": CodexSchema.V2PluginShareListResponse,\n  \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutResponse,\n  \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteResponse,\n  \"app/read\": CodexSchema.V2AppsReadResponse,\n  \"app/list\": CodexSchema.V2AppsListResponse,\n  \"app/installed\": CodexSchema.V2AppsInstalledResponse,\n  \"fs/readFile\": CodexSchema.V2FsReadFileResponse,\n  \"fs/writeFile\": CodexSchema.V2FsWriteFileResponse,\n  \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryResponse,\n  \"fs/getMetadata\": CodexSchema.V2FsGetMetadataResponse,\n  \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryResponse,\n  \"fs/remove\": CodexSchema.V2FsRemoveResponse,\n  \"fs/copy\": CodexSchema.V2FsCopyResponse,\n  \"fs/watch\": CodexSchema.V2FsWatchResponse,\n  \"fs/unwatch\": CodexSchema.V2FsUnwatchResponse,\n  \"skills/config/write\": CodexSchema.V2SkillsConfigWriteResponse,\n  \"plugin/install\": CodexSchema.V2PluginInstallResponse,\n  \"plugin/uninstall\": CodexSchema.V2PluginUninstallResponse,\n  \"turn/start\": CodexSchema.V2TurnStartResponse,\n  \"turn/steer\": CodexSchema.V2TurnSteerResponse,\n  \"turn/interrupt\": CodexSchema.V2TurnInterruptResponse,\n  \"review/start\": CodexSchema.V2ReviewStartResponse,\n  \"model/list\": CodexSchema.V2ModelListResponse,\n  \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadResponse,\n  \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListResponse,\n  \"permissionProfile/list\": CodexSchema.V2PermissionProfileListResponse,\n  \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,\n  \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginResponse,\n  \"config/mcpServer/reload\": CodexSchema.V2McpServerRefreshResponse,\n  \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusResponse,\n  \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadResponse,\n  \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallResponse,\n  \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartResponse,\n  \"windowsSandbox/readiness\": CodexSchema.V2WindowsSandboxReadinessResponse,\n  \"account/login/start\": CodexSchema.V2LoginAccountResponse,\n  \"account/login/cancel\": CodexSchema.V2CancelLoginAccountResponse,\n  \"account/logout\": CodexSchema.V2LogoutAccountResponse,\n  \"account/rateLimits/read\": CodexSchema.V2GetAccountRateLimitsResponse,\n  \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,\n  \"account/usage/read\": CodexSchema.V2GetAccountTokenUsageResponse,\n  \"account/workspaceMessages/read\": CodexSchema.V2GetWorkspaceMessagesResponse,\n  \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailResponse,\n  \"feedback/upload\": CodexSchema.V2FeedbackUploadResponse,\n  \"command/exec\": CodexSchema.V2CommandExecResponse,\n  \"command/exec/write\": CodexSchema.V2CommandExecWriteResponse,\n  \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateResponse,\n  \"command/exec/resize\": CodexSchema.V2CommandExecResizeResponse,\n  \"config/read\": CodexSchema.V2ConfigReadResponse,\n  \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectResponse,\n  \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportResponse,\n  \"externalAgentConfig/import/readHistories\":\n    CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse,\n  \"config/value/write\": CodexSchema.V2ConfigWriteResponse,\n  \"config/batchWrite\": CodexSchema.V2ConfigWriteResponse,\n  \"configRequirements/read\": CodexSchema.V2ConfigRequirementsReadResponse,\n  \"account/read\": CodexSchema.V2GetAccountResponse,\n  getConversationSummary: CodexSchema.GetConversationSummaryResponse,\n  gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse,\n  getAuthStatus: CodexSchema.GetAuthStatusResponse,\n  fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse,\n} as const;\n\nexport const CLIENT_NOTIFICATION_PARAMS = {\n  initialized: undefined,\n} as const;\n\nexport const SERVER_REQUEST_PARAMS = {\n  \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalParams,\n  \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalParams,\n  \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputParams,\n  \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestParams,\n  \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalParams,\n  \"item/tool/call\": CodexSchema.DynamicToolCallParams,\n  \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshParams,\n  \"attestation/generate\": CodexSchema.AttestationGenerateParams,\n  applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,\n  execCommandApproval: CodexSchema.ExecCommandApprovalParams,\n} as const;\n\nexport const SERVER_REQUEST_RESPONSES = {\n  \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalResponse,\n  \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalResponse,\n  \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputResponse,\n  \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestResponse,\n  \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalResponse,\n  \"item/tool/call\": CodexSchema.DynamicToolCallResponse,\n  \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshResponse,\n  \"attestation/generate\": CodexSchema.AttestationGenerateResponse,\n  applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,\n  execCommandApproval: CodexSchema.ExecCommandApprovalResponse,\n} as const;\n\nexport const SERVER_NOTIFICATION_PARAMS = {\n  error: CodexSchema.V2ErrorNotification,\n  \"thread/started\": CodexSchema.V2ThreadStartedNotification,\n  \"thread/status/changed\": CodexSchema.V2ThreadStatusChangedNotification,\n  \"thread/archived\": CodexSchema.V2ThreadArchivedNotification,\n  \"thread/deleted\": CodexSchema.V2ThreadDeletedNotification,\n  \"thread/unarchived\": CodexSchema.V2ThreadUnarchivedNotification,\n  \"thread/closed\": CodexSchema.V2ThreadClosedNotification,\n  \"skills/changed\": CodexSchema.V2SkillsChangedNotification,\n  \"thread/name/updated\": CodexSchema.V2ThreadNameUpdatedNotification,\n  \"thread/goal/updated\": CodexSchema.V2ThreadGoalUpdatedNotification,\n  \"thread/goal/cleared\": CodexSchema.V2ThreadGoalClearedNotification,\n  \"thread/environment/connected\": CodexSchema.V2EnvironmentConnectionNotification,\n  \"thread/environment/disconnected\": CodexSchema.V2EnvironmentConnectionNotification,\n  \"thread/settings/updated\": CodexSchema.V2ThreadSettingsUpdatedNotification,\n  \"thread/tokenUsage/updated\": CodexSchema.V2ThreadTokenUsageUpdatedNotification,\n  \"turn/started\": CodexSchema.V2TurnStartedNotification,\n  \"hook/started\": CodexSchema.V2HookStartedNotification,\n  \"turn/completed\": CodexSchema.V2TurnCompletedNotification,\n  \"hook/completed\": CodexSchema.V2HookCompletedNotification,\n  \"turn/diff/updated\": CodexSchema.V2TurnDiffUpdatedNotification,\n  \"turn/plan/updated\": CodexSchema.V2TurnPlanUpdatedNotification,\n  \"item/started\": CodexSchema.V2ItemStartedNotification,\n  \"item/autoApprovalReview/started\": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,\n  \"item/autoApprovalReview/completed\":\n    CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,\n  \"item/completed\": CodexSchema.V2ItemCompletedNotification,\n  \"rawResponseItem/completed\": CodexSchema.V2RawResponseItemCompletedNotification,\n  \"rawResponse/completed\": CodexSchema.V2RawResponseCompletedNotification,\n  \"item/agentMessage/delta\": CodexSchema.V2AgentMessageDeltaNotification,\n  \"item/plan/delta\": CodexSchema.V2PlanDeltaNotification,\n  \"command/exec/outputDelta\": CodexSchema.V2CommandExecOutputDeltaNotification,\n  \"process/outputDelta\": CodexSchema.V2ProcessOutputDeltaNotification,\n  \"process/exited\": CodexSchema.V2ProcessExitedNotification,\n  \"item/commandExecution/outputDelta\": CodexSchema.V2CommandExecutionOutputDeltaNotification,\n  \"item/commandExecution/terminalInteraction\": CodexSchema.V2TerminalInteractionNotification,\n  \"item/fileChange/outputDelta\": CodexSchema.V2FileChangeOutputDeltaNotification,\n  \"item/fileChange/patchUpdated\": CodexSchema.V2FileChangePatchUpdatedNotification,\n  \"serverRequest/resolved\": CodexSchema.V2ServerRequestResolvedNotification,\n  \"item/mcpToolCall/progress\": CodexSchema.V2McpToolCallProgressNotification,\n  \"mcpServer/oauthLogin/completed\": CodexSchema.V2McpServerOauthLoginCompletedNotification,\n  \"mcpServer/startupStatus/updated\": CodexSchema.V2McpServerStatusUpdatedNotification,\n  \"account/updated\": CodexSchema.V2AccountUpdatedNotification,\n  \"account/rateLimits/updated\": CodexSchema.V2AccountRateLimitsUpdatedNotification,\n  \"app/list/updated\": CodexSchema.V2AppListUpdatedNotification,\n  \"remoteControl/status/changed\": CodexSchema.V2RemoteControlStatusChangedNotification,\n  \"externalAgentConfig/import/progress\":\n    CodexSchema.V2ExternalAgentConfigImportProgressNotification,\n  \"externalAgentConfig/import/completed\":\n    CodexSchema.V2ExternalAgentConfigImportCompletedNotification,\n  \"fs/changed\": CodexSchema.V2FsChangedNotification,\n  \"item/reasoning/summaryTextDelta\": CodexSchema.V2ReasoningSummaryTextDeltaNotification,\n  \"item/reasoning/summaryPartAdded\": CodexSchema.V2ReasoningSummaryPartAddedNotification,\n  \"item/reasoning/textDelta\": CodexSchema.V2ReasoningTextDeltaNotification,\n  \"thread/compacted\": CodexSchema.V2ContextCompactedNotification,\n  \"model/rerouted\": CodexSchema.V2ModelReroutedNotification,\n  \"model/verification\": CodexSchema.V2ModelVerificationNotification,\n  \"turn/moderationMetadata\": CodexSchema.V2TurnModerationMetadataNotification,\n  \"model/safetyBuffering/updated\": CodexSchema.V2ModelSafetyBufferingUpdatedNotification,\n  warning: CodexSchema.V2WarningNotification,\n  guardianWarning: CodexSchema.V2GuardianWarningNotification,\n  deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,\n  configWarning: CodexSchema.V2ConfigWarningNotification,\n  \"fuzzyFileSearch/sessionUpdated\": CodexSchema.FuzzyFileSearchSessionUpdatedNotification,\n  \"fuzzyFileSearch/sessionCompleted\": CodexSchema.FuzzyFileSearchSessionCompletedNotification,\n  \"thread/realtime/started\": CodexSchema.V2ThreadRealtimeStartedNotification,\n  \"thread/realtime/itemAdded\": CodexSchema.V2ThreadRealtimeItemAddedNotification,\n  \"thread/realtime/transcript/delta\": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,\n  \"thread/realtime/transcript/done\": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification,\n  \"thread/realtime/outputAudio/delta\": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,\n  \"thread/realtime/sdp\": CodexSchema.V2ThreadRealtimeSdpNotification,\n  \"thread/realtime/error\": CodexSchema.V2ThreadRealtimeErrorNotification,\n  \"thread/realtime/closed\": CodexSchema.V2ThreadRealtimeClosedNotification,\n  \"windows/worldWritableWarning\": CodexSchema.V2WindowsWorldWritableWarningNotification,\n  \"windowsSandbox/setupCompleted\": CodexSchema.V2WindowsSandboxSetupCompletedNotification,\n  \"account/login/completed\": CodexSchema.V2AccountLoginCompletedNotification,\n} as const;\n","// This file is generated by the effect-codex-app-server package. Do not edit manually.\n// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461\n\nimport * as CodexSchema from \"./schema.gen.ts\";\n\nexport const v1 = {\n  InitializeParams: CodexSchema.V1InitializeParams,\n  InitializeResponse: CodexSchema.V1InitializeResponse,\n} as const;\n\nexport const v2 = {\n  AccountLoginCompletedNotification: CodexSchema.V2AccountLoginCompletedNotification,\n  AccountRateLimitsUpdatedNotification: CodexSchema.V2AccountRateLimitsUpdatedNotification,\n  AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification,\n  AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification,\n  AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification,\n  AppsInstalledParams: CodexSchema.V2AppsInstalledParams,\n  AppsInstalledResponse: CodexSchema.V2AppsInstalledResponse,\n  AppsListParams: CodexSchema.V2AppsListParams,\n  AppsListResponse: CodexSchema.V2AppsListResponse,\n  AppsReadParams: CodexSchema.V2AppsReadParams,\n  AppsReadResponse: CodexSchema.V2AppsReadResponse,\n  CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams,\n  CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse,\n  CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification,\n  CommandExecParams: CodexSchema.V2CommandExecParams,\n  CommandExecResizeParams: CodexSchema.V2CommandExecResizeParams,\n  CommandExecResizeResponse: CodexSchema.V2CommandExecResizeResponse,\n  CommandExecResponse: CodexSchema.V2CommandExecResponse,\n  CommandExecTerminateParams: CodexSchema.V2CommandExecTerminateParams,\n  CommandExecTerminateResponse: CodexSchema.V2CommandExecTerminateResponse,\n  CommandExecutionOutputDeltaNotification: CodexSchema.V2CommandExecutionOutputDeltaNotification,\n  CommandExecWriteParams: CodexSchema.V2CommandExecWriteParams,\n  CommandExecWriteResponse: CodexSchema.V2CommandExecWriteResponse,\n  ConfigBatchWriteParams: CodexSchema.V2ConfigBatchWriteParams,\n  ConfigReadParams: CodexSchema.V2ConfigReadParams,\n  ConfigReadResponse: CodexSchema.V2ConfigReadResponse,\n  ConfigRequirementsReadResponse: CodexSchema.V2ConfigRequirementsReadResponse,\n  ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams,\n  ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification,\n  ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse,\n  ConsumeAccountRateLimitResetCreditParams: CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,\n  ConsumeAccountRateLimitResetCreditResponse:\n    CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,\n  ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification,\n  DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification,\n  EnvironmentConnectionNotification: CodexSchema.V2EnvironmentConnectionNotification,\n  ErrorNotification: CodexSchema.V2ErrorNotification,\n  ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams,\n  ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse,\n  ExperimentalFeatureListParams: CodexSchema.V2ExperimentalFeatureListParams,\n  ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse,\n  ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams,\n  ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse,\n  ExternalAgentConfigImportCompletedNotification:\n    CodexSchema.V2ExternalAgentConfigImportCompletedNotification,\n  ExternalAgentConfigImportHistoriesReadResponse:\n    CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse,\n  ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams,\n  ExternalAgentConfigImportProgressNotification:\n    CodexSchema.V2ExternalAgentConfigImportProgressNotification,\n  ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse,\n  FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams,\n  FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse,\n  FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification,\n  FileChangePatchUpdatedNotification: CodexSchema.V2FileChangePatchUpdatedNotification,\n  FsChangedNotification: CodexSchema.V2FsChangedNotification,\n  FsCopyParams: CodexSchema.V2FsCopyParams,\n  FsCopyResponse: CodexSchema.V2FsCopyResponse,\n  FsCreateDirectoryParams: CodexSchema.V2FsCreateDirectoryParams,\n  FsCreateDirectoryResponse: CodexSchema.V2FsCreateDirectoryResponse,\n  FsGetMetadataParams: CodexSchema.V2FsGetMetadataParams,\n  FsGetMetadataResponse: CodexSchema.V2FsGetMetadataResponse,\n  FsReadDirectoryParams: CodexSchema.V2FsReadDirectoryParams,\n  FsReadDirectoryResponse: CodexSchema.V2FsReadDirectoryResponse,\n  FsReadFileParams: CodexSchema.V2FsReadFileParams,\n  FsReadFileResponse: CodexSchema.V2FsReadFileResponse,\n  FsRemoveParams: CodexSchema.V2FsRemoveParams,\n  FsRemoveResponse: CodexSchema.V2FsRemoveResponse,\n  FsUnwatchParams: CodexSchema.V2FsUnwatchParams,\n  FsUnwatchResponse: CodexSchema.V2FsUnwatchResponse,\n  FsWatchParams: CodexSchema.V2FsWatchParams,\n  FsWatchResponse: CodexSchema.V2FsWatchResponse,\n  FsWriteFileParams: CodexSchema.V2FsWriteFileParams,\n  FsWriteFileResponse: CodexSchema.V2FsWriteFileResponse,\n  GetAccountParams: CodexSchema.V2GetAccountParams,\n  GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,\n  GetAccountResponse: CodexSchema.V2GetAccountResponse,\n  GetAccountTokenUsageResponse: CodexSchema.V2GetAccountTokenUsageResponse,\n  GetWorkspaceMessagesResponse: CodexSchema.V2GetWorkspaceMessagesResponse,\n  GuardianWarningNotification: CodexSchema.V2GuardianWarningNotification,\n  HookCompletedNotification: CodexSchema.V2HookCompletedNotification,\n  HooksListParams: CodexSchema.V2HooksListParams,\n  HooksListResponse: CodexSchema.V2HooksListResponse,\n  HookStartedNotification: CodexSchema.V2HookStartedNotification,\n  ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification,\n  ItemGuardianApprovalReviewCompletedNotification:\n    CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,\n  ItemGuardianApprovalReviewStartedNotification:\n    CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,\n  ItemStartedNotification: CodexSchema.V2ItemStartedNotification,\n  ListMcpServerStatusParams: CodexSchema.V2ListMcpServerStatusParams,\n  ListMcpServerStatusResponse: CodexSchema.V2ListMcpServerStatusResponse,\n  LoginAccountParams: CodexSchema.V2LoginAccountParams,\n  LoginAccountResponse: CodexSchema.V2LoginAccountResponse,\n  LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse,\n  MarketplaceAddParams: CodexSchema.V2MarketplaceAddParams,\n  MarketplaceAddResponse: CodexSchema.V2MarketplaceAddResponse,\n  MarketplaceRemoveParams: CodexSchema.V2MarketplaceRemoveParams,\n  MarketplaceRemoveResponse: CodexSchema.V2MarketplaceRemoveResponse,\n  MarketplaceUpgradeParams: CodexSchema.V2MarketplaceUpgradeParams,\n  MarketplaceUpgradeResponse: CodexSchema.V2MarketplaceUpgradeResponse,\n  McpResourceReadParams: CodexSchema.V2McpResourceReadParams,\n  McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse,\n  McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification,\n  McpServerOauthLoginParams: CodexSchema.V2McpServerOauthLoginParams,\n  McpServerOauthLoginResponse: CodexSchema.V2McpServerOauthLoginResponse,\n  McpServerRefreshResponse: CodexSchema.V2McpServerRefreshResponse,\n  McpServerStatusUpdatedNotification: CodexSchema.V2McpServerStatusUpdatedNotification,\n  McpServerToolCallParams: CodexSchema.V2McpServerToolCallParams,\n  McpServerToolCallResponse: CodexSchema.V2McpServerToolCallResponse,\n  McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification,\n  ModelListParams: CodexSchema.V2ModelListParams,\n  ModelListResponse: CodexSchema.V2ModelListResponse,\n  ModelProviderCapabilitiesReadParams: CodexSchema.V2ModelProviderCapabilitiesReadParams,\n  ModelProviderCapabilitiesReadResponse: CodexSchema.V2ModelProviderCapabilitiesReadResponse,\n  ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,\n  ModelSafetyBufferingUpdatedNotification: CodexSchema.V2ModelSafetyBufferingUpdatedNotification,\n  ModelVerificationNotification: CodexSchema.V2ModelVerificationNotification,\n  PermissionProfileListParams: CodexSchema.V2PermissionProfileListParams,\n  PermissionProfileListResponse: CodexSchema.V2PermissionProfileListResponse,\n  PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,\n  PluginInstalledParams: CodexSchema.V2PluginInstalledParams,\n  PluginInstalledResponse: CodexSchema.V2PluginInstalledResponse,\n  PluginInstallParams: CodexSchema.V2PluginInstallParams,\n  PluginInstallResponse: CodexSchema.V2PluginInstallResponse,\n  PluginListParams: CodexSchema.V2PluginListParams,\n  PluginListResponse: CodexSchema.V2PluginListResponse,\n  PluginReadParams: CodexSchema.V2PluginReadParams,\n  PluginReadResponse: CodexSchema.V2PluginReadResponse,\n  PluginShareCheckoutParams: CodexSchema.V2PluginShareCheckoutParams,\n  PluginShareCheckoutResponse: CodexSchema.V2PluginShareCheckoutResponse,\n  PluginShareDeleteParams: CodexSchema.V2PluginShareDeleteParams,\n  PluginShareDeleteResponse: CodexSchema.V2PluginShareDeleteResponse,\n  PluginShareListParams: CodexSchema.V2PluginShareListParams,\n  PluginShareListResponse: CodexSchema.V2PluginShareListResponse,\n  PluginShareSaveParams: CodexSchema.V2PluginShareSaveParams,\n  PluginShareSaveResponse: CodexSchema.V2PluginShareSaveResponse,\n  PluginShareUpdateTargetsParams: CodexSchema.V2PluginShareUpdateTargetsParams,\n  PluginShareUpdateTargetsResponse: CodexSchema.V2PluginShareUpdateTargetsResponse,\n  PluginSkillReadParams: CodexSchema.V2PluginSkillReadParams,\n  PluginSkillReadResponse: CodexSchema.V2PluginSkillReadResponse,\n  PluginUninstallParams: CodexSchema.V2PluginUninstallParams,\n  PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse,\n  ProcessExitedNotification: CodexSchema.V2ProcessExitedNotification,\n  ProcessOutputDeltaNotification: CodexSchema.V2ProcessOutputDeltaNotification,\n  RawResponseCompletedNotification: CodexSchema.V2RawResponseCompletedNotification,\n  RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification,\n  ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification,\n  ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification,\n  ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification,\n  RemoteControlStatusChangedNotification: CodexSchema.V2RemoteControlStatusChangedNotification,\n  ReviewStartParams: CodexSchema.V2ReviewStartParams,\n  ReviewStartResponse: CodexSchema.V2ReviewStartResponse,\n  SendAddCreditsNudgeEmailParams: CodexSchema.V2SendAddCreditsNudgeEmailParams,\n  SendAddCreditsNudgeEmailResponse: CodexSchema.V2SendAddCreditsNudgeEmailResponse,\n  ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification,\n  SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,\n  SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,\n  SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,\n  SkillsExtraRootsSetParams: CodexSchema.V2SkillsExtraRootsSetParams,\n  SkillsExtraRootsSetResponse: CodexSchema.V2SkillsExtraRootsSetResponse,\n  SkillsListParams: CodexSchema.V2SkillsListParams,\n  SkillsListResponse: CodexSchema.V2SkillsListResponse,\n  TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,\n  ThreadApproveGuardianDeniedActionParams: CodexSchema.V2ThreadApproveGuardianDeniedActionParams,\n  ThreadApproveGuardianDeniedActionResponse:\n    CodexSchema.V2ThreadApproveGuardianDeniedActionResponse,\n  ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification,\n  ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams,\n  ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse,\n  ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,\n  ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,\n  ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,\n  ThreadDeletedNotification: CodexSchema.V2ThreadDeletedNotification,\n  ThreadDeleteParams: CodexSchema.V2ThreadDeleteParams,\n  ThreadDeleteResponse: CodexSchema.V2ThreadDeleteResponse,\n  ThreadForkParams: CodexSchema.V2ThreadForkParams,\n  ThreadForkResponse: CodexSchema.V2ThreadForkResponse,\n  ThreadGoalClearedNotification: CodexSchema.V2ThreadGoalClearedNotification,\n  ThreadGoalClearParams: CodexSchema.V2ThreadGoalClearParams,\n  ThreadGoalClearResponse: CodexSchema.V2ThreadGoalClearResponse,\n  ThreadGoalGetParams: CodexSchema.V2ThreadGoalGetParams,\n  ThreadGoalGetResponse: CodexSchema.V2ThreadGoalGetResponse,\n  ThreadGoalSetParams: CodexSchema.V2ThreadGoalSetParams,\n  ThreadGoalSetResponse: CodexSchema.V2ThreadGoalSetResponse,\n  ThreadGoalUpdatedNotification: CodexSchema.V2ThreadGoalUpdatedNotification,\n  ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams,\n  ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse,\n  ThreadListParams: CodexSchema.V2ThreadListParams,\n  ThreadListResponse: CodexSchema.V2ThreadListResponse,\n  ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams,\n  ThreadLoadedListResponse: CodexSchema.V2ThreadLoadedListResponse,\n  ThreadMetadataUpdateParams: CodexSchema.V2ThreadMetadataUpdateParams,\n  ThreadMetadataUpdateResponse: CodexSchema.V2ThreadMetadataUpdateResponse,\n  ThreadNameUpdatedNotification: CodexSchema.V2ThreadNameUpdatedNotification,\n  ThreadReadParams: CodexSchema.V2ThreadReadParams,\n  ThreadReadResponse: CodexSchema.V2ThreadReadResponse,\n  ThreadRealtimeClosedNotification: CodexSchema.V2ThreadRealtimeClosedNotification,\n  ThreadRealtimeErrorNotification: CodexSchema.V2ThreadRealtimeErrorNotification,\n  ThreadRealtimeItemAddedNotification: CodexSchema.V2ThreadRealtimeItemAddedNotification,\n  ThreadRealtimeOutputAudioDeltaNotification:\n    CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,\n  ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification,\n  ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification,\n  ThreadRealtimeTranscriptDeltaNotification:\n    CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,\n  ThreadRealtimeTranscriptDoneNotification: CodexSchema.V2ThreadRealtimeTranscriptDoneNotification,\n  ThreadResumeParams: CodexSchema.V2ThreadResumeParams,\n  ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse,\n  ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams,\n  ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,\n  ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,\n  ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,\n  ThreadSettingsUpdatedNotification: CodexSchema.V2ThreadSettingsUpdatedNotification,\n  ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,\n  ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,\n  ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,\n  ThreadStartParams: CodexSchema.V2ThreadStartParams,\n  ThreadStartResponse: CodexSchema.V2ThreadStartResponse,\n  ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification,\n  ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification,\n  ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification,\n  ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams,\n  ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse,\n  ThreadUnsubscribeParams: CodexSchema.V2ThreadUnsubscribeParams,\n  ThreadUnsubscribeResponse: CodexSchema.V2ThreadUnsubscribeResponse,\n  TurnCompletedNotification: CodexSchema.V2TurnCompletedNotification,\n  TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,\n  TurnInterruptParams: CodexSchema.V2TurnInterruptParams,\n  TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,\n  TurnModerationMetadataNotification: CodexSchema.V2TurnModerationMetadataNotification,\n  TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,\n  TurnStartedNotification: CodexSchema.V2TurnStartedNotification,\n  TurnStartParams: CodexSchema.V2TurnStartParams,\n  TurnStartResponse: CodexSchema.V2TurnStartResponse,\n  TurnSteerParams: CodexSchema.V2TurnSteerParams,\n  TurnSteerResponse: CodexSchema.V2TurnSteerResponse,\n  WarningNotification: CodexSchema.V2WarningNotification,\n  WindowsSandboxReadinessResponse: CodexSchema.V2WindowsSandboxReadinessResponse,\n  WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification,\n  WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams,\n  WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse,\n  WindowsWorldWritableWarningNotification: CodexSchema.V2WindowsWorldWritableWarningNotification,\n} as const;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as CodexError from \"../errors.ts\";\n\nexport const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);\n\nexport const JsonRpcError = Schema.Struct({\n  code: Schema.Number,\n  message: Schema.String,\n  data: Schema.optional(Schema.Unknown),\n});\n\nexport const JsonRpcResponseEnvelope = Schema.Struct({\n  id: JsonRpcId,\n  result: Schema.optional(Schema.Unknown),\n  error: Schema.optional(JsonRpcError),\n});\n\nexport const decodeOptionalPayload = <A, I>(\n  method: string,\n  schema: Schema.Codec<A, I> | undefined,\n  raw: unknown,\n): Effect.Effect<A, CodexError.CodexAppServerRequestError> => {\n  if (!schema) {\n    if (raw === undefined) {\n      return Effect.sync(() => undefined as A);\n    }\n    return Effect.fail(\n      CodexError.CodexAppServerRequestError.unexpectedPayload(method, \"decode-payload\", raw),\n    );\n  }\n\n  return Schema.decodeUnknownEffect(schema)(raw).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerRequestError.invalidPayload(method, \"decode-payload\", error),\n    ),\n  );\n};\n\nexport const encodeOptionalPayload = <A, I>(\n  method: string,\n  schema: Schema.Codec<A, I> | undefined,\n  payload: A,\n): Effect.Effect<I | undefined, CodexError.CodexAppServerRequestError> => {\n  if (!schema) {\n    if (payload === undefined) {\n      return Effect.sync(() => undefined);\n    }\n    return Effect.fail(\n      CodexError.CodexAppServerRequestError.unexpectedPayload(method, \"encode-payload\", payload),\n    );\n  }\n\n  return Schema.encodeEffect(schema)(payload).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerRequestError.invalidPayload(method, \"encode-payload\", error),\n    ),\n  );\n};\n\nexport const decodeNotificationPayload = <A, I>(\n  method: string,\n  schema: Schema.Codec<A, I> | undefined,\n  raw: unknown,\n): Effect.Effect<A, CodexError.CodexAppServerProtocolParseError> =>\n  decodeOptionalPayload(method, schema, raw).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerProtocolParseError.fromRequestError(\n        \"decode-notification-payload\",\n        method,\n        error,\n      ),\n    ),\n  );\n\nexport const runHandler = Effect.fnUntraced(function* <A, B>(\n  handler: ((payload: A) => Effect.Effect<B, CodexError.CodexAppServerError>) | undefined,\n  payload: A,\n  method: string,\n) {\n  if (!handler) {\n    return yield* CodexError.CodexAppServerRequestError.methodNotFound(method);\n  }\n\n  return yield* handler(payload).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerRequestError.fromAppServerError(error, method),\n    ),\n  );\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as CodexError from \"./errors.ts\";\nimport { JsonRpcId, JsonRpcResponseEnvelope } from \"./_internal/shared.ts\";\nconst isJsonRpcId = Schema.is(JsonRpcId);\nconst isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);\nconst isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);\n\nexport interface CodexAppServerProtocolLogEvent {\n  readonly direction: \"incoming\" | \"outgoing\";\n  readonly stage: \"raw\" | \"decoded\" | \"decode_failed\";\n  readonly payload: unknown;\n}\n\nexport interface CodexAppServerIncomingNotification {\n  readonly method: string;\n  readonly params?: unknown;\n}\n\nexport interface CodexAppServerIncomingRequest {\n  readonly id: string | number;\n  readonly method: string;\n  readonly params?: unknown;\n}\n\nexport interface CodexAppServerPatchedProtocolOptions {\n  readonly stdio: Stdio.Stdio;\n  readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;\n  readonly onNotification?: (\n    notification: CodexAppServerIncomingNotification,\n  ) => Effect.Effect<void, never>;\n  readonly onRequest?: (\n    request: CodexAppServerIncomingRequest,\n  ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\n  readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;\n}\n\nexport interface CodexAppServerPatchedProtocol {\n  readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;\n  readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;\n  readonly request: (\n    method: string,\n    payload?: unknown,\n  ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\n  readonly notify: (\n    method: string,\n    payload?: unknown,\n  ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n  readonly respond: (\n    requestId: string | number,\n    result: unknown,\n  ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n  readonly respondError: (\n    requestId: string | number,\n    error: CodexError.CodexAppServerRequestError,\n  ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n}\n\ninterface CodexAppServerPendingRequest {\n  readonly deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>;\n  readonly method: string;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null;\n}\n\nfunction isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {\n  if (!isObject(value) || typeof value.method !== \"string\") {\n    return false;\n  }\n  return isJsonRpcId(value.id);\n}\n\nfunction isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {\n  return isObject(value) && typeof value.method === \"string\" && !(\"id\" in value);\n}\n\nfunction isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {\n  return isJsonRpcResponseEnvelope(value);\n}\n\nconst encodeJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\nconst decodeJsonString = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst encodeWireMessage = (\n  message: Record<string, unknown>,\n): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>\n  encodeJsonString(message).pipe(\n    Effect.map((encoded) => `${encoded}\\n`),\n    Effect.mapError((cause) => {\n      const method = typeof message.method === \"string\" ? message.method : undefined;\n      const requestId =\n        typeof message.id === \"string\" || typeof message.id === \"number\"\n          ? String(message.id)\n          : undefined;\n      return CodexError.CodexAppServerProtocolParseError.fromSchemaError(\n        \"encode-wire-message\",\n        cause,\n        {\n          ...(method === undefined ? {} : { method }),\n          ...(requestId === undefined ? {} : { requestId }),\n        },\n      );\n    }),\n  );\n\nconst decodeWireMessage = (\n  line: string,\n): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>\n  decodeJsonString(line).pipe(\n    Effect.mapError((cause) =>\n      CodexError.CodexAppServerProtocolParseError.fromSchemaError(\"decode-wire-message\", cause),\n    ),\n  );\n\nconst normalizeIncomingError = (\n  error: unknown,\n  operation: CodexError.CodexAppServerTransportOperation,\n): CodexError.CodexAppServerError =>\n  isCodexAppServerError(error)\n    ? error\n    : new CodexError.CodexAppServerTransportError({\n        operation,\n        cause: error,\n      });\n\nconst toProtocolMessage = (\n  requestId: string | number,\n  fields: {\n    readonly result?: unknown;\n    readonly error?: CodexError.CodexAppServerProtocolErrorShape;\n  },\n): { readonly [key: string]: unknown } => ({\n  id: requestId,\n  ...(fields.result !== undefined ? { result: fields.result } : {}),\n  ...(fields.error !== undefined ? { error: fields.error } : {}),\n});\n\nexport const makeCodexAppServerPatchedProtocol = Effect.fn(\"makeCodexAppServerPatchedProtocol\")(\n  function* (\n    options: CodexAppServerPatchedProtocolOptions,\n  ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {\n    const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();\n    const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();\n    const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();\n    const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());\n    const nextRequestId = yield* Ref.make(1);\n    const remainder = yield* Ref.make(\"\");\n    const terminationHandled = yield* Ref.make(false);\n\n    const logProtocol = (event: CodexAppServerProtocolLogEvent) => {\n      if (event.direction === \"incoming\" && !options.logIncoming) {\n        return Effect.void;\n      }\n      if (event.direction === \"outgoing\" && !options.logOutgoing) {\n        return Effect.void;\n      }\n      return (\n        options.logger?.(event) ??\n        Effect.logDebug(\"Codex App Server protocol event\").pipe(Effect.annotateLogs({ event }))\n      );\n    };\n\n    const failAllPending = (error: CodexError.CodexAppServerError) =>\n      Ref.get(pending).pipe(\n        Effect.flatMap((current) =>\n          Effect.forEach([...current.values()], ({ deferred }) => Deferred.fail(deferred, error), {\n            discard: true,\n          }),\n        ),\n        Effect.andThen(Ref.set(pending, new Map())),\n      );\n\n    const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>\n      Ref.modify(terminationHandled, (handled) => {\n        if (handled) {\n          return [Effect.void, true] as const;\n        }\n        return [\n          Effect.gen(function* () {\n            const error = yield* classify();\n            yield* failAllPending(error);\n            yield* Queue.end(outgoing);\n            if (options.onTermination) {\n              yield* options.onTermination(error);\n            }\n          }),\n          true,\n        ] as const;\n      }).pipe(Effect.flatten);\n\n    const offerOutgoing = (message: Record<string, unknown>) =>\n      Effect.gen(function* () {\n        yield* logProtocol({\n          direction: \"outgoing\",\n          stage: \"decoded\",\n          payload: message,\n        });\n        const encoded = yield* encodeWireMessage(message);\n        yield* logProtocol({\n          direction: \"outgoing\",\n          stage: \"raw\",\n          payload: encoded,\n        });\n        yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);\n      });\n\n    const removePending = (requestId: string) =>\n      Ref.update(pending, (current) => {\n        if (!current.has(requestId)) {\n          return current;\n        }\n        const next = new Map(current);\n        next.delete(requestId);\n        return next;\n      });\n\n    const resolvePending = (\n      requestId: string,\n      handler: (pendingRequest: CodexAppServerPendingRequest) => Effect.Effect<void>,\n    ) =>\n      Ref.modify(pending, (current) => {\n        const pendingRequest = current.get(requestId);\n        if (!pendingRequest) {\n          return [Effect.void, current] as const;\n        }\n        const next = new Map(current);\n        next.delete(requestId);\n        return [handler(pendingRequest), next] as const;\n      }).pipe(Effect.flatten);\n\n    const respond = (requestId: string | number, result: unknown) =>\n      offerOutgoing(toProtocolMessage(requestId, { result }));\n\n    const respondError = (\n      requestId: string | number,\n      error: CodexError.CodexAppServerRequestError,\n    ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));\n\n    const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {\n      const requestId = String(response.id);\n      const protocolError = response.error;\n      if (protocolError !== undefined) {\n        return resolvePending(requestId, ({ deferred, method }) =>\n          Deferred.fail(\n            deferred,\n            CodexError.CodexAppServerRequestError.fromProtocolError(\n              protocolError,\n              method,\n              requestId,\n            ),\n          ),\n        );\n      }\n      return resolvePending(requestId, ({ deferred }) =>\n        Deferred.succeed(deferred, response.result),\n      );\n    };\n\n    const handleRequest = (request: CodexAppServerIncomingRequest) =>\n      Queue.offer(incomingRequests, request).pipe(\n        Effect.andThen(\n          options.onRequest\n            ? options.onRequest(request).pipe(\n                Effect.matchEffect({\n                  onFailure: (error) =>\n                    respondError(\n                      request.id,\n                      CodexError.CodexAppServerRequestError.fromAppServerError(\n                        error,\n                        request.method,\n                      ),\n                    ),\n                  onSuccess: (result) => respond(request.id, result),\n                }),\n              )\n            : Effect.void,\n        ),\n        Effect.asVoid,\n      );\n\n    const handleNotification = (notification: CodexAppServerIncomingNotification) =>\n      Queue.offer(incomingNotifications, notification).pipe(\n        Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),\n        Effect.asVoid,\n      );\n\n    const routeMessage = (\n      message: unknown,\n    ): Effect.Effect<void, CodexError.CodexAppServerError> => {\n      if (isIncomingRequest(message)) {\n        return handleRequest(message);\n      }\n      if (isIncomingNotification(message)) {\n        return handleNotification(message);\n      }\n      if (isIncomingResponse(message)) {\n        return handleResponse(message);\n      }\n      return Effect.fail(\n        CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message),\n      );\n    };\n\n    const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {\n      if (line.trim().length === 0) {\n        return Effect.void;\n      }\n      return logProtocol({\n        direction: \"incoming\",\n        stage: \"raw\",\n        payload: line,\n      }).pipe(\n        Effect.flatMap(() => decodeWireMessage(line)),\n        Effect.tap((decoded) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decoded\",\n            payload: decoded,\n          }),\n        ),\n        Effect.tapErrorTag(\"CodexAppServerProtocolParseError\", (error) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decode_failed\",\n            payload: {\n              operation: error.operation,\n              ...(error.method === undefined ? {} : { method: error.method }),\n              ...(error.requestId === undefined ? {} : { requestId: error.requestId }),\n              ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),\n              ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),\n              ...(error.maximumPathDepth === undefined\n                ? {}\n                : { maximumPathDepth: error.maximumPathDepth }),\n            },\n          }),\n        ),\n        Effect.flatMap(routeMessage),\n      );\n    };\n\n    yield* options.stdio.stdin.pipe(\n      Stream.decodeText(),\n      Stream.runForEach((chunk) =>\n        Ref.modify(remainder, (current) => {\n          const combined = current + chunk;\n          const lines = combined.split(\"\\n\");\n          const nextRemainder = lines.pop() ?? \"\";\n          return [lines.map((line) => line.replace(/\\r$/, \"\")), nextRemainder] as const;\n        }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),\n      ),\n      Effect.matchEffect({\n        onFailure: (error) =>\n          handleTermination(() =>\n            Effect.succeed(normalizeIncomingError(error, \"read-input-stream\")),\n          ),\n        onSuccess: () =>\n          Ref.get(remainder).pipe(\n            Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))),\n            Effect.matchEffect({\n              onFailure: (error) => handleTermination(() => Effect.succeed(error)),\n              onSuccess: () =>\n                handleTermination(\n                  () =>\n                    options.terminationError ??\n                    Effect.succeed(new CodexError.CodexAppServerInputStreamEndedError({})),\n                ),\n            }),\n          ),\n      }),\n      Effect.forkScoped,\n    );\n\n    yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);\n\n    const request = (method: string, payload?: unknown) =>\n      Effect.gen(function* () {\n        const requestId = yield* Ref.modify(\n          nextRequestId,\n          (current) => [current, current + 1] as const,\n        );\n        const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();\n        yield* Ref.update(pending, (current) =>\n          new Map(current).set(String(requestId), { deferred, method }),\n        );\n        yield* offerOutgoing({\n          id: requestId,\n          method,\n          ...(payload !== undefined ? { params: payload } : {}),\n        }).pipe(Effect.tapError(() => removePending(String(requestId))));\n        return yield* Deferred.await(deferred).pipe(\n          Effect.onInterrupt(() => removePending(String(requestId))),\n        );\n      });\n\n    const notify = (method: string, payload?: unknown) =>\n      offerOutgoing({\n        method,\n        ...(payload !== undefined ? { params: payload } : {}),\n      });\n\n    return {\n      incomingNotifications: Stream.fromQueue(incomingNotifications),\n      incomingRequests: Stream.fromQueue(incomingRequests),\n      request,\n      notify,\n      respond,\n      respondError,\n    } satisfies CodexAppServerPatchedProtocol;\n  },\n);\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as CodexError from \"../errors.ts\";\n\nconst encoder = new TextEncoder();\n\nexport const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>\n  Stdio.make({\n    args: Effect.succeed([]),\n    stdin: handle.stdout,\n    stdout: () =>\n      Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>\n        typeof chunk === \"string\" ? encoder.encode(chunk) : chunk,\n      ),\n    stderr: () => Sink.drain,\n  });\n\nexport const makeInMemoryStdio = Effect.fn(\"makeInMemoryStdio\")(function* () {\n  const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();\n  const output = yield* Queue.unbounded<string>();\n  const decoder = new TextDecoder();\n\n  return {\n    stdio: Stdio.make({\n      args: Effect.succeed([]),\n      stdin: Stream.fromQueue(input),\n      stdout: () =>\n        Sink.forEach((chunk: string | Uint8Array) =>\n          Queue.offer(\n            output,\n            typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true }),\n          ),\n        ),\n      stderr: () => Sink.drain,\n    }),\n    input,\n    output,\n  };\n});\n\ntype ChildProcessTerminationHandle = Pick<\n  ChildProcessSpawner.ChildProcessHandle,\n  \"exitCode\" | \"pid\"\n>;\n\nexport const makeTerminationError = (\n  handle: ChildProcessTerminationHandle,\n): Effect.Effect<CodexError.CodexAppServerError> =>\n  Effect.match(handle.exitCode, {\n    onFailure: (cause) =>\n      new CodexError.CodexAppServerTransportError({\n        operation: \"read-process-exit-status\",\n        pid: handle.pid,\n        cause,\n      }),\n    onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),\n  });\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\nimport * as CodexRpc from \"./_generated/meta.gen.ts\";\nimport * as CodexError from \"./errors.ts\";\nimport * as CodexProtocol from \"./protocol.ts\";\nimport {\n  decodeNotificationPayload,\n  decodeOptionalPayload,\n  encodeOptionalPayload,\n  runHandler,\n} from \"./_internal/shared.ts\";\nimport { makeChildStdio, makeTerminationError } from \"./_internal/stdio.ts\";\n\nexport interface CodexAppServerClientOptions {\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (\n    event: CodexProtocol.CodexAppServerProtocolLogEvent,\n  ) => Effect.Effect<void, never>;\n}\n\ninterface CodexAppServerClientRaw {\n  readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol[\"incomingNotifications\"];\n  readonly requests: CodexProtocol.CodexAppServerPatchedProtocol[\"incomingRequests\"];\n  readonly request: CodexProtocol.CodexAppServerPatchedProtocol[\"request\"];\n  readonly notify: CodexProtocol.CodexAppServerPatchedProtocol[\"notify\"];\n  readonly respond: CodexProtocol.CodexAppServerPatchedProtocol[\"respond\"];\n  readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol[\"respondError\"];\n}\n\nexport class CodexAppServerClient extends Context.Service<\n  CodexAppServerClient,\n  {\n    readonly raw: CodexAppServerClientRaw;\n    readonly request: <M extends CodexRpc.ClientRequestMethod>(\n      method: M,\n      payload: CodexRpc.ClientRequestParamsByMethod[M],\n    ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;\n    readonly notify: <M extends CodexRpc.ClientNotificationMethod>(\n      method: M,\n      payload: CodexRpc.ClientNotificationParamsByMethod[M],\n    ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n    readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(\n      method: M,\n      handler: (\n        payload: CodexRpc.ServerRequestParamsByMethod[M],\n      ) => Effect.Effect<\n        CodexRpc.ServerRequestResponsesByMethod[M],\n        CodexError.CodexAppServerError\n      >,\n    ) => Effect.Effect<void>;\n    readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(\n      method: M,\n      handler: (\n        payload: CodexRpc.ServerNotificationParamsByMethod[M],\n      ) => Effect.Effect<void, CodexError.CodexAppServerError>,\n    ) => Effect.Effect<void>;\n    readonly handleUnknownServerRequest: (\n      handler: (\n        method: string,\n        params: unknown,\n      ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,\n    ) => Effect.Effect<void>;\n    readonly handleUnknownServerNotification: (\n      handler: (\n        method: string,\n        params: unknown,\n      ) => Effect.Effect<void, CodexError.CodexAppServerError>,\n    ) => Effect.Effect<void>;\n  }\n>()(\"effect-codex-app-server/client/CodexAppServerClient\") {}\n\ntype ServerRequestHandler = (\n  payload: unknown,\n) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\ntype ServerNotificationHandler = (\n  payload: unknown,\n) => Effect.Effect<void, CodexError.CodexAppServerError>;\n\nexport const make = Effect.fn(\"effect-codex-app-server/CodexAppServerClient.make\")(function* (\n  stdio: Stdio.Stdio,\n  options: CodexAppServerClientOptions = {},\n  terminationError?: Effect.Effect<CodexError.CodexAppServerError>,\n): Effect.fn.Return<CodexAppServerClient[\"Service\"], never, Scope.Scope> {\n  const requestHandlers = new Map<string, ServerRequestHandler>();\n  const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();\n  let unknownRequestHandler:\n    | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)\n    | undefined;\n  let unknownNotificationHandler:\n    | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)\n    | undefined;\n\n  const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>\n    | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;\n\n  const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<\n        CodexRpc.ServerRequestResponsesByMethod[M],\n        CodexRpc.ServerRequestResponsesByMethod[M]\n      >\n    | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;\n\n  const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>\n    | undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;\n\n  const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<\n        CodexRpc.ClientRequestResponsesByMethod[M],\n        CodexRpc.ClientRequestResponsesByMethod[M]\n      >\n    | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;\n\n  const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(\n    method: M,\n  ):\n    | Schema.Codec<\n        CodexRpc.ClientNotificationParamsByMethod[M],\n        CodexRpc.ClientNotificationParamsByMethod[M]\n      >\n    | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;\n\n  const dispatchNotification = (\n    notification: CodexProtocol.CodexAppServerIncomingNotification,\n  ): Effect.Effect<void, never> => {\n    const schema =\n      notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS\n        ? CodexRpc.SERVER_NOTIFICATION_PARAMS[\n            notification.method as CodexRpc.ServerNotificationMethod\n          ]\n        : undefined;\n    const handlers = notificationHandlers.get(notification.method) ?? [];\n\n    if (schema) {\n      return decodeNotificationPayload(notification.method, schema, notification.params).pipe(\n        Effect.flatMap((decoded) =>\n          Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),\n        ),\n        Effect.catch(() => Effect.void),\n      );\n    }\n\n    return unknownNotificationHandler\n      ? unknownNotificationHandler(notification.method, notification.params).pipe(\n          Effect.catch(() => Effect.void),\n        )\n      : Effect.void;\n  };\n\n  const dispatchRequest = (\n    request: CodexProtocol.CodexAppServerIncomingRequest,\n  ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {\n    if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {\n      const method = request.method as CodexRpc.ServerRequestMethod;\n      const payloadSchema = getServerRequestParamSchema(method);\n      const responseSchema = getServerRequestResponseSchema(method);\n      const handler = requestHandlers.get(method);\n\n      return decodeOptionalPayload(method, payloadSchema, request.params).pipe(\n        Effect.flatMap((decoded) => runHandler(handler, decoded, method)),\n        Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),\n      );\n    }\n\n    return unknownRequestHandler\n      ? unknownRequestHandler(request.method, request.params)\n      : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));\n  };\n\n  const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({\n    stdio,\n    ...(terminationError ? { terminationError } : {}),\n    ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),\n    ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),\n    ...(options.logger ? { logger: options.logger } : {}),\n    onNotification: dispatchNotification,\n    onRequest: dispatchRequest,\n  });\n\n  const request = <M extends CodexRpc.ClientRequestMethod>(\n    method: M,\n    payload: CodexRpc.ClientRequestParamsByMethod[M],\n  ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>\n    encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(\n      Effect.flatMap((encoded) => transport.request(method, encoded)),\n      Effect.flatMap(\n        (\n          raw,\n        ): Effect.Effect<\n          CodexRpc.ClientRequestResponsesByMethod[M],\n          CodexError.CodexAppServerError\n        > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),\n      ),\n    );\n\n  const notify = <M extends CodexRpc.ClientNotificationMethod>(\n    method: M,\n    payload: CodexRpc.ClientNotificationParamsByMethod[M],\n  ) =>\n    encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(\n      Effect.flatMap((encoded) => transport.notify(method, encoded)),\n    );\n\n  return CodexAppServerClient.of({\n    raw: {\n      notifications: transport.incomingNotifications,\n      requests: transport.incomingRequests,\n      request: transport.request,\n      notify: transport.notify,\n      respond: transport.respond,\n      respondError: transport.respondError,\n    },\n    request,\n    notify,\n    handleServerRequest: (method, handler) =>\n      Effect.sync(() => {\n        requestHandlers.set(method, handler as ServerRequestHandler);\n      }),\n    handleServerNotification: (method, handler) =>\n      Effect.sync(() => {\n        const current = notificationHandlers.get(method) ?? [];\n        current.push(handler as ServerNotificationHandler);\n        notificationHandlers.set(method, current);\n      }),\n    handleUnknownServerRequest: (handler) =>\n      Effect.sync(() => {\n        unknownRequestHandler = handler;\n      }),\n    handleUnknownServerNotification: (handler) =>\n      Effect.sync(() => {\n        unknownNotificationHandler = handler;\n      }),\n  });\n});\n\nexport const layer = (\n  stdio: Stdio.Stdio,\n  options: CodexAppServerClientOptions = {},\n): Layer.Layer<CodexAppServerClient> => Layer.effect(CodexAppServerClient, make(stdio, options));\n\nexport const layerChildProcess = (\n  handle: ChildProcessSpawner.ChildProcessHandle,\n  options: CodexAppServerClientOptions = {},\n): Layer.Layer<CodexAppServerClient> =>\n  Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));\n\nconst makeChildProcessClient = Effect.fn(\n  \"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient\",\n)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {\n  yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);\n  return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));\n});\n","import * as Cause from \"effect/Cause\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Types from \"effect/Types\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as CodexClient from \"effect-codex-app-server/client\";\nimport * as CodexSchema from \"effect-codex-app-server/schema\";\nimport * as CodexErrors from \"effect-codex-app-server/errors\";\n\nimport type {\n  CodexSettings,\n  ServerProvider,\n  ServerProviderState,\n  ModelCapabilities,\n  ProviderOptionDescriptor,\n  ServerProviderModel,\n  ServerProviderSkill,\n} from \"@t3tools/contracts\";\nimport { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from \"@t3tools/contracts\";\n\nimport { createModelCapabilities } from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport { codexAppServerArgs, resolveCodexLaunchArgs } from \"./codexLaunchArgs.ts\";\nimport {\n  AUTH_PROBE_TIMEOUT_MS,\n  buildServerProvider,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport { expandHomePath } from \"../../pathExpansion.ts\";\nimport { resolveCodexUsageLimits } from \"../providerUsageLimits.ts\";\nimport packageJson from \"../../../package.json\" with { type: \"json\" };\nconst isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);\nconst RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000;\n\nconst CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = \"2 seconds\" as const;\n\nconst CODEX_PRESENTATION = {\n  displayName: \"Codex\",\n  showInteractionModeToggle: true,\n} as const;\n\nexport interface CodexAppServerProviderSnapshot {\n  readonly account: CodexSchema.V2GetAccountResponse;\n  readonly rateLimits?: CodexSchema.V2GetAccountRateLimitsResponse__RateLimitSnapshot;\n  readonly version: string | undefined;\n  readonly models: ReadonlyArray<ServerProviderModel>;\n  readonly skills: ReadonlyArray<ServerProviderSkill>;\n}\n\nconst REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {\n  none: \"None\",\n  minimal: \"Minimal\",\n  low: \"Low\",\n  medium: \"Medium\",\n  high: \"High\",\n  xhigh: \"Extra High\",\n  max: \"Max\",\n  ultra: \"Ultra\",\n};\n\nconst DEFAULT_SERVICE_TIER_ID = \"default\";\nconst CURRENT_CODEX_MODELS = new Set([\"gpt-5.6-luna\", \"gpt-5.6-terra\", \"gpt-5.6-sol\"]);\n\nexport function isLegacyCodexModel(model: string): boolean {\n  return !CURRENT_CODEX_MODELS.has(model);\n}\n\nfunction reasoningEffortLabel(reasoningEffort: string): string {\n  return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;\n}\n\nfunction codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse[\"account\"]) {\n  if (!account) return undefined;\n  if (account.type === \"apiKey\") return \"OpenAI API Key\";\n  if (account.type === \"amazonBedrock\") return \"Amazon Bedrock\";\n  if (account.type !== \"chatgpt\") return undefined;\n\n  switch (account.planType) {\n    case \"free\":\n      return \"ChatGPT Free Subscription\";\n    case \"go\":\n      return \"ChatGPT Go Subscription\";\n    case \"plus\":\n      return \"ChatGPT Plus Subscription\";\n    case \"pro\":\n      return \"ChatGPT Pro 20x Subscription\";\n    case \"prolite\":\n      return \"ChatGPT Pro 5x Subscription\";\n    case \"team\":\n      return \"ChatGPT Team Subscription\";\n    case \"self_serve_business_usage_based\":\n    case \"business\":\n      return \"ChatGPT Business Subscription\";\n    case \"enterprise_cbp_usage_based\":\n    case \"enterprise\":\n      return \"ChatGPT Enterprise Subscription\";\n    case \"edu\":\n      return \"ChatGPT Edu Subscription\";\n    case \"unknown\":\n      return \"ChatGPT Subscription\";\n    default:\n      account.planType satisfies never;\n      return undefined;\n  }\n}\n\nfunction codexAccountEmail(account: CodexSchema.V2GetAccountResponse[\"account\"]) {\n  if (!account || account.type !== \"chatgpt\") return undefined;\n  return account.email;\n}\n\nexport function mapCodexModelCapabilities(\n  model: CodexSchema.V2ModelListResponse__Model,\n): ModelCapabilities {\n  const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>\n    reasoningEffort === model.defaultReasoningEffort\n      ? {\n          id: reasoningEffort,\n          label: reasoningEffortLabel(reasoningEffort),\n          isDefault: true,\n        }\n      : {\n          id: reasoningEffort,\n          label: reasoningEffortLabel(reasoningEffort),\n        },\n  );\n  const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;\n  const serviceTiers =\n    model.serviceTiers && model.serviceTiers.length > 0\n      ? model.serviceTiers\n      : (model.additionalSpeedTiers ?? []).map((id) => ({\n          id,\n          name: id === \"fast\" ? \"Fast\" : id,\n          description: \"\",\n        }));\n  const catalogDefaultServiceTier = serviceTiers.some(\n    (tier) => tier.id === model.defaultServiceTier,\n  )\n    ? model.defaultServiceTier\n    : null;\n  const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;\n  const optionDescriptors: ProviderOptionDescriptor[] = [];\n\n  if (reasoningOptions.length > 0) {\n    optionDescriptors.push({\n      id: \"reasoningEffort\",\n      label: \"Reasoning\",\n      type: \"select\",\n      options: reasoningOptions,\n      ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),\n    });\n  }\n  if (serviceTiers.length > 0) {\n    optionDescriptors.push({\n      id: \"serviceTier\",\n      label: \"Service Tier\",\n      type: \"select\",\n      options: [\n        {\n          id: DEFAULT_SERVICE_TIER_ID,\n          label: \"Standard\",\n          ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),\n        },\n        ...serviceTiers.map((tier) => ({\n          id: tier.id,\n          label: tier.name,\n          ...(tier.description ? { description: tier.description } : {}),\n          ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),\n        })),\n      ],\n      currentValue: defaultServiceTier,\n    });\n  }\n\n  return createModelCapabilities({\n    optionDescriptors,\n  });\n}\n\nconst toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => {\n  // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash\n  return model.displayName\n    .replace(/^gpt/i, \"GPT\") // Handle start with 'gpt' or 'GPT'\n    .replace(/-([a-z])/g, (_, c) => \"-\" + c.toUpperCase());\n};\n\nfunction parseCodexModelListResponse(\n  response: CodexSchema.V2ModelListResponse,\n): ReadonlyArray<ServerProviderModel> {\n  return response.data.map((model) => ({\n    slug: model.model,\n    name: toDisplayName(model),\n    isCustom: false,\n    ...(model.isDefault ? { isDefault: true } : {}),\n    ...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}),\n    capabilities: mapCodexModelCapabilities(model),\n  }));\n}\n\n/**\n * Prefer our own default-model ranking when one of the preferred slugs is in\n * the live catalog; otherwise keep whatever Codex itself flagged as default.\n */\nexport function applyPreferredCodexDefaultModel(\n  models: ReadonlyArray<ServerProviderModel>,\n): ReadonlyArray<ServerProviderModel> {\n  const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>\n    models.some((model) => model.slug === slug && !model.isCustom),\n  );\n  if (!preferredSlug) {\n    return models;\n  }\n  return models.map((model) => {\n    if (model.slug === preferredSlug) {\n      return model.isDefault ? model : { ...model, isDefault: true };\n    }\n    if (!model.isDefault) {\n      return model;\n    }\n    const { isDefault: _isDefault, ...rest } = model;\n    return rest;\n  });\n}\n\nfunction appendCustomCodexModels(\n  models: ReadonlyArray<ServerProviderModel>,\n  customModels: ReadonlyArray<string>,\n): ReadonlyArray<ServerProviderModel> {\n  if (customModels.length === 0) {\n    return models;\n  }\n\n  const seen = new Set(models.map((model) => model.slug));\n  const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;\n  const customEntries: ServerProviderModel[] = [];\n  for (const rawModel of customModels) {\n    const slug = rawModel.trim();\n    if (!slug || seen.has(slug)) {\n      continue;\n    }\n    seen.add(slug);\n    customEntries.push({\n      slug,\n      name: slug,\n      isCustom: true,\n      capabilities: fallbackCapabilities,\n    });\n  }\n  return customEntries.length === 0 ? models : [...models, ...customEntries];\n}\n\nfunction parseCodexSkillsListResponse(\n  response: CodexSchema.V2SkillsListResponse,\n  cwd: string,\n): ReadonlyArray<ServerProviderSkill> {\n  const matchingEntry = response.data.find((entry) => entry.cwd === cwd);\n  const skills = matchingEntry\n    ? matchingEntry.skills\n    : response.data.flatMap((entry) => entry.skills);\n\n  return skills.map((skill) => {\n    const shortDescription =\n      skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;\n\n    const parsedSkill: Types.Mutable<ServerProviderSkill> = {\n      name: skill.name,\n      path: skill.path,\n      enabled: skill.enabled,\n    };\n\n    if (skill.description) {\n      parsedSkill.description = skill.description;\n    }\n    if (skill.scope) {\n      parsedSkill.scope = skill.scope;\n    }\n    if (skill.interface?.displayName) {\n      parsedSkill.displayName = skill.interface.displayName;\n    }\n    if (shortDescription) {\n      parsedSkill.shortDescription = shortDescription;\n    }\n\n    return parsedSkill;\n  });\n}\n\nconst requestAllCodexModels = Effect.fn(\"requestAllCodexModels\")(function* (\n  client: CodexClient.CodexAppServerClient[\"Service\"],\n) {\n  const models: ServerProviderModel[] = [];\n  let cursor: string | null | undefined = undefined;\n\n  do {\n    const response: CodexSchema.V2ModelListResponse = yield* client.request(\n      \"model/list\",\n      cursor ? { cursor } : {},\n    );\n    models.push(...parseCodexModelListResponse(response));\n    cursor = response.nextCursor;\n  } while (cursor);\n\n  return models;\n});\n\nexport function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {\n  return {\n    clientInfo: {\n      name: \"t3code_desktop\",\n      title: \"T3 Code Desktop\",\n      version: packageJson.version,\n    },\n    capabilities: {\n      experimentalApi: true,\n    },\n  };\n}\n\nconst probeCodexAppServerProvider = Effect.fn(\"probeCodexAppServerProvider\")(function* (input: {\n  readonly binaryPath: string;\n  readonly homePath?: string;\n  readonly launchArgs?: string;\n  readonly cwd: string;\n  readonly customModels?: ReadonlyArray<string>;\n  readonly environment?: NodeJS.ProcessEnv;\n}) {\n  // `~` is not shell-expanded when env vars are set via `child_process.spawn`,\n  // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip\n  // \"CODEX_HOME points to '~/.codex_work', but that path does not exist\".\n  // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.\n  const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const environment = {\n    ...input.environment,\n    ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),\n  };\n  const spawnCommand = yield* resolveSpawnCommand(\n    input.binaryPath,\n    codexAppServerArgs(input.launchArgs),\n    {\n      env: environment,\n      extendEnv: true,\n    },\n  );\n  const child = yield* spawner\n    .spawn(\n      ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        cwd: input.cwd,\n        env: environment,\n        extendEnv: true,\n        forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,\n        shell: spawnCommand.shell,\n      }),\n    )\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new CodexErrors.CodexAppServerSpawnError({\n            command: `${input.binaryPath} app-server`,\n            cause,\n          }),\n      ),\n    );\n  const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));\n  const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(\n    Effect.provide(clientContext),\n  );\n\n  const initialize = yield* client.request(\"initialize\", {\n    clientInfo: {\n      name: \"t3code_desktop\",\n      title: \"T3 Code Desktop\",\n      version: \"0.1.0\",\n    },\n    capabilities: {\n      experimentalApi: true,\n    },\n  });\n  yield* client.notify(\"initialized\", undefined);\n\n  // Extract the version string after the first '/' in userAgent, up to the next space or the end\n  const versionMatch = initialize.userAgent.match(/\\/([^\\s]+)/);\n  const version = versionMatch ? versionMatch[1] : undefined;\n\n  const accountResponse = yield* client.request(\"account/read\", {});\n  if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {\n    return {\n      account: accountResponse,\n      version,\n      models: appendCustomCodexModels([], input.customModels ?? []),\n      skills: [],\n    } satisfies CodexAppServerProviderSnapshot;\n  }\n\n  const [skillsResponse, models] = yield* Effect.all(\n    [\n      client.request(\"skills/list\", {\n        cwds: [input.cwd],\n      }),\n      requestAllCodexModels(client),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n  const rateLimitsResponse = yield* client.request(\"account/rateLimits/read\", undefined).pipe(\n    Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)),\n    Effect.catchCause((cause) =>\n      Cause.hasInterrupts(cause) ? Effect.failCause(cause) : Effect.succeed(Option.none()),\n    ),\n  );\n  const rateLimits = Option.getOrUndefined(rateLimitsResponse)?.rateLimits;\n\n  return {\n    account: accountResponse,\n    ...(rateLimits ? { rateLimits } : {}),\n    version,\n    models: applyPreferredCodexDefaultModel(\n      appendCustomCodexModels(models, input.customModels ?? []),\n    ),\n    skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),\n  } satisfies CodexAppServerProviderSnapshot;\n});\n\nconst emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider[\"models\"] => {\n  const models = new Set<string>();\n  for (const model of codexSettings.customModels) {\n    const trimmed = model.trim();\n    if (trimmed.length > 0) {\n      models.add(trimmed);\n    }\n  }\n  return Array.from(models, (model) => ({\n    slug: model,\n    name: model,\n    isCustom: true,\n    capabilities: null,\n  }));\n};\n\nconst makePendingCodexProvider = (\n  codexSettings: CodexSettings,\n): Effect.Effect<ServerProviderDraft> =>\n  Effect.gen(function* () {\n    const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);\n    const models = emptyCodexModelsFromSettings(codexSettings);\n\n    if (!codexSettings.enabled) {\n      return buildServerProvider({\n        presentation: CODEX_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        skills: [],\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: \"Codex is disabled in T3 Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      skills: [],\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Codex provider status has not been checked in this session yet.\",\n      },\n    });\n  });\n\nfunction accountProbeStatus(account: CodexAppServerProviderSnapshot[\"account\"]): {\n  readonly status: Exclude<ServerProviderState, \"disabled\">;\n  readonly auth: ServerProvider[\"auth\"];\n  readonly message?: string;\n} {\n  const authLabel = codexAccountAuthLabel(account.account);\n  const authEmail = codexAccountEmail(account.account);\n  const auth = {\n    status: account.account ? (\"authenticated\" as const) : (\"unknown\" as const),\n    ...(account.account?.type ? { type: account.account?.type } : {}),\n    ...(authLabel ? { label: authLabel } : {}),\n    ...(authEmail ? { email: authEmail } : {}),\n  } satisfies ServerProvider[\"auth\"];\n\n  if (account.account) {\n    return { status: \"ready\", auth };\n  }\n\n  if (account.requiresOpenaiAuth) {\n    return {\n      status: \"error\",\n      auth: { status: \"unauthenticated\" },\n      message: \"Codex CLI is not authenticated. Run `codex login` and try again.\",\n    };\n  }\n\n  return { status: \"ready\", auth };\n}\n\nexport const checkCodexProviderStatus = Effect.fn(\"checkCodexProviderStatus\")(function* (\n  codexSettings: CodexSettings,\n  probe: (input: {\n    readonly binaryPath: string;\n    readonly homePath?: string;\n    readonly launchArgs?: string;\n    readonly cwd: string;\n    readonly customModels: ReadonlyArray<string>;\n    readonly environment?: NodeJS.ProcessEnv;\n  }) => Effect.Effect<\n    CodexAppServerProviderSnapshot,\n    CodexErrors.CodexAppServerError,\n    ChildProcessSpawner.ChildProcessSpawner | Scope.Scope\n  > = probeCodexAppServerProvider,\n  environment?: NodeJS.ProcessEnv,\n): Effect.fn.Return<\n  ServerProviderDraft,\n  ServerSettingsError,\n  ChildProcessSpawner.ChildProcessSpawner\n> {\n  const resolvedEnvironment = environment ?? process.env;\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const emptyModels = emptyCodexModelsFromSettings(codexSettings);\n\n  if (!codexSettings.enabled) {\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: emptyModels,\n      skills: [],\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Codex is disabled in T3 Code settings.\",\n      },\n    });\n  }\n\n  const probeResult = yield* probe({\n    binaryPath: codexSettings.binaryPath,\n    homePath: codexSettings.homePath,\n    launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),\n    cwd: process.cwd(),\n    customModels: codexSettings.customModels,\n    environment: resolvedEnvironment,\n  }).pipe(\n    Effect.scoped,\n    Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),\n    Effect.result,\n  );\n\n  if (Result.isFailure(probeResult)) {\n    const error = probeResult.failure;\n    const installed = !isCodexAppServerSpawnError(error);\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: codexSettings.enabled,\n      checkedAt,\n      models: emptyModels,\n      skills: [],\n      probe: {\n        installed,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: installed\n          ? `Codex app-server provider probe failed: ${error.message}.`\n          : \"Codex CLI (`codex`) is not installed or not on PATH.\",\n      },\n    });\n  }\n\n  if (Option.isNone(probeResult.success)) {\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: codexSettings.enabled,\n      checkedAt,\n      models: emptyModels,\n      skills: [],\n      probe: {\n        installed: true,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Timed out while checking Codex app-server provider status.\",\n      },\n    });\n  }\n\n  const snapshot = probeResult.success.value;\n  const accountStatus = accountProbeStatus(snapshot.account);\n  const usageLimits =\n    snapshot.account.account?.type === \"apiKey\"\n      ? {\n          source: \"codexAppServer\" as const,\n          available: false,\n          reason: \"Usage limits unavailable for API key Codex accounts.\",\n          windows: [],\n          checkedAt,\n        }\n      : resolveCodexUsageLimits({\n          checkedAt,\n          ...(snapshot.rateLimits ? { snapshot: snapshot.rateLimits } : {}),\n        });\n\n  return buildServerProvider({\n    presentation: CODEX_PRESENTATION,\n    enabled: codexSettings.enabled,\n    checkedAt,\n    models: snapshot.models,\n    skills: snapshot.skills,\n    probe: {\n      installed: true,\n      version: snapshot.version ?? null,\n      status: accountStatus.status,\n      auth: accountStatus.auth,\n      ...(accountStatus.message ? { message: accountStatus.message } : {}),\n      usageLimits,\n    },\n  });\n});\n\n// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of\n// the per-instance-driver refactor. `CodexDriver.create()` builds a managed\n// snapshot per instance (each with its own `CodexSettings`) and hands the\n// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.\n//\n// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are\n// re-exported for use by `CodexDriver`.\nexport { makePendingCodexProvider };\n","import type { ProviderInteractionMode } from \"@t3tools/contracts\";\n\nconst AGENTLINK_BROWSER_TOOL_INSTRUCTIONS = `\n\n## AgentLink collaborative browser\n\nYou are running inside AgentLink. The \\`t3-code\\` MCP server is the product-native collaborative browser shared with the user. When it exposes \\`preview_*\\` tools, prefer those tools for browser navigation, inspection, interaction, screenshots, and recordings.\n\nFor browser work, first call \\`preview_status\\`. If no automation-capable preview is attached, call \\`preview_open\\` before concluding that the browser is unavailable. Then use \\`preview_navigate\\`, \\`preview_snapshot\\`, and the focused interaction tools. Prefer snapshot-provided locators over coordinates.\n\nDo not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \\`preview_open\\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.\n`;\n\nexport const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)\n\nYou work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.\n\n## Mode rules (strict)\n\nYou are in **Plan Mode** until a developer message explicitly ends it.\n\nPlan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.\n\n## Plan Mode vs update_plan tool\n\nPlan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \\`<proposed_plan>\\` block.\n\nSeparately, \\`update_plan\\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \\`update_plan\\` in Plan mode, it will return an error.\n\n## Execution vs. mutation in Plan Mode\n\nYou may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.\n\n### Allowed (non-mutating, plan-improving)\n\nActions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:\n\n* Reading or searching files, configs, schemas, types, manifests, and docs\n* Static analysis, inspection, and repo exploration\n* Dry-run style commands when they do not edit repo-tracked files\n* Tests, builds, or checks that may write to caches or build artifacts (for example, \\`target/\\`, \\`.cache/\\`, or snapshots) so long as they do not edit repo-tracked files\n\n### Not allowed (mutating, plan-executing)\n\nActions that implement the plan or change repo-tracked state. Examples:\n\n* Editing or writing files\n* Running formatters or linters that rewrite files\n* Applying patches, migrations, or codegen that updates repo-tracked files\n* Side-effectful commands whose purpose is to carry out the plan rather than refine it\n\nWhen in doubt: if the action would reasonably be described as \"doing the work\" rather than \"planning the work,\" do not do it.\n\n## PHASE 1 - Ground in the environment (explore first, ask second)\n\nBegin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.\n\nBefore asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.\n\nException: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.\n\nDo not ask questions that can be answered from the repo or system (for example, \"where is this struct?\" or \"which UI component should we use?\" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.\n\n## PHASE 2 - Intent chat (what they actually want)\n\n* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.\n* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.\n\n## PHASE 3 - Implementation chat (what/how we'll build)\n\n* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.\n\n## Asking questions\n\nCritical rules:\n\n* Strongly prefer using the \\`request_user_input\\` tool to ask any questions.\n* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.\n* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.\n\nYou SHOULD ask many questions, but each question must:\n\n* materially change the spec/plan, OR\n* confirm/lock an assumption, OR\n* choose between meaningful tradeoffs.\n* not be answerable by non-mutating commands.\n\nUse the \\`request_user_input\\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.\n\n## Two kinds of unknowns (treat differently)\n\n1. **Discoverable facts** (repo/system truth): explore first.\n\n   * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).\n   * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.\n   * If asking, present concrete candidates (paths/service names) + recommend one.\n   * Never ask questions you can answer from your environment (e.g., \"where is this struct\").\n\n2. **Preferences/tradeoffs** (not discoverable): ask early.\n\n   * These are intent or implementation preferences that cannot be derived from exploration.\n   * Provide 2-4 mutually exclusive options + a recommended default.\n   * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.\n\n## Finalization rule\n\nOnly output the final plan when it is decision complete and leaves no decisions to the implementer.\n\nWhen you present the official plan, wrap it in a \\`<proposed_plan>\\` block so the client can render it specially:\n\n1) The opening tag must be on its own line.\n2) Start the plan content on the next line (no text on the same line as the tag).\n3) The closing tag must be on its own line.\n4) Use Markdown inside the block.\n5) Keep the tags exactly as \\`<proposed_plan>\\` and \\`</proposed_plan>\\` (do not translate or rename them), even if the plan content is in another language.\n\nExample:\n\n<proposed_plan>\nplan content\n</proposed_plan>\n\nplan content should be human and agent digestible. The final plan must be plan-only and include:\n\n* A clear title\n* A brief summary section\n* Important changes or additions to public APIs/interfaces/types\n* Test cases and scenarios\n* Explicit assumptions and defaults chosen where needed\n\nDo not ask \"should I proceed?\" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \\`<proposed_plan>\\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.\n\nOnly produce at most one \\`<proposed_plan>\\` block per turn, and only when you are presenting a complete spec.\n${AGENTLINK_BROWSER_TOOL_INSTRUCTIONS}\n</collaboration_mode>`;\n\nexport const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default\n\nYou are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.\n\nYour active mode changes only when new developer instructions with a different \\`<collaboration_mode>...</collaboration_mode>\\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.\n\n## request_user_input availability\n\nThe \\`request_user_input\\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.\n\nIn Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.\n${AGENTLINK_BROWSER_TOOL_INSTRUCTIONS}\n</collaboration_mode>`;\n\nexport interface CodexRuntimeInfo {\n  readonly model: string;\n  readonly reasoningEffort: string;\n}\n\n// Values come from trusted config, but keep the block single-line regardless.\nfunction toSingleLine(value: string): string {\n  return value.replaceAll(/\\s+/g, \" \").trim();\n}\n\nexport function buildCodexDeveloperInstructions(\n  interactionMode: ProviderInteractionMode,\n  runtime: CodexRuntimeInfo,\n): string {\n  const base =\n    interactionMode === \"plan\"\n      ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS\n      : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;\n  return `${base}\n\n<runtime_info>In case you're asked: you are running in AgentLink through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.</runtime_info>`;\n}\n","import {\n  ApprovalRequestId,\n  DEFAULT_MODEL,\n  EventId,\n  ProviderDriverKind,\n  ProviderItemId,\n  type ProviderInstanceId,\n  type ProviderApprovalDecision,\n  type ProviderEvent,\n  type ProviderInteractionMode,\n  type ProviderRequestKind,\n  type ProviderSession,\n  type ProviderTurnStartResult,\n  type ProviderUserInputAnswers,\n  RuntimeMode,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport { normalizeModelSlug } from \"@t3tools/shared/model\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport * as CodexClient from \"effect-codex-app-server/client\";\nimport * as CodexErrors from \"effect-codex-app-server/errors\";\nimport * as CodexRpc from \"effect-codex-app-server/rpc\";\nimport * as EffectCodexSchema from \"effect-codex-app-server/schema\";\n\nimport { buildCodexInitializeParams } from \"./CodexProvider.ts\";\nimport { codexSessionAppServerArgs } from \"./codexLaunchArgs.ts\";\nimport { expandHomePath } from \"../../pathExpansion.ts\";\nimport { buildCodexDeveloperInstructions } from \"../CodexDeveloperInstructions.ts\";\nconst decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);\n\nconst PROVIDER = ProviderDriverKind.make(\"codex\");\n\nconst ANSI_ESCAPE_CHAR = String.fromCharCode(27);\nconst ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\\\[[0-9;]*m`, \"g\");\nconst CODEX_STDERR_LOG_REGEX =\n  /^\\d{4}-\\d{2}-\\d{2}T\\S+\\s+(TRACE|DEBUG|INFO|WARN|ERROR)\\s+\\S+:\\s+(.*)$/;\nconst BENIGN_ERROR_LOG_SNIPPETS = [\n  \"state db missing rollout path for thread\",\n  \"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back\",\n];\nconst CODEX_APP_SERVER_FORCE_KILL_AFTER = \"2 seconds\" as const;\nconst RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [\n  \"not found\",\n  \"missing thread\",\n  \"no such thread\",\n  \"unknown thread\",\n  \"does not exist\",\n];\n\nexport function hasConfiguredMcpServer(appServerArgs: ReadonlyArray<string> | undefined): boolean {\n  return appServerArgs?.some((argument) => argument.includes(\"mcp_servers.\")) === true;\n}\n\nexport const CodexResumeCursorSchema = Schema.Struct({\n  threadId: Schema.String,\n});\nconst CodexUserInputAnswerObject = Schema.Struct({\n  answers: Schema.Array(Schema.String),\n});\nconst isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);\nconst isCodexUserInputAnswerObject = Schema.is(CodexUserInputAnswerObject);\n\n// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated\n// `V2TurnStartParams` schema includes `collaborationMode` directly.\nconst CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe(\n  Schema.fieldsAssign({\n    collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),\n  }),\n);\nconst decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect(\n  CodexTurnStartParamsWithCollaborationMode,\n);\n\nexport type CodexTurnStartParamsWithCollaborationMode =\n  typeof CodexTurnStartParamsWithCollaborationMode.Type;\n\nexport type CodexResumeCursor = typeof CodexResumeCursorSchema.Type;\ntype CodexServiceTier = NonNullable<EffectCodexSchema.V2ThreadStartParams[\"serviceTier\"]>;\ntype CodexThreadItem =\n  | EffectCodexSchema.V2ThreadReadResponse[\"thread\"][\"turns\"][number][\"items\"][number]\n  | EffectCodexSchema.V2ThreadRollbackResponse[\"thread\"][\"turns\"][number][\"items\"][number];\n\nexport interface CodexSessionRuntimeOptions {\n  readonly threadId: ThreadId;\n  readonly providerInstanceId?: ProviderInstanceId;\n  readonly binaryPath: string;\n  readonly homePath?: string;\n  readonly launchArgs?: string;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly cwd: string;\n  readonly runtimeMode: RuntimeMode;\n  readonly model?: string;\n  readonly serviceTier?: CodexServiceTier | undefined;\n  readonly resumeCursor?: CodexResumeCursor;\n  readonly appServerArgs?: ReadonlyArray<string>;\n}\n\nexport interface CodexSessionRuntimeSendTurnInput {\n  readonly input?: string;\n  readonly attachments?: ReadonlyArray<{\n    readonly type: \"image\";\n    readonly url: string;\n  }>;\n  readonly model?: string;\n  readonly serviceTier?: CodexServiceTier | undefined;\n  readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;\n  readonly interactionMode?: ProviderInteractionMode;\n}\n\nexport interface CodexThreadTurnSnapshot {\n  readonly id: TurnId;\n  readonly status: EffectCodexSchema.V2ThreadReadResponse__TurnStatus;\n  readonly startedAt?: number;\n  readonly completedAt?: number;\n  readonly items: ReadonlyArray<CodexThreadItem>;\n}\n\nexport interface CodexThreadSnapshot {\n  readonly threadId: string;\n  readonly createdAt: number;\n  readonly updatedAt: number;\n  readonly status: EffectCodexSchema.V2ThreadReadResponse__ThreadStatus;\n  readonly turns: ReadonlyArray<CodexThreadTurnSnapshot>;\n}\n\nexport interface CodexSessionRuntimeShape {\n  readonly start: () => Effect.Effect<ProviderSession, CodexSessionRuntimeError>;\n  readonly getSession: Effect.Effect<ProviderSession>;\n  readonly sendTurn: (\n    input: CodexSessionRuntimeSendTurnInput,\n  ) => Effect.Effect<ProviderTurnStartResult, CodexSessionRuntimeError>;\n  readonly interruptTurn: (turnId?: TurnId) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly startRealtimeVoiceInput: () => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly appendRealtimeVoiceAudio: (audio: {\n    readonly data: string;\n    readonly sampleRate: number;\n    readonly numChannels: number;\n    readonly samplesPerChannel?: number;\n  }) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly stopRealtimeVoiceInput: () => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly readThread: Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;\n  readonly rollbackThread: (\n    numTurns: number,\n  ) => Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;\n  readonly respondToRequest: (\n    requestId: ApprovalRequestId,\n    decision: ProviderApprovalDecision,\n  ) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly respondToUserInput: (\n    requestId: ApprovalRequestId,\n    answers: ProviderUserInputAnswers,\n  ) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly events: Stream.Stream<ProviderEvent, never>;\n  readonly close: Effect.Effect<void>;\n}\n\nexport type CodexSessionRuntimeError =\n  | CodexErrors.CodexAppServerError\n  | CodexSessionRuntimePendingApprovalNotFoundError\n  | CodexSessionRuntimePendingUserInputNotFoundError\n  | CodexSessionRuntimeInvalidUserInputAnswersError\n  | CodexSessionRuntimeThreadIdMissingError;\n\nexport class CodexSessionRuntimePendingApprovalNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingApprovalNotFoundError>()(\n  \"CodexSessionRuntimePendingApprovalNotFoundError\",\n  {\n    requestId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Unknown pending Codex approval request: ${this.requestId}`;\n  }\n}\n\nexport class CodexSessionRuntimePendingUserInputNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingUserInputNotFoundError>()(\n  \"CodexSessionRuntimePendingUserInputNotFoundError\",\n  {\n    requestId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Unknown pending Codex user input request: ${this.requestId}`;\n  }\n}\n\nexport class CodexSessionRuntimeInvalidUserInputAnswersError extends Schema.TaggedErrorClass<CodexSessionRuntimeInvalidUserInputAnswersError>()(\n  \"CodexSessionRuntimeInvalidUserInputAnswersError\",\n  {\n    questionId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Invalid Codex user input answers for question '${this.questionId}'`;\n  }\n}\n\nexport class CodexSessionRuntimeThreadIdMissingError extends Schema.TaggedErrorClass<CodexSessionRuntimeThreadIdMissingError>()(\n  \"CodexSessionRuntimeThreadIdMissingError\",\n  {\n    threadId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Codex session is missing a provider thread id for ${this.threadId}`;\n  }\n}\n\ninterface PendingApproval {\n  readonly requestId: ApprovalRequestId;\n  readonly jsonRpcId: string;\n  readonly requestKind: ProviderRequestKind;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n}\n\ninterface ApprovalCorrelation {\n  readonly requestId: ApprovalRequestId;\n  readonly requestKind: ProviderRequestKind;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n}\n\ninterface PendingUserInput {\n  readonly requestId: ApprovalRequestId;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n  readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;\n}\n\ntype CodexServerNotification = {\n  readonly [M in CodexRpc.ServerNotificationMethod]: {\n    readonly method: M;\n    readonly params: CodexRpc.ServerNotificationParamsByMethod[M];\n  };\n}[CodexRpc.ServerNotificationMethod];\n\nfunction makeCodexServerNotification<M extends CodexRpc.ServerNotificationMethod>(\n  method: M,\n  params: CodexRpc.ServerNotificationParamsByMethod[M],\n): CodexServerNotification {\n  return { method, params } as CodexServerNotification;\n}\n\nfunction normalizeCodexModelSlug(\n  model: string | undefined | null,\n  preferredId?: string,\n): string | undefined {\n  const normalized = normalizeModelSlug(model);\n  if (!normalized) {\n    return undefined;\n  }\n  if (preferredId?.endsWith(\"-codex\") && preferredId !== normalized) {\n    return preferredId;\n  }\n  return normalized;\n}\n\nfunction readResumeCursorThreadId(\n  resumeCursor: ProviderSession[\"resumeCursor\"],\n): string | undefined {\n  return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.threadId : undefined;\n}\n\nfunction runtimeModeToThreadConfig(input: RuntimeMode): {\n  readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval;\n  readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode;\n  // Always explicit: omitting the field on resume keeps the thread's previous\n  // reviewer, which would leave auto_review sticky after switching modes.\n  readonly approvalsReviewer: EffectCodexSchema.V2ThreadStartParams__ApprovalsReviewer;\n} {\n  switch (input) {\n    case \"approval-required\":\n      return {\n        approvalPolicy: \"untrusted\",\n        sandbox: \"read-only\",\n        approvalsReviewer: \"user\",\n      };\n    case \"auto-accept-edits\":\n      return {\n        approvalPolicy: \"on-request\",\n        sandbox: \"workspace-write\",\n        approvalsReviewer: \"user\",\n      };\n    case \"auto\":\n      return {\n        approvalPolicy: \"on-request\",\n        sandbox: \"workspace-write\",\n        approvalsReviewer: \"auto_review\",\n      };\n    case \"full-access\":\n    default:\n      return {\n        approvalPolicy: \"never\",\n        sandbox: \"danger-full-access\",\n        approvalsReviewer: \"user\",\n      };\n  }\n}\n\nfunction buildThreadStartParams(input: {\n  readonly cwd: string;\n  readonly runtimeMode: RuntimeMode;\n  readonly model: string | undefined;\n  readonly serviceTier: CodexServiceTier | undefined;\n}): EffectCodexSchema.V2ThreadStartParams {\n  const config = runtimeModeToThreadConfig(input.runtimeMode);\n  return {\n    cwd: input.cwd,\n    approvalPolicy: config.approvalPolicy,\n    sandbox: config.sandbox,\n    approvalsReviewer: config.approvalsReviewer,\n    ...(input.model ? { model: input.model } : {}),\n    ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),\n  };\n}\n\nfunction runtimeModeToTurnSandboxPolicy(\n  input: RuntimeMode,\n): EffectCodexSchema.V2TurnStartParams__SandboxPolicy {\n  switch (input) {\n    case \"approval-required\":\n      return {\n        type: \"readOnly\",\n      };\n    case \"auto-accept-edits\":\n    case \"auto\":\n      return {\n        type: \"workspaceWrite\",\n      };\n    case \"full-access\":\n    default:\n      return {\n        type: \"dangerFullAccess\",\n      };\n  }\n}\n\nfunction buildCodexCollaborationMode(input: {\n  readonly interactionMode?: ProviderInteractionMode;\n  readonly model?: string;\n  readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;\n}): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined {\n  if (input.interactionMode === undefined) {\n    return undefined;\n  }\n  const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;\n  const reasoningEffort = input.effort ?? \"medium\";\n  return {\n    mode: input.interactionMode,\n    settings: {\n      model,\n      reasoning_effort: reasoningEffort,\n      developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, {\n        model,\n        reasoningEffort,\n      }),\n    },\n  };\n}\n\nexport function buildTurnStartParams(input: {\n  readonly threadId: string;\n  readonly runtimeMode: RuntimeMode;\n  readonly prompt?: string;\n  readonly attachments?: ReadonlyArray<{\n    readonly type: \"image\";\n    readonly url: string;\n  }>;\n  readonly model?: string;\n  readonly serviceTier?: CodexServiceTier;\n  readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;\n  readonly interactionMode?: ProviderInteractionMode;\n}): Effect.Effect<\n  CodexTurnStartParamsWithCollaborationMode,\n  CodexErrors.CodexAppServerProtocolParseError\n> {\n  const turnInput: Array<EffectCodexSchema.V2TurnStartParams__UserInput> = [];\n  if (input.prompt) {\n    turnInput.push({\n      type: \"text\",\n      text: input.prompt,\n    });\n  }\n  for (const attachment of input.attachments ?? []) {\n    turnInput.push(attachment);\n  }\n\n  const config = runtimeModeToThreadConfig(input.runtimeMode);\n  const collaborationMode = buildCodexCollaborationMode({\n    ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),\n    ...(input.model ? { model: input.model } : {}),\n    ...(input.effort ? { effort: input.effort } : {}),\n  });\n\n  return decodeCodexTurnStartParamsWithCollaborationMode({\n    threadId: input.threadId,\n    input: turnInput,\n    approvalPolicy: config.approvalPolicy,\n    approvalsReviewer: config.approvalsReviewer,\n    sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode),\n    ...(input.model ? { model: input.model } : {}),\n    ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),\n    ...(input.effort ? { effort: input.effort } : {}),\n    ...(collaborationMode ? { collaborationMode } : {}),\n  }).pipe(\n    Effect.mapError((cause) =>\n      CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(\n        \"decode-request-payload\",\n        cause,\n        { method: \"turn/start\" },\n      ),\n    ),\n  );\n}\n\nfunction classifyCodexStderrLine(rawLine: string): { readonly message: string } | null {\n  const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, \"\").trim();\n  if (!line) {\n    return null;\n  }\n\n  const match = line.match(CODEX_STDERR_LOG_REGEX);\n  if (match) {\n    const level = match[1];\n    if (level && level !== \"ERROR\") {\n      return null;\n    }\n    if (BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet))) {\n      return null;\n    }\n  }\n\n  return { message: line };\n}\n\nexport function isRecoverableThreadResumeError(error: unknown): boolean {\n  const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n  if (!message.includes(\"thread\")) {\n    return false;\n  }\n  return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));\n}\n\ntype CodexThreadOpenResponse =\n  | CodexRpc.ClientRequestResponsesByMethod[\"thread/start\"]\n  | CodexRpc.ClientRequestResponsesByMethod[\"thread/resume\"];\n\ntype CodexThreadOpenMethod = \"thread/start\" | \"thread/resume\";\n\ninterface CodexThreadOpenClient {\n  readonly request: <M extends CodexThreadOpenMethod>(\n    method: M,\n    payload: CodexRpc.ClientRequestParamsByMethod[M],\n  ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexErrors.CodexAppServerError>;\n}\n\nexport const openCodexThread = (input: {\n  readonly client: CodexThreadOpenClient;\n  readonly threadId: ThreadId;\n  readonly runtimeMode: RuntimeMode;\n  readonly cwd: string;\n  readonly requestedModel: string | undefined;\n  readonly serviceTier: CodexServiceTier | undefined;\n  readonly resumeThreadId: string | undefined;\n}): Effect.Effect<CodexThreadOpenResponse, CodexErrors.CodexAppServerError> => {\n  const resumeThreadId = input.resumeThreadId;\n  const startParams = buildThreadStartParams({\n    cwd: input.cwd,\n    runtimeMode: input.runtimeMode,\n    model: input.requestedModel,\n    serviceTier: input.serviceTier,\n  });\n\n  if (resumeThreadId === undefined) {\n    return input.client.request(\"thread/start\", startParams);\n  }\n\n  return input.client\n    .request(\"thread/resume\", {\n      threadId: resumeThreadId,\n      ...startParams,\n    })\n    .pipe(\n      Effect.catchIf(isRecoverableThreadResumeError, (error) =>\n        Effect.logWarning(\"codex app-server thread resume fell back to fresh start\", {\n          threadId: input.threadId,\n          requestedRuntimeMode: input.runtimeMode,\n          resumeThreadId,\n          recoverable: true,\n          cause: error,\n        }).pipe(Effect.andThen(input.client.request(\"thread/start\", startParams))),\n      ),\n    );\n};\n\nfunction readNotificationThreadId(notification: CodexServerNotification): string | undefined {\n  switch (notification.method) {\n    case \"thread/started\":\n      return notification.params.thread.id;\n    case \"error\":\n    case \"thread/status/changed\":\n    case \"thread/archived\":\n    case \"thread/unarchived\":\n    case \"thread/closed\":\n    case \"thread/name/updated\":\n    case \"thread/tokenUsage/updated\":\n    case \"turn/started\":\n    case \"hook/started\":\n    case \"turn/completed\":\n    case \"hook/completed\":\n    case \"turn/diff/updated\":\n    case \"turn/plan/updated\":\n    case \"item/started\":\n    case \"item/autoApprovalReview/started\":\n    case \"item/autoApprovalReview/completed\":\n    case \"item/completed\":\n    case \"rawResponseItem/completed\":\n    case \"item/agentMessage/delta\":\n    case \"item/plan/delta\":\n    case \"item/commandExecution/outputDelta\":\n    case \"item/commandExecution/terminalInteraction\":\n    case \"item/fileChange/outputDelta\":\n    case \"item/fileChange/patchUpdated\":\n    case \"serverRequest/resolved\":\n    case \"item/mcpToolCall/progress\":\n    case \"item/reasoning/summaryTextDelta\":\n    case \"item/reasoning/summaryPartAdded\":\n    case \"item/reasoning/textDelta\":\n    case \"thread/compacted\":\n    case \"thread/realtime/started\":\n    case \"thread/realtime/itemAdded\":\n    case \"thread/realtime/transcript/delta\":\n    case \"thread/realtime/transcript/done\":\n    case \"thread/realtime/outputAudio/delta\":\n    case \"thread/realtime/sdp\":\n    case \"thread/realtime/error\":\n    case \"thread/realtime/closed\":\n      return notification.params.threadId;\n    default:\n      return undefined;\n  }\n}\n\nfunction readRouteFields(notification: CodexServerNotification): {\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n} {\n  switch (notification.method) {\n    case \"thread/started\":\n      return {\n        turnId: undefined,\n        itemId: undefined,\n      };\n    case \"turn/started\":\n    case \"turn/completed\":\n      return {\n        turnId: TurnId.make(notification.params.turn.id),\n        itemId: undefined,\n      };\n    case \"error\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: undefined,\n      };\n    case \"turn/diff/updated\":\n    case \"turn/plan/updated\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: undefined,\n      };\n    case \"serverRequest/resolved\":\n      return {\n        turnId: undefined,\n        itemId: undefined,\n      };\n    case \"item/started\":\n    case \"item/completed\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: ProviderItemId.make(notification.params.item.id),\n      };\n    case \"item/agentMessage/delta\":\n    case \"item/plan/delta\":\n    case \"item/commandExecution/outputDelta\":\n    case \"item/commandExecution/terminalInteraction\":\n    case \"item/fileChange/outputDelta\":\n    case \"item/fileChange/patchUpdated\":\n    case \"item/reasoning/summaryTextDelta\":\n    case \"item/reasoning/summaryPartAdded\":\n    case \"item/reasoning/textDelta\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: ProviderItemId.make(notification.params.itemId),\n      };\n    default:\n      return {\n        turnId: undefined,\n        itemId: undefined,\n      };\n  }\n}\n\n/**\n * Native collab child-agent tracking (multi-agent v2). Under v2 subagents are\n * full app-server threads: identity arrives on `thread/started` with\n * source.subAgent.thread_spawn, lifecycle on `subAgentActivity` items and the\n * child thread's own turn/status/tokenUsage notifications. The runtime\n * registers children from those explicit signals, intercepts their\n * notifications before parent-timeline mapping, and re-emits them as\n * synthetic `collabAgent/*` provider events the adapter turns into task.*\n * runtime events (timelineBypass keeps them out of the parent chat).\n *\n * WIP, probe-gated: registration is deliberately explicit-signals-only. The\n * spec's \"provisionally treat unknown foreign thread ids as v2 children\" rule\n * needs a live wire capture of the packaged binary before it lands — blind\n * capture risks eating unrelated traffic. Until then a child whose first\n * notification precedes registration passes through as today (no regression\n * vs main, which passes everything through).\n */\ninterface CollabChildAgentState {\n  readonly agentThreadId: string;\n  readonly nickname: string | undefined;\n  readonly role: string | undefined;\n  readonly agentPath: string | undefined;\n  readonly depth: number | undefined;\n  readonly parentThreadId: string | undefined;\n  /**\n   * Parent canonical turn active when the child registered. Stamped on every\n   * synthetic collabAgent/* event so clients can batch a fleet by its spawn\n   * turn — without it, separate fleets in one thread collapsed into a single\n   * \"direct:no-turn\" CTA (review finding).\n   */\n  readonly spawnTurnId: TurnId | undefined;\n}\n\nfunction readThreadSpawnSource(thread: { readonly source: unknown }):\n  | {\n      nickname: string | undefined;\n      role: string | undefined;\n      agentPath: string | undefined;\n      depth: number | undefined;\n      parentThreadId: string | undefined;\n    }\n  | undefined {\n  const source = thread.source;\n  if (typeof source !== \"object\" || source === null || !(\"subAgent\" in source)) {\n    return undefined;\n  }\n  const subAgent = (source as { subAgent: unknown }).subAgent;\n  if (typeof subAgent !== \"object\" || subAgent === null || !(\"thread_spawn\" in subAgent)) {\n    return undefined;\n  }\n  const spawn = (subAgent as { thread_spawn: unknown }).thread_spawn;\n  if (typeof spawn !== \"object\" || spawn === null) {\n    return undefined;\n  }\n  const record = spawn as Record<string, unknown>;\n  return {\n    nickname: typeof record.agent_nickname === \"string\" ? record.agent_nickname : undefined,\n    role: typeof record.agent_role === \"string\" ? record.agent_role : undefined,\n    agentPath: typeof record.agent_path === \"string\" ? record.agent_path : undefined,\n    depth: typeof record.depth === \"number\" ? record.depth : undefined,\n    parentThreadId:\n      typeof record.parent_thread_id === \"string\" ? record.parent_thread_id : undefined,\n  };\n}\n\nfunction rememberCollabReceiverTurns(\n  collabReceiverTurns: Map<string, TurnId>,\n  notification: CodexServerNotification,\n  parentTurnId: TurnId | undefined,\n): void {\n  if (!parentTurnId) {\n    return;\n  }\n\n  if (notification.method !== \"item/started\" && notification.method !== \"item/completed\") {\n    return;\n  }\n\n  if (notification.params.item.type !== \"collabAgentToolCall\") {\n    return;\n  }\n\n  for (const receiverThreadId of notification.params.item.receiverThreadIds) {\n    collabReceiverTurns.set(receiverThreadId, parentTurnId);\n  }\n}\n\nfunction shouldSuppressChildConversationNotification(\n  method: CodexRpc.ServerNotificationMethod,\n): boolean {\n  return (\n    method === \"thread/started\" ||\n    method === \"thread/status/changed\" ||\n    method === \"thread/archived\" ||\n    method === \"thread/unarchived\" ||\n    method === \"thread/closed\" ||\n    method === \"thread/compacted\" ||\n    method === \"thread/name/updated\" ||\n    method === \"thread/tokenUsage/updated\" ||\n    method === \"turn/started\" ||\n    method === \"turn/completed\" ||\n    method === \"turn/plan/updated\" ||\n    method === \"item/plan/delta\"\n  );\n}\n\n/**\n * How a notification addressed to a REGISTERED child thread is handled.\n *\n * Exported and pure so the routing table can be asserted against captured\n * wire traces (see codexMultiAgentWire.json) rather than only read.\n *\n * - \"agent-event\": map to a synthetic collabAgent/* event (Agents surface).\n * - \"parent\": pass through to the parent path — it carries state the parent\n *   still owns (approval correlation cleanup).\n * - \"drop\": genuine child chatter with no parent meaning (deltas, name and\n *   plan updates).\n *\n * Default is \"drop\" ONLY for the enumerated chatter; anything unrecognized\n * routes to \"parent\" so new wire methods surface instead of vanishing\n * (two shipped bugs came from a catch-all that swallowed everything).\n */\nexport type CodexChildNotificationRoute = \"agent-event\" | \"parent\" | \"drop\";\n\nconst CHILD_AGENT_EVENT_METHODS: ReadonlySet<string> = new Set([\n  \"turn/started\",\n  \"turn/completed\",\n  \"thread/status/changed\",\n  \"thread/tokenUsage/updated\",\n  \"item/started\",\n  \"item/completed\",\n  \"thread/closed\",\n  \"error\",\n]);\n\nconst CHILD_CHATTER_METHODS: ReadonlySet<string> = new Set([\n  \"item/agentMessage/delta\",\n  \"item/reasoning/textDelta\",\n  \"item/reasoning/summaryTextDelta\",\n  \"item/reasoning/summaryPartAdded\",\n  \"item/commandExecution/outputDelta\",\n  \"item/fileChange/outputDelta\",\n  \"item/fileChange/patchUpdated\",\n  \"item/plan/delta\",\n  \"turn/plan/updated\",\n  \"turn/diff/updated\",\n  \"thread/name/updated\",\n  \"thread/settings/updated\",\n  \"rawResponseItem/completed\",\n  // Child-owned thread lifecycle: the parent adapter maps these onto the\n  // PARENT thread (archived/compacted state), so a child compacting would\n  // rewrite the parent. Mirrors the v1 suppressor list — dropping them is\n  // the pre-existing behavior for collab children (review finding).\n  \"thread/archived\",\n  \"thread/unarchived\",\n  \"thread/compacted\",\n  // Registration path 1 handles a child's first thread/started; a repeat\n  // must not reach the parent (it would restart the parent's thread state).\n  \"thread/started\",\n]);\n\nexport function routeCodexChildNotification(method: string): CodexChildNotificationRoute {\n  if (CHILD_AGENT_EVENT_METHODS.has(method)) {\n    return \"agent-event\";\n  }\n  if (CHILD_CHATTER_METHODS.has(method)) {\n    return \"drop\";\n  }\n  // Unknown or parent-owned (serverRequest/resolved, approvals, …).\n  return \"parent\";\n}\n\nfunction toCodexUserInputAnswer(\n  questionId: string,\n  value: ProviderUserInputAnswers[string],\n): Effect.Effect<\n  EffectCodexSchema.ToolRequestUserInputResponse__ToolRequestUserInputAnswer,\n  CodexSessionRuntimeInvalidUserInputAnswersError\n> {\n  if (typeof value === \"string\") {\n    return Effect.succeed({ answers: [value] });\n  }\n  if (Array.isArray(value)) {\n    const answers = value.filter((entry): entry is string => typeof entry === \"string\");\n    return Effect.succeed({ answers });\n  }\n  if (isCodexUserInputAnswerObject(value)) {\n    return Effect.succeed({ answers: value.answers });\n  }\n  return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId }));\n}\n\nfunction toCodexUserInputAnswers(\n  answers: ProviderUserInputAnswers,\n): Effect.Effect<\n  EffectCodexSchema.ToolRequestUserInputResponse[\"answers\"],\n  CodexSessionRuntimeInvalidUserInputAnswersError\n> {\n  return Effect.forEach(\n    Object.entries(answers),\n    ([questionId, value]) =>\n      toCodexUserInputAnswer(questionId, value).pipe(\n        Effect.map((answer) => [questionId, answer] as const),\n      ),\n    { concurrency: 1 },\n  ).pipe(Effect.map((entries) => Object.fromEntries(entries)));\n}\n\nfunction currentProviderThreadId(session: ProviderSession): string | undefined {\n  return readResumeCursorThreadId(session.resumeCursor);\n}\n\nfunction updateSession(\n  sessionRef: Ref.Ref<ProviderSession>,\n  updates: Partial<ProviderSession>,\n): Effect.Effect<void> {\n  return Effect.gen(function* () {\n    const updatedAt = DateTime.formatIso(yield* DateTime.now);\n    yield* Ref.update(sessionRef, (session) => ({\n      ...session,\n      ...updates,\n      updatedAt,\n    }));\n  });\n}\n\nfunction parseThreadSnapshot(\n  response: EffectCodexSchema.V2ThreadReadResponse | EffectCodexSchema.V2ThreadRollbackResponse,\n): CodexThreadSnapshot {\n  return {\n    threadId: response.thread.id,\n    createdAt: response.thread.createdAt,\n    updatedAt: response.thread.updatedAt,\n    status: response.thread.status,\n    turns: response.thread.turns.map((turn) => ({\n      id: TurnId.make(turn.id),\n      status: turn.status,\n      ...(turn.startedAt !== undefined && turn.startedAt !== null\n        ? { startedAt: turn.startedAt }\n        : {}),\n      ...(turn.completedAt !== undefined && turn.completedAt !== null\n        ? { completedAt: turn.completedAt }\n        : {}),\n      items: turn.items,\n    })),\n  };\n}\n\nexport const makeCodexSessionRuntime = (\n  options: CodexSessionRuntimeOptions,\n): Effect.Effect<\n  CodexSessionRuntimeShape,\n  CodexErrors.CodexAppServerError,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const runtimeScope = yield* Scope.Scope;\n    const crypto = yield* Crypto.Crypto;\n    const events = yield* Queue.unbounded<ProviderEvent>();\n    const pendingApprovalsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingApproval>());\n    const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());\n    const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());\n    const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());\n    const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());\n    /** Child provider-thread id → its currently running provider turn id. */\n    const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());\n    const closedRef = yield* Ref.make(false);\n\n    // `~` is not shell-expanded when env vars are set via\n    // `child_process.spawn`; `expandHomePath` lets a configured\n    // `CODEX_HOME=~/.codex_work` reach codex as an absolute path.\n    const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;\n    const env = {\n      ...options.environment,\n      ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),\n    };\n    const extendEnv = options.environment === undefined;\n    const appServerArgs = codexSessionAppServerArgs(options.appServerArgs, options.launchArgs);\n    const spawnCommand = yield* resolveSpawnCommand(options.binaryPath, appServerArgs, {\n      env,\n      extendEnv,\n    });\n    const child = yield* spawner\n      .spawn(\n        ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n          cwd: options.cwd,\n          env,\n          extendEnv,\n          forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,\n          shell: spawnCommand.shell,\n        }),\n      )\n      .pipe(\n        Effect.provideService(Scope.Scope, runtimeScope),\n        Effect.mapError(\n          (cause) =>\n            new CodexErrors.CodexAppServerSpawnError({\n              command: `${options.binaryPath} app-server`,\n              cause,\n            }),\n        ),\n      );\n\n    const clientContext = yield* CodexClient.layerChildProcess(child).pipe(\n      Layer.build,\n      Effect.provideService(Scope.Scope, runtimeScope),\n    );\n    const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(\n      Effect.provide(clientContext),\n    );\n    const initializeClient = yield* Effect.cached(\n      Effect.gen(function* () {\n        yield* client.request(\"initialize\", buildCodexInitializeParams());\n        yield* client.notify(\"initialized\", undefined);\n      }),\n    );\n    const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();\n    const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n    const randomUUIDv4 = (purpose: CodexErrors.CodexAppServerIdentifierPurpose) =>\n      crypto.randomUUIDv4.pipe(\n        Effect.mapError(\n          (cause) =>\n            new CodexErrors.CodexAppServerIdentifierGenerationError({\n              purpose,\n              cause,\n            }),\n        ),\n      );\n\n    const sessionCreatedAt = yield* nowIso;\n    const initialSession = {\n      provider: PROVIDER,\n      ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),\n      status: \"connecting\",\n      runtimeMode: options.runtimeMode,\n      cwd: options.cwd,\n      ...(options.model ? { model: options.model } : {}),\n      threadId: options.threadId,\n      ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}),\n      createdAt: sessionCreatedAt,\n      updatedAt: sessionCreatedAt,\n    } satisfies ProviderSession;\n    const sessionRef = yield* Ref.make<ProviderSession>(initialSession);\n    const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);\n\n    const emitEvent = (event: Omit<ProviderEvent, \"id\" | \"provider\" | \"createdAt\">) =>\n      Effect.gen(function* () {\n        const id = yield* randomUUIDv4(\"provider-event\");\n        return yield* offerEvent({\n          id: EventId.make(id),\n          provider: PROVIDER,\n          ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),\n          createdAt: yield* nowIso,\n          ...event,\n        });\n      });\n    const emitSessionEvent = (method: string, message: string) =>\n      emitEvent({\n        kind: \"session\",\n        threadId: options.threadId,\n        method,\n        message,\n      });\n\n    const settlePendingApprovals = (decision: ProviderApprovalDecision) =>\n      Ref.get(pendingApprovalsRef).pipe(\n        Effect.flatMap((pendingApprovals) =>\n          Effect.forEach(\n            Array.from(pendingApprovals.values()),\n            (pendingApproval) =>\n              Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore),\n            { discard: true },\n          ),\n        ),\n      );\n\n    const settlePendingUserInputs = (answers: ProviderUserInputAnswers) =>\n      Ref.get(pendingUserInputsRef).pipe(\n        Effect.flatMap((pendingUserInputs) =>\n          Effect.forEach(\n            Array.from(pendingUserInputs.values()),\n            (pendingUserInput) =>\n              Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore),\n            { discard: true },\n          ),\n        ),\n      );\n\n    /**\n     * Registers v2 collab children and re-emits their notifications as\n     * synthetic `collabAgent/*` events for the adapter's task.* synthesis.\n     * Returns true when the notification was fully handled (must not reach\n     * parent-timeline mapping).\n     */\n    const interceptCollabChildNotification = (notification: CodexServerNotification) =>\n      Effect.gen(function* () {\n        // Registration path 1: child thread announces itself with a\n        // subAgent thread_spawn source.\n        if (notification.method === \"thread/started\") {\n          const thread = notification.params.thread;\n          const spawn = readThreadSpawnSource(thread);\n          if (!spawn) {\n            return false;\n          }\n          // Merge with any subAgentActivity registration that got here\n          // first. spawnTurnId is REGISTRATION-time-only on both paths: for\n          // an already-known child we keep its value (set or unset) — a\n          // later thread/started during an unrelated parent turn must not\n          // backfill that turn as the spawn batch, which would stamp an old\n          // child onto a new fleet's CTA (review finding). Only a genuinely\n          // new registration captures the current turn.\n          const existingChild = (yield* Ref.get(collabChildAgentsRef)).get(thread.id);\n          const spawnTurnId = existingChild\n            ? existingChild.spawnTurnId\n            : ((yield* Ref.get(sessionRef)).activeTurnId ?? undefined);\n          const state: CollabChildAgentState = {\n            agentThreadId: thread.id,\n            nickname: spawn.nickname ?? thread.agentNickname ?? existingChild?.nickname,\n            role: spawn.role ?? thread.agentRole ?? existingChild?.role,\n            agentPath: spawn.agentPath ?? existingChild?.agentPath,\n            depth: spawn.depth ?? existingChild?.depth,\n            parentThreadId:\n              spawn.parentThreadId ?? thread.parentThreadId ?? existingChild?.parentThreadId,\n            spawnTurnId,\n          };\n          yield* Ref.update(collabChildAgentsRef, (current) => {\n            const next = new Map(current);\n            next.set(thread.id, state);\n            return next;\n          });\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"collabAgent/started\",\n            ...(state.spawnTurnId ? { turnId: state.spawnTurnId } : {}),\n            payload: {\n              agentThreadId: state.agentThreadId,\n              ...(state.nickname ? { nickname: state.nickname } : {}),\n              ...(state.role ? { role: state.role } : {}),\n              ...(state.agentPath ? { agentPath: state.agentPath } : {}),\n              ...(state.depth !== undefined ? { depth: state.depth } : {}),\n              ...(state.parentThreadId ? { parentThreadId: state.parentThreadId } : {}),\n            },\n          });\n          return true;\n        }\n\n        // Registration path 2: parent-side subAgentActivity item names the\n        // child thread (may arrive before or after thread/started).\n        if (\n          (notification.method === \"item/started\" || notification.method === \"item/completed\") &&\n          notification.params.item.type === \"subAgentActivity\"\n        ) {\n          const item = notification.params.item;\n          // Never register the session's ROOT thread as its own child. The\n          // wire emits subAgentActivity {agentPath: \"/root\", interacted}\n          // about the root during collab runs; registering it intercepted\n          // every subsequent root notification — including the final\n          // assistant message and turn/completed — so the thread hung\n          // \"working\" after all subagents finished (live-probe finding).\n          const rootProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));\n          if (\n            item.agentThreadId === rootProviderThreadId ||\n            item.agentPath === \"/root\" ||\n            item.agentPath === \"/\"\n          ) {\n            return false;\n          }\n          const activitySpawnTurnId = (yield* Ref.get(sessionRef)).activeTurnId ?? undefined;\n          yield* Ref.update(collabChildAgentsRef, (current) => {\n            const existing = current.get(item.agentThreadId);\n            const next = new Map(current);\n            // Merge-late semantics: when thread/started registered first, a\n            // later subAgentActivity still carries the real agentPath (and a\n            // derived nickname) — fill missing fields, never clobber known\n            // ones. spawnTurnId is registration-time-only: for an already\n            // registered child, a later activity during an UNRELATED turn\n            // must not backfill that turn as the spawn batch (review\n            // finding); an unset spawn turn stays unset.\n            next.set(item.agentThreadId, {\n              agentThreadId: item.agentThreadId,\n              nickname:\n                existing?.nickname ??\n                item.agentPath.split(\"/\").findLast((segment) => segment.length > 0),\n              role: existing?.role,\n              agentPath: existing?.agentPath ?? item.agentPath,\n              depth: existing?.depth,\n              parentThreadId: existing?.parentThreadId,\n              spawnTurnId: existing ? existing.spawnTurnId : activitySpawnTurnId,\n            });\n            return next;\n          });\n          const registeredChild = (yield* Ref.get(collabChildAgentsRef)).get(item.agentThreadId);\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"collabAgent/activity\",\n            ...(registeredChild?.spawnTurnId ? { turnId: registeredChild.spawnTurnId } : {}),\n            payload: {\n              agentThreadId: item.agentThreadId,\n              agentPath: item.agentPath,\n              activityKind: item.kind,\n            },\n          });\n          return true;\n        }\n\n        // Interception: notifications addressed to a registered child thread\n        // become agent-scoped synthetic events instead of parent chatter.\n        const providerConversationId = readNotificationThreadId(notification);\n        if (!providerConversationId) {\n          return false;\n        }\n        // Belt-and-braces: the root thread's traffic must never be\n        // intercepted, whatever the registry says.\n        const interceptRootId = currentProviderThreadId(yield* Ref.get(sessionRef));\n        if (providerConversationId === interceptRootId) {\n          return false;\n        }\n        const children = yield* Ref.get(collabChildAgentsRef);\n        const child = children.get(providerConversationId);\n        if (!child) {\n          return false;\n        }\n        const childIdentity = {\n          agentThreadId: child.agentThreadId,\n          ...(child.nickname ? { nickname: child.nickname } : {}),\n          ...(child.role ? { role: child.role } : {}),\n          ...(child.agentPath ? { agentPath: child.agentPath } : {}),\n        };\n        switch (notification.method) {\n          case \"turn/started\": {\n            const childTurnId =\n              typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === \"string\"\n                ? ((notification.params as { turn: { id: string } }).turn.id as string)\n                : undefined;\n            if (childTurnId) {\n              yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n                const next = new Map(current);\n                next.set(child.agentThreadId, childTurnId);\n                return next;\n              });\n            }\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/turnStarted\",\n              payload: childIdentity,\n            });\n            return true;\n          }\n          case \"turn/completed\":\n            yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n              const next = new Map(current);\n              next.delete(child.agentThreadId);\n              return next;\n            });\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/turnCompleted\",\n              payload: {\n                ...childIdentity,\n                turn: notification.params.turn,\n              },\n            });\n            return true;\n          case \"thread/status/changed\":\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/statusChanged\",\n              payload: {\n                ...childIdentity,\n                status: notification.params.status,\n              },\n            });\n            return true;\n          case \"thread/tokenUsage/updated\":\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/tokenUsage\",\n              payload: {\n                ...childIdentity,\n                tokenUsage: notification.params.tokenUsage,\n              },\n            });\n            return true;\n          case \"item/started\":\n          case \"item/completed\":\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/item\",\n              payload: {\n                ...childIdentity,\n                item: notification.params.item,\n              },\n            });\n            return true;\n          case \"thread/closed\":\n            // The child is gone: drop its live-turn entry so a later Stop\n            // doesn't waste a turn/interrupt RPC on a closed thread before\n            // reaching the parent (review finding).\n            yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n              const next = new Map(current);\n              next.delete(child.agentThreadId);\n              return next;\n            });\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/closed\",\n              payload: childIdentity,\n            });\n            return true;\n          case \"error\": {\n            // A child error must surface as a failed agent, not vanish into\n            // the default swallow (review finding: the child stayed\n            // \"running\" forever). Retryable errors (willRetry) keep the\n            // child RUNNING and interruptible — mirroring the root error\n            // handler; settling it would orphan a still-live child from\n            // Stop (review finding). Terminal errors clean up the live turn\n            // like thread/closed and reuse the statusChanged systemError\n            // path.\n            const willRetry = (notification.params as { willRetry?: boolean }).willRetry === true;\n            if (willRetry) {\n              return true;\n            }\n            yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n              const next = new Map(current);\n              next.delete(child.agentThreadId);\n              return next;\n            });\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/statusChanged\",\n              payload: {\n                ...childIdentity,\n                status: { type: \"systemError\" },\n              },\n            });\n            return true;\n          }\n          default:\n            // Routing table decides (single source of truth, asserted\n            // against captured wire traces): enumerated chatter is dropped,\n            // everything else — including methods this build has never seen\n            // — falls through to the parent path rather than vanishing.\n            return routeCodexChildNotification(notification.method) === \"drop\";\n        }\n      });\n\n    const handleRawNotification = (notification: CodexServerNotification) =>\n      Effect.gen(function* () {\n        const payload = notification.params;\n        const route = readRouteFields(notification);\n        const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef);\n        const childParentTurnId = (() => {\n          const providerConversationId = readNotificationThreadId(notification);\n          return providerConversationId\n            ? collabReceiverTurns.get(providerConversationId)\n            : undefined;\n        })();\n\n        rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);\n        // Interception FIRST: a registered v2 child is usually also in the\n        // receiver-turn map (collabAgentToolCall.receiverThreadIds), and the\n        // legacy suppressor below would drop its lifecycle before it could\n        // become synthetic collabAgent events (review finding). The\n        // suppressor still covers UNREGISTERED children.\n        if (yield* interceptCollabChildNotification(notification)) {\n          yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);\n          return;\n        }\n\n        // Suppression applies to receiver-map children (v1) AND to any\n        // conversation that is not the root thread. The live capture\n        // (codexMultiAgentWire.json) shows a child's thread/status/changed\n        // arriving BEFORE anything registers the child — pre-registration\n        // lifecycle must not reach the parent path, where the adapter maps\n        // thread/* onto parent session state. Root-id-known guard keeps the\n        // root's own early notifications flowing during session open.\n        const suppressRootId = currentProviderThreadId(yield* Ref.get(sessionRef));\n        const foreignConversation = (() => {\n          const providerConversationId = readNotificationThreadId(notification);\n          return (\n            providerConversationId !== undefined &&\n            suppressRootId !== undefined &&\n            providerConversationId !== suppressRootId\n          );\n        })();\n        if (\n          (childParentTurnId !== undefined || foreignConversation) &&\n          shouldSuppressChildConversationNotification(notification.method)\n        ) {\n          // Stop-everything must not depend on registration timing: a\n          // child's turn/started can arrive before the subAgentActivity that\n          // registers it (captured ordering), and suppressing it without\n          // remembering the live turn would leave that child running after\n          // Stop (review finding). Track live turns for ANY foreign\n          // conversation; interrupts are best-effort per child, so a\n          // false-positive entry costs one ignored RPC at worst.\n          const foreignThreadId = readNotificationThreadId(notification);\n          if (foreignThreadId !== undefined) {\n            if (notification.method === \"turn/started\") {\n              const foreignTurnId =\n                typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === \"string\"\n                  ? (notification.params as { turn: { id: string } }).turn.id\n                  : undefined;\n              if (foreignTurnId) {\n                yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n                  const next = new Map(current);\n                  next.set(foreignThreadId, foreignTurnId);\n                  return next;\n                });\n              }\n            } else if (\n              notification.method === \"turn/completed\" ||\n              notification.method === \"thread/closed\"\n            ) {\n              yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n                const next = new Map(current);\n                next.delete(foreignThreadId);\n                return next;\n              });\n            }\n          }\n          yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);\n          return;\n        }\n\n        let requestId: ApprovalRequestId | undefined;\n        let requestKind: ProviderRequestKind | undefined;\n        let turnId = childParentTurnId ?? route.turnId;\n        let itemId = route.itemId;\n\n        if (notification.method === \"serverRequest/resolved\") {\n          const rawRequestId =\n            typeof notification.params.requestId === \"string\"\n              ? notification.params.requestId\n              : String(notification.params.requestId);\n          const correlation = rawRequestId\n            ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId)\n            : undefined;\n          if (correlation) {\n            requestId = correlation.requestId;\n            requestKind = correlation.requestKind;\n            turnId = correlation.turnId ?? turnId;\n            itemId = correlation.itemId ?? itemId;\n            yield* Ref.update(approvalCorrelationsRef, (current) => {\n              const next = new Map(current);\n              next.delete(rawRequestId);\n              return next;\n            });\n          }\n        }\n\n        yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);\n        yield* emitEvent({\n          kind: \"notification\",\n          threadId: options.threadId,\n          method: notification.method,\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          ...(requestId ? { requestId } : {}),\n          ...(requestKind ? { requestKind } : {}),\n          ...(notification.method === \"item/agentMessage/delta\"\n            ? { textDelta: notification.params.delta }\n            : {}),\n          ...(payload !== undefined ? { payload } : {}),\n        });\n      });\n\n    const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId);\n\n    yield* client.handleServerNotification(\"thread/started\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          if (providerThreadId && payload.thread.id !== providerThreadId) {\n            return Effect.void;\n          }\n          return updateSession(sessionRef, {\n            resumeCursor: { threadId: payload.thread.id },\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerNotification(\"turn/started\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          if (providerThreadId && payload.threadId !== providerThreadId) {\n            return Effect.void;\n          }\n          return updateSession(sessionRef, {\n            status: \"running\",\n            activeTurnId: TurnId.make(payload.turn.id),\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerNotification(\"turn/completed\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          if (providerThreadId && payload.threadId !== providerThreadId) {\n            return Effect.void;\n          }\n          const lastError =\n            payload.turn.status === \"failed\" && \"error\" in payload.turn && payload.turn.error\n              ? payload.turn.error.message\n              : undefined;\n          return updateSession(sessionRef, {\n            status: payload.turn.status === \"failed\" ? \"error\" : \"ready\",\n            activeTurnId: undefined,\n            ...(lastError ? { lastError } : {}),\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerNotification(\"error\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          const payloadThreadId = payload.threadId;\n          if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) {\n            return Effect.void;\n          }\n          const errorMessage = payload.error.message;\n          const willRetry = payload.willRetry;\n          return updateSession(sessionRef, {\n            status: willRetry ? \"running\" : \"error\",\n            ...(errorMessage ? { lastError: errorMessage } : {}),\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerRequest(\"item/commandExecution/requestApproval\", (payload) =>\n      Effect.gen(function* () {\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4(\"command-approval-request\"));\n        const turnId = TurnId.make(payload.turnId);\n        const itemId = ProviderItemId.make(payload.itemId);\n        const decision = yield* Deferred.make<ProviderApprovalDecision>();\n\n        yield* Ref.update(pendingApprovalsRef, (current) => {\n          const next = new Map(current);\n          next.set(requestId, {\n            requestId,\n            jsonRpcId: payload.approvalId ?? payload.itemId,\n            requestKind: \"command\",\n            turnId,\n            itemId,\n            decision,\n          });\n          return next;\n        });\n        yield* Ref.update(approvalCorrelationsRef, (current) => {\n          const next = new Map(current);\n          next.set(payload.approvalId ?? payload.itemId, {\n            requestId,\n            requestKind: \"command\",\n            turnId,\n            itemId,\n          });\n          return next;\n        });\n\n        yield* emitEvent({\n          kind: \"request\",\n          threadId: options.threadId,\n          method: \"item/commandExecution/requestApproval\",\n          requestId,\n          requestKind: \"command\",\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          payload,\n        });\n\n        const resolved = yield* Deferred.await(decision).pipe(\n          Effect.ensuring(\n            Ref.update(pendingApprovalsRef, (current) => {\n              const next = new Map(current);\n              next.delete(requestId);\n              return next;\n            }),\n          ),\n        );\n        return {\n          decision: resolved,\n        } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse;\n      }),\n    );\n\n    yield* client.handleServerRequest(\"item/fileChange/requestApproval\", (payload) =>\n      Effect.gen(function* () {\n        const requestId = ApprovalRequestId.make(\n          yield* randomUUIDv4(\"file-change-approval-request\"),\n        );\n        const turnId = TurnId.make(payload.turnId);\n        const itemId = ProviderItemId.make(payload.itemId);\n        const decision = yield* Deferred.make<ProviderApprovalDecision>();\n\n        yield* Ref.update(pendingApprovalsRef, (current) => {\n          const next = new Map(current);\n          next.set(requestId, {\n            requestId,\n            jsonRpcId: payload.itemId,\n            requestKind: \"file-change\",\n            turnId,\n            itemId,\n            decision,\n          });\n          return next;\n        });\n        yield* Ref.update(approvalCorrelationsRef, (current) => {\n          const next = new Map(current);\n          next.set(payload.itemId, {\n            requestId,\n            requestKind: \"file-change\",\n            turnId,\n            itemId,\n          });\n          return next;\n        });\n\n        yield* emitEvent({\n          kind: \"request\",\n          threadId: options.threadId,\n          method: \"item/fileChange/requestApproval\",\n          requestId,\n          requestKind: \"file-change\",\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          payload,\n        });\n\n        const resolved = yield* Deferred.await(decision).pipe(\n          Effect.ensuring(\n            Ref.update(pendingApprovalsRef, (current) => {\n              const next = new Map(current);\n              next.delete(requestId);\n              return next;\n            }),\n          ),\n        );\n        return {\n          decision: resolved,\n        } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse;\n      }),\n    );\n\n    yield* client.handleServerRequest(\"item/tool/requestUserInput\", (payload) =>\n      Effect.gen(function* () {\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4(\"user-input-request\"));\n        const turnId = TurnId.make(payload.turnId);\n        const itemId = ProviderItemId.make(payload.itemId);\n        const answers = yield* Deferred.make<ProviderUserInputAnswers>();\n\n        yield* Ref.update(pendingUserInputsRef, (current) => {\n          const next = new Map(current);\n          next.set(requestId, {\n            requestId,\n            turnId,\n            itemId,\n            answers,\n          });\n          return next;\n        });\n\n        yield* emitEvent({\n          kind: \"request\",\n          threadId: options.threadId,\n          method: \"item/tool/requestUserInput\",\n          requestId,\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          payload,\n        });\n\n        const resolvedAnswers = yield* Deferred.await(answers).pipe(\n          Effect.ensuring(\n            Ref.update(pendingUserInputsRef, (current) => {\n              const next = new Map(current);\n              next.delete(requestId);\n              return next;\n            }),\n          ),\n        );\n\n        return {\n          answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe(\n            Effect.mapError((error) =>\n              CodexErrors.CodexAppServerRequestError.invalidParams(error.message, {\n                questionId: error.questionId,\n              }),\n            ),\n          ),\n        } satisfies EffectCodexSchema.ToolRequestUserInputResponse;\n      }),\n    );\n\n    yield* client.handleUnknownServerRequest((method) =>\n      Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)),\n    );\n\n    const registerServerNotification = <M extends CodexRpc.ServerNotificationMethod>(method: M) =>\n      client.handleServerNotification(method, (params) =>\n        Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe(\n          Effect.asVoid,\n        ),\n      );\n\n    yield* Effect.forEach(\n      Object.values(\n        CodexRpc.SERVER_NOTIFICATION_METHODS,\n      ) as ReadonlyArray<CodexRpc.ServerNotificationMethod>,\n      registerServerNotification,\n      { concurrency: 1, discard: true },\n    );\n\n    yield* Stream.fromQueue(serverNotifications).pipe(\n      Stream.runForEach(handleRawNotification),\n      Effect.forkIn(runtimeScope),\n    );\n\n    const stderrRemainderRef = yield* Ref.make(\"\");\n    yield* child.stderr.pipe(\n      Stream.decodeText(),\n      Stream.runForEach((chunk) =>\n        Ref.modify(stderrRemainderRef, (current) => {\n          const combined = current + chunk;\n          const lines = combined.split(\"\\n\");\n          const remainder = lines.pop() ?? \"\";\n          return [lines.map((line) => line.replace(/\\r$/, \"\")), remainder] as const;\n        }).pipe(\n          Effect.flatMap((lines) =>\n            Effect.forEach(\n              lines,\n              (line) => {\n                const classified = classifyCodexStderrLine(line);\n                if (!classified) {\n                  return Effect.void;\n                }\n                return emitEvent({\n                  kind: \"notification\",\n                  threadId: options.threadId,\n                  method: \"process/stderr\",\n                  message: classified.message,\n                });\n              },\n              { discard: true },\n            ),\n          ),\n        ),\n      ),\n      Effect.forkIn(runtimeScope),\n    );\n\n    yield* child.exitCode.pipe(\n      Effect.flatMap((exitCode) =>\n        Ref.get(closedRef).pipe(\n          Effect.flatMap((closed) => {\n            if (closed) {\n              return Effect.void;\n            }\n            const nextStatus = exitCode === 0 ? \"closed\" : \"error\";\n            return updateSession(sessionRef, {\n              status: nextStatus,\n              activeTurnId: undefined,\n            }).pipe(\n              Effect.andThen(\n                emitSessionEvent(\n                  \"session/exited\",\n                  exitCode === 0\n                    ? \"Codex App Server exited.\"\n                    : `Codex App Server exited with code ${exitCode}.`,\n                ),\n              ),\n            );\n          }),\n        ),\n      ),\n      Effect.forkIn(runtimeScope),\n    );\n\n    const start = Effect.fn(\"CodexSessionRuntime.start\")(function* () {\n      yield* emitSessionEvent(\"session/connecting\", \"Starting Codex App Server session.\");\n      yield* initializeClient;\n\n      const requestedModel = normalizeCodexModelSlug(options.model);\n\n      const opened = yield* openCodexThread({\n        client,\n        threadId: options.threadId,\n        runtimeMode: options.runtimeMode,\n        cwd: options.cwd,\n        requestedModel,\n        serviceTier: options.serviceTier,\n        resumeThreadId: readResumeCursorThreadId(options.resumeCursor),\n      });\n\n      const providerThreadId = opened.thread.id;\n      const session = {\n        ...(yield* Ref.get(sessionRef)),\n        status: \"ready\",\n        cwd: opened.cwd,\n        model: opened.model,\n        resumeCursor: { threadId: providerThreadId },\n        updatedAt: yield* nowIso,\n      } satisfies ProviderSession;\n      yield* Ref.set(sessionRef, session);\n      yield* emitSessionEvent(\"session/ready\", \"Codex App Server session ready.\");\n      return session;\n    });\n\n    const readProviderThreadId = Effect.gen(function* () {\n      const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));\n      if (!providerThreadId) {\n        return yield* new CodexSessionRuntimeThreadIdMissingError({\n          threadId: options.threadId,\n        });\n      }\n      return providerThreadId;\n    });\n\n    const close = Effect.gen(function* () {\n      const alreadyClosed = yield* Ref.getAndSet(closedRef, true);\n      if (alreadyClosed) {\n        return;\n      }\n      yield* settlePendingApprovals(\"cancel\");\n      yield* settlePendingUserInputs({});\n      yield* updateSession(sessionRef, {\n        status: \"closed\",\n        activeTurnId: undefined,\n      });\n      yield* emitSessionEvent(\"session/closed\", \"Session stopped\").pipe(\n        Effect.catch((cause) =>\n          Effect.logError(\"Failed to emit Codex session closed event.\", { cause }),\n        ),\n      );\n      yield* Scope.close(runtimeScope, Exit.void);\n      yield* Queue.shutdown(serverNotifications);\n      yield* Queue.shutdown(events);\n    });\n\n    return {\n      start,\n      getSession: Ref.get(sessionRef),\n      sendTurn: (input) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          if (hasConfiguredMcpServer(options.appServerArgs)) {\n            yield* client.request(\"config/mcpServer/reload\", undefined).pipe(\n              Effect.catch((cause) =>\n                Effect.logWarning(\"Failed to refresh Codex MCP tool catalog before turn.\", {\n                  cause,\n                }),\n              ),\n            );\n          }\n          const normalizedModel = normalizeCodexModelSlug(\n            input.model ?? (yield* Ref.get(sessionRef)).model,\n          );\n          const params = yield* buildTurnStartParams({\n            threadId: providerThreadId,\n            runtimeMode: options.runtimeMode,\n            ...(input.input ? { prompt: input.input } : {}),\n            ...(input.attachments ? { attachments: input.attachments } : {}),\n            ...(normalizedModel ? { model: normalizedModel } : {}),\n            ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),\n            ...(input.effort ? { effort: input.effort } : {}),\n            ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),\n          });\n          const rawResponse = yield* client.raw.request(\"turn/start\", params);\n          const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(\n            Effect.mapError((error) =>\n              CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(\n                \"decode-response-payload\",\n                error,\n                { method: \"turn/start\" },\n              ),\n            ),\n          );\n          const turnId = TurnId.make(response.turn.id);\n          yield* updateSession(sessionRef, {\n            status: \"running\",\n            activeTurnId: turnId,\n            ...(normalizedModel ? { model: normalizedModel } : {}),\n          });\n          const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));\n          return {\n            threadId: options.threadId,\n            turnId,\n            ...(resumedProviderThreadId\n              ? { resumeCursor: { threadId: resumedProviderThreadId } }\n              : {}),\n          } satisfies ProviderTurnStartResult;\n        }),\n      interruptTurn: (turnId) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          const session = yield* Ref.get(sessionRef);\n          // Stop-everything: children are full threads with their own turns;\n          // interrupting only the parent leaves the fleet running. Interrupt\n          // each live child turn first, best-effort per child, BOUNDED: the\n          // transport awaits an unbounded Deferred per request, so a wedged\n          // child would otherwise block the parent interrupt forever —\n          // exactly during the runaway fleet where Stop matters most\n          // (review finding). Per-child and overall deadlines guarantee the\n          // parent interrupt below always runs.\n          const liveChildTurns = yield* Ref.get(collabChildLiveTurnsRef);\n          yield* Effect.forEach(\n            Array.from(liveChildTurns.entries()),\n            ([childThreadId, childTurnId]) =>\n              client\n                .request(\"turn/interrupt\", {\n                  threadId: childThreadId,\n                  turnId: childTurnId,\n                })\n                .pipe(Effect.timeoutOption(\"3 seconds\"), Effect.ignore),\n            { concurrency: 8, discard: true },\n          ).pipe(Effect.timeoutOption(\"10 seconds\"), Effect.ignore);\n          const effectiveTurnId = turnId ?? session.activeTurnId;\n          if (!effectiveTurnId) {\n            return;\n          }\n          yield* client.request(\"turn/interrupt\", {\n            threadId: providerThreadId,\n            turnId: effectiveTurnId,\n          });\n        }),\n      startRealtimeVoiceInput: () =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          yield* client.raw.request(\"thread/realtime/start\", {\n            threadId: providerThreadId,\n            outputModality: \"text\",\n            transport: { type: \"websocket\" },\n            clientManagedHandoffs: true,\n          });\n        }),\n      appendRealtimeVoiceAudio: (audio) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          yield* client.raw.request(\"thread/realtime/appendAudio\", {\n            threadId: providerThreadId,\n            audio,\n          });\n        }),\n      stopRealtimeVoiceInput: () =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          yield* client.raw.request(\"thread/realtime/stop\", { threadId: providerThreadId });\n        }),\n      readThread: Effect.gen(function* () {\n        const providerThreadId = yield* readProviderThreadId;\n        yield* initializeClient;\n        const response = yield* client.request(\"thread/read\", {\n          threadId: providerThreadId,\n          includeTurns: true,\n        });\n        return parseThreadSnapshot(response);\n      }),\n      rollbackThread: (numTurns) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          const response = yield* client.request(\"thread/rollback\", {\n            threadId: providerThreadId,\n            numTurns,\n          });\n          yield* updateSession(sessionRef, {\n            status: \"ready\",\n            activeTurnId: undefined,\n          });\n          return parseThreadSnapshot(response);\n        }),\n      respondToRequest: (requestId, decision) =>\n        Effect.gen(function* () {\n          const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId);\n          if (!pending) {\n            return yield* new CodexSessionRuntimePendingApprovalNotFoundError({\n              requestId,\n            });\n          }\n          yield* Ref.update(pendingApprovalsRef, (current) => {\n            const next = new Map(current);\n            next.delete(requestId);\n            return next;\n          });\n          yield* Deferred.succeed(pending.decision, decision);\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"item/requestApproval/decision\",\n            requestId: pending.requestId,\n            requestKind: pending.requestKind,\n            ...(pending.turnId ? { turnId: pending.turnId } : {}),\n            ...(pending.itemId ? { itemId: pending.itemId } : {}),\n            payload: {\n              requestId: pending.requestId,\n              requestKind: pending.requestKind,\n              decision,\n            },\n          });\n        }),\n      respondToUserInput: (requestId, answers) =>\n        Effect.gen(function* () {\n          const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId);\n          if (!pending) {\n            return yield* new CodexSessionRuntimePendingUserInputNotFoundError({\n              requestId,\n            });\n          }\n          const codexAnswers = yield* toCodexUserInputAnswers(answers);\n          yield* Ref.update(pendingUserInputsRef, (current) => {\n            const next = new Map(current);\n            next.delete(requestId);\n            return next;\n          });\n          yield* Deferred.succeed(pending.answers, answers);\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"item/tool/requestUserInput/answered\",\n            requestId: pending.requestId,\n            ...(pending.turnId ? { turnId: pending.turnId } : {}),\n            ...(pending.itemId ? { itemId: pending.itemId } : {}),\n            payload: {\n              answers: codexAnswers,\n            },\n          });\n        }),\n      events: Stream.fromQueue(events),\n      close,\n    } satisfies CodexSessionRuntimeShape;\n  });\n","/**\n * CodexAdapterLive - Scoped live implementation for the Codex provider adapter.\n *\n * Wraps the typed Codex session runtime behind the `CodexAdapter` service\n * contract and maps runtime failures into the shared `ProviderAdapterError`\n * algebra.\n *\n * @module CodexAdapterLive\n */\nimport {\n  type CanonicalItemType,\n  type CanonicalRequestType,\n  type CodexSettings,\n  EventId,\n  ProviderDriverKind,\n  type ProviderEvent,\n  ProviderInstanceId,\n  ProviderItemId,\n  type ProviderRuntimeEvent,\n  type ProviderRequestKind,\n  type ThreadTokenUsageSnapshot,\n  type ProviderUserInputAnswers,\n  RuntimeItemId,\n  RuntimeRequestId,\n  RuntimeTaskId,\n  type RuntimeTaskUsage,\n  ProviderApprovalDecision,\n  ThreadId,\n  TurnId,\n  ProviderSendTurnInput,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\nimport * as CodexErrors from \"effect-codex-app-server/errors\";\nimport * as EffectCodexSchema from \"effect-codex-app-server/schema\";\n\nimport { getModelSelectionStringOptionValue } from \"@t3tools/shared/model\";\nimport { getCodexServiceTierOptionValue } from \"../../codexModelOptions.ts\";\n\nimport {\n  ProviderAdapterRequestError,\n  ProviderAdapterProcessError,\n  ProviderAdapterSessionClosedError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n  type ProviderAdapterError,\n} from \"../Errors.ts\";\nimport { type CodexAdapterShape } from \"../Services/CodexAdapter.ts\";\nimport type { ProviderThreadSnapshot } from \"../Services/ProviderAdapter.ts\";\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport {\n  CodexResumeCursorSchema,\n  CodexSessionRuntimeThreadIdMissingError,\n  makeCodexSessionRuntime,\n  type CodexSessionRuntimeError,\n  type CodexSessionRuntimeOptions,\n  type CodexSessionRuntimeShape,\n  type CodexThreadSnapshot,\n} from \"./CodexSessionRuntime.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nimport { resolveCodexLaunchArgs } from \"./codexLaunchArgs.ts\";\nconst isCodexAppServerProcessExitedError = Schema.is(CodexErrors.CodexAppServerProcessExitedError);\nconst isCodexAppServerTransportError = Schema.is(CodexErrors.CodexAppServerTransportError);\nconst isCodexSessionRuntimeThreadIdMissingError = Schema.is(\n  CodexSessionRuntimeThreadIdMissingError,\n);\nconst isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);\n\nconst PROVIDER = ProviderDriverKind.make(\"codex\");\n\nexport interface CodexAdapterLiveOptions {\n  readonly instanceId?: ProviderInstanceId;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly makeRuntime?: (\n    options: CodexSessionRuntimeOptions,\n  ) => Effect.Effect<\n    CodexSessionRuntimeShape,\n    CodexSessionRuntimeError,\n    ChildProcessSpawner.ChildProcessSpawner | Scope.Scope\n  >;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n}\n\ninterface CodexAdapterSessionContext {\n  readonly threadId: ThreadId;\n  readonly scope: Scope.Closeable;\n  readonly runtime: CodexSessionRuntimeShape;\n  readonly eventFiber: Fiber.Fiber<void, never>;\n  stopped: boolean;\n}\n\nfunction mapCodexRuntimeError(\n  threadId: ThreadId,\n  method: string,\n  error: CodexSessionRuntimeError,\n): ProviderAdapterError {\n  if (isCodexAppServerProcessExitedError(error) || isCodexAppServerTransportError(error)) {\n    return new ProviderAdapterSessionClosedError({\n      provider: PROVIDER,\n      threadId,\n      cause: error,\n    });\n  }\n\n  if (isCodexSessionRuntimeThreadIdMissingError(error)) {\n    return new ProviderAdapterSessionNotFoundError({\n      provider: PROVIDER,\n      threadId,\n      cause: error,\n    });\n  }\n\n  return new ProviderAdapterRequestError({\n    provider: PROVIDER,\n    method,\n    detail: error.message,\n    cause: error,\n  });\n}\n\ntype CodexLifecycleItem =\n  | EffectCodexSchema.V2ItemStartedNotification[\"item\"]\n  | EffectCodexSchema.V2ItemCompletedNotification[\"item\"];\n\ntype CodexToolUserInputQuestion =\n  | EffectCodexSchema.ServerRequest__ToolRequestUserInputQuestion\n  | EffectCodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion;\n\nconst ApprovalDecisionPayload = Schema.Struct({\n  decision: ProviderApprovalDecision,\n});\n\nfunction readPayload<A>(\n  schema: Schema.Schema<A>,\n  payload: ProviderEvent[\"payload\"],\n): A | undefined {\n  const isPayload = Schema.is(schema);\n  return isPayload(payload) ? payload : undefined;\n}\n\nfunction trimText(value: string | undefined | null): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nconst FATAL_CODEX_STDERR_SNIPPETS = [\"failed to connect to websocket\"];\n\nfunction isFatalCodexProcessStderrMessage(message: string): boolean {\n  const normalized = message.toLowerCase();\n  return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));\n}\n\nfunction normalizeCodexTokenUsage(\n  usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification[\"tokenUsage\"],\n): ThreadTokenUsageSnapshot | undefined {\n  const totalProcessedTokens = usage.total.totalTokens;\n  const usedTokens = usage.last.totalTokens;\n  if (usedTokens === undefined || usedTokens <= 0) {\n    return undefined;\n  }\n\n  const maxTokens = usage.modelContextWindow ?? undefined;\n  const inputTokens = usage.last.inputTokens;\n  const cachedInputTokens = usage.last.cachedInputTokens;\n  const outputTokens = usage.last.outputTokens;\n  const reasoningOutputTokens = usage.last.reasoningOutputTokens;\n\n  return {\n    usedTokens,\n    ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens\n      ? { totalProcessedTokens }\n      : {}),\n    ...(maxTokens !== undefined ? { maxTokens } : {}),\n    ...(inputTokens !== undefined ? { inputTokens } : {}),\n    ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n    ...(outputTokens !== undefined ? { outputTokens } : {}),\n    ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),\n    ...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),\n    ...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),\n    ...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),\n    ...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),\n    ...(reasoningOutputTokens !== undefined\n      ? { lastReasoningOutputTokens: reasoningOutputTokens }\n      : {}),\n    compactsAutomatically: true,\n  };\n}\n\nfunction toTurnStatus(\n  value: EffectCodexSchema.V2TurnCompletedNotification[\"turn\"][\"status\"] | \"cancelled\",\n): \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" {\n  switch (value) {\n    case \"completed\":\n    case \"failed\":\n    case \"cancelled\":\n    case \"interrupted\":\n      return value;\n    default:\n      return \"completed\";\n  }\n}\n\nfunction normalizeItemType(raw: string | undefined | null): string {\n  const type = trimText(raw);\n  if (!type) return \"item\";\n  return type\n    .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n    .replace(/[._/-]/g, \" \")\n    .replace(/\\s+/g, \" \")\n    .trim()\n    .toLowerCase();\n}\n\nfunction toCanonicalItemType(raw: string | undefined | null): CanonicalItemType {\n  const type = normalizeItemType(raw);\n  if (type.includes(\"user\")) return \"user_message\";\n  if (type.includes(\"agent message\") || type.includes(\"assistant\")) return \"assistant_message\";\n  if (type.includes(\"reasoning\") || type.includes(\"thought\")) return \"reasoning\";\n  if (type.includes(\"plan\") || type.includes(\"todo\")) return \"plan\";\n  if (type.includes(\"command\")) return \"command_execution\";\n  if (type.includes(\"file change\") || type.includes(\"patch\") || type.includes(\"edit\"))\n    return \"file_change\";\n  if (type.includes(\"mcp\")) return \"mcp_tool_call\";\n  if (type.includes(\"dynamic tool\")) return \"dynamic_tool_call\";\n  if (type.includes(\"collab\")) return \"collab_agent_tool_call\";\n  if (type.includes(\"web search\")) return \"web_search\";\n  if (type.includes(\"image\")) return \"image_view\";\n  if (type.includes(\"review entered\")) return \"review_entered\";\n  if (type.includes(\"review exited\")) return \"review_exited\";\n  if (type.includes(\"compact\")) return \"context_compaction\";\n  if (type.includes(\"error\")) return \"error\";\n  return \"unknown\";\n}\n\nfunction itemTitle(itemType: CanonicalItemType, item?: CodexLifecycleItem): string | undefined {\n  if (itemType === \"mcp_tool_call\" && item?.type === \"mcpToolCall\") {\n    return `${item.server} · ${item.tool}`;\n  }\n  switch (itemType) {\n    case \"assistant_message\":\n      return \"Assistant message\";\n    case \"user_message\":\n      return \"User message\";\n    case \"reasoning\":\n      return \"Reasoning\";\n    case \"plan\":\n      return \"Plan\";\n    case \"command_execution\":\n      return \"Ran command\";\n    case \"file_change\":\n      return \"File change\";\n    case \"mcp_tool_call\":\n      return \"MCP tool call\";\n    case \"dynamic_tool_call\":\n      return \"Tool call\";\n    case \"web_search\":\n      return \"Web search\";\n    case \"image_view\":\n      return \"Image view\";\n    case \"error\":\n      return \"Error\";\n    default:\n      return undefined;\n  }\n}\n\nfunction itemDetail(itemType: CanonicalItemType, item: CodexLifecycleItem): string | undefined {\n  const itemRecord = item as Record<string, unknown>;\n  const action = itemRecord.action as Record<string, unknown> | undefined;\n  const actionQueries = Array.isArray(action?.queries) ? action.queries : [];\n  const candidates = [\n    ...(itemType === \"web_search\"\n      ? [itemRecord.query, action?.query, ...actionQueries, action?.pattern, action?.url]\n      : []),\n    \"command\" in item ? item.command : undefined,\n    \"title\" in item ? item.title : undefined,\n    \"summary\" in item ? item.summary : undefined,\n    \"text\" in item ? item.text : undefined,\n    \"path\" in item ? item.path : undefined,\n    \"prompt\" in item ? item.prompt : undefined,\n  ];\n\n  for (const candidate of candidates) {\n    const trimmed = typeof candidate === \"string\" ? trimText(candidate) : undefined;\n    if (!trimmed) continue;\n    return trimmed;\n  }\n  return undefined;\n}\n\nfunction toRequestTypeFromMethod(method: string): CanonicalRequestType {\n  switch (method) {\n    case \"item/commandExecution/requestApproval\":\n      return \"command_execution_approval\";\n    case \"item/fileRead/requestApproval\":\n      return \"file_read_approval\";\n    case \"item/fileChange/requestApproval\":\n      return \"file_change_approval\";\n    case \"applyPatchApproval\":\n      return \"apply_patch_approval\";\n    case \"execCommandApproval\":\n      return \"exec_command_approval\";\n    case \"item/tool/requestUserInput\":\n      return \"tool_user_input\";\n    case \"item/tool/call\":\n      return \"dynamic_tool_call\";\n    case \"account/chatgptAuthTokens/refresh\":\n      return \"auth_tokens_refresh\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction toRequestTypeFromKind(kind: ProviderRequestKind | undefined): CanonicalRequestType {\n  switch (kind) {\n    case \"command\":\n      return \"command_execution_approval\";\n    case \"file-read\":\n      return \"file_read_approval\";\n    case \"file-change\":\n      return \"file_change_approval\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction toCanonicalUserInputAnswers(\n  answers: EffectCodexSchema.ToolRequestUserInputResponse[\"answers\"],\n): ProviderUserInputAnswers {\n  return Object.fromEntries(\n    Object.entries(answers).map(([questionId, value]) => {\n      const normalizedAnswers = value.answers.length === 1 ? value.answers[0]! : [...value.answers];\n      return [questionId, normalizedAnswers] as const;\n    }),\n  );\n}\n\nfunction toUserInputQuestions(questions: ReadonlyArray<CodexToolUserInputQuestion>) {\n  const parsedQuestions = questions\n    .map((question) => {\n      const options =\n        question.options\n          ?.map((option) => {\n            const label = trimText(option.label);\n            const description = trimText(option.description);\n            if (!label || !description) {\n              return undefined;\n            }\n            return { label, description };\n          })\n          .filter((option) => option !== undefined) ?? [];\n\n      const id = trimText(question.id);\n      const header = trimText(question.header);\n      const prompt = trimText(question.question);\n      if (!id || !header || !prompt || options.length === 0) {\n        return undefined;\n      }\n      return {\n        id,\n        header,\n        question: prompt,\n        options,\n        multiSelect: false,\n      };\n    })\n    .filter((question) => question !== undefined);\n\n  return parsedQuestions.length > 0 ? parsedQuestions : undefined;\n}\n\nfunction toThreadState(\n  status: EffectCodexSchema.V2ThreadStatusChangedNotification[\"status\"],\n): \"active\" | \"idle\" | \"archived\" | \"closed\" | \"compacted\" | \"error\" {\n  switch (status.type) {\n    case \"idle\":\n      return \"idle\";\n    case \"systemError\":\n      return \"error\";\n    default:\n      return \"active\";\n  }\n}\n\nfunction contentStreamKindFromMethod(\n  method: string,\n):\n  | \"assistant_text\"\n  | \"reasoning_text\"\n  | \"reasoning_summary_text\"\n  | \"plan_text\"\n  | \"command_output\"\n  | \"file_change_output\" {\n  switch (method) {\n    case \"item/agentMessage/delta\":\n      return \"assistant_text\";\n    case \"item/reasoning/textDelta\":\n      return \"reasoning_text\";\n    case \"item/reasoning/summaryTextDelta\":\n      return \"reasoning_summary_text\";\n    case \"item/commandExecution/outputDelta\":\n      return \"command_output\";\n    case \"item/fileChange/outputDelta\":\n      return \"file_change_output\";\n    default:\n      return \"assistant_text\";\n  }\n}\n\nfunction asRuntimeItemId(itemId: ProviderEvent[\"itemId\"] & string): RuntimeItemId {\n  return RuntimeItemId.make(itemId);\n}\n\nfunction asRuntimeRequestId(requestId: string): RuntimeRequestId {\n  return RuntimeRequestId.make(requestId);\n}\n\nfunction eventRawSource(event: ProviderEvent): NonNullable<ProviderRuntimeEvent[\"raw\"]>[\"source\"] {\n  return event.kind === \"request\" ? \"codex.app-server.request\" : \"codex.app-server.notification\";\n}\n\nfunction providerRefsFromEvent(\n  event: ProviderEvent,\n): ProviderRuntimeEvent[\"providerRefs\"] | undefined {\n  const refs: Record<string, string> = {};\n  if (event.turnId) refs.providerTurnId = event.turnId;\n  if (event.itemId) refs.providerItemId = event.itemId;\n  if (event.requestId) refs.providerRequestId = event.requestId;\n\n  return Object.keys(refs).length > 0 ? (refs as ProviderRuntimeEvent[\"providerRefs\"]) : undefined;\n}\n\nfunction runtimeEventBase(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n): Omit<ProviderRuntimeEvent, \"type\" | \"payload\"> {\n  const refs = providerRefsFromEvent(event);\n  return {\n    eventId: event.id,\n    provider: event.provider,\n    ...(event.providerInstanceId !== undefined\n      ? { providerInstanceId: event.providerInstanceId }\n      : {}),\n    threadId: canonicalThreadId,\n    createdAt: event.createdAt,\n    ...(event.turnId ? { turnId: event.turnId } : {}),\n    ...(event.itemId ? { itemId: asRuntimeItemId(event.itemId) } : {}),\n    ...(event.requestId ? { requestId: asRuntimeRequestId(event.requestId) } : {}),\n    ...(refs ? { providerRefs: refs } : {}),\n    raw: {\n      source: eventRawSource(event),\n      method: event.method,\n      payload: event.payload ?? {},\n    },\n  };\n}\n\nfunction mapItemLifecycle(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n  lifecycle: \"item.started\" | \"item.updated\" | \"item.completed\",\n): ProviderRuntimeEvent | undefined {\n  const payload =\n    readPayload(EffectCodexSchema.V2ItemStartedNotification, event.payload) ??\n    readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);\n  const item = payload?.item;\n  if (!item) {\n    return undefined;\n  }\n  const itemType = toCanonicalItemType(item.type);\n  if (itemType === \"unknown\" && lifecycle !== \"item.updated\") {\n    return undefined;\n  }\n\n  const detail = itemDetail(itemType, item);\n  const status =\n    lifecycle === \"item.started\"\n      ? \"inProgress\"\n      : lifecycle === \"item.completed\"\n        ? \"completed\"\n        : undefined;\n\n  return {\n    ...runtimeEventBase(event, canonicalThreadId),\n    type: lifecycle,\n    payload: {\n      itemType,\n      ...(status ? { status } : {}),\n      ...(itemTitle(itemType, item) ? { title: itemTitle(itemType, item) } : {}),\n      ...(detail ? { detail } : {}),\n      ...(event.payload !== undefined ? { data: event.payload } : {}),\n    },\n  };\n}\n\n/**\n * Maps the session runtime's synthetic `collabAgent/*` events (native\n * multi-agent v2 child-thread signals) into the shared task.* lifecycle.\n * Agent identity = child thread id; nickname is the display title, role is\n * agentRole (fallback: last agentPath segment, then \"general-purpose\").\n * A completed child turn is idle (resumable), not terminal. timelineBypass\n * keeps these rows out of the parent chat.\n */\nfunction mapCollabAgentEvent(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n): ReadonlyArray<ProviderRuntimeEvent> {\n  const payload =\n    typeof event.payload === \"object\" && event.payload !== null\n      ? (event.payload as Record<string, unknown>)\n      : undefined;\n  const agentThreadId = typeof payload?.agentThreadId === \"string\" ? payload.agentThreadId : \"\";\n  if (!payload || agentThreadId.length === 0) {\n    return [];\n  }\n  const base = runtimeEventBase(event, canonicalThreadId);\n  const taskId = RuntimeTaskId.make(agentThreadId);\n  const agentPath = typeof payload.agentPath === \"string\" ? payload.agentPath : undefined;\n  const pathLeaf = agentPath?.split(\"/\").findLast((segment) => segment.length > 0);\n  const nickname = typeof payload.nickname === \"string\" ? payload.nickname : undefined;\n  const role =\n    (typeof payload.role === \"string\" ? payload.role : undefined) ?? pathLeaf ?? \"general-purpose\";\n  // A bare thread id is not a name. Omitting the title lets the client fold\n  // keep the real one from task.started instead of clobbering it (probe\n  // finding: progress rows renamed math_one to its UUID).\n  const knownName = nickname ?? pathLeaf;\n  const title = knownName ?? agentThreadId;\n  // Identity repeated on every status patch so rows are self-describing when\n  // the start row ages out of activity retention (review finding: a\n  // reconstructed agent had a UUID name and no role/path).\n  const statusLinkage = {\n    role,\n    ...(knownName ? { title: knownName } : {}),\n    ...(agentPath ? { agentPath } : {}),\n    timelineBypass: true,\n  } as const;\n\n  switch (event.method) {\n    case \"collabAgent/started\":\n      return [\n        {\n          ...base,\n          type: \"task.started\",\n          payload: {\n            taskId,\n            description: title,\n            title,\n            role,\n            ...(agentPath ? { agentPath } : {}),\n            ...(typeof payload.parentThreadId === \"string\"\n              ? { parentAgentId: payload.parentThreadId }\n              : {}),\n            timelineBypass: true,\n          },\n        },\n      ];\n    case \"collabAgent/activity\": {\n      const activityKind = typeof payload.activityKind === \"string\" ? payload.activityKind : \"\";\n      if (activityKind === \"interrupted\") {\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: \"interrupted\", ...statusLinkage },\n          },\n        ];\n      }\n      if (activityKind === \"started\") {\n        // Wire-probe finding: children often register via subAgentActivity\n        // alone (no thread/started with a spawn source), so this is the one\n        // shot at a task.started with a real name — agentPath leaf beats a\n        // bare thread-id title.\n        return [\n          {\n            ...base,\n            type: \"task.started\",\n            payload: {\n              taskId,\n              description: title,\n              title,\n              role,\n              ...(agentPath ? { agentPath } : {}),\n              timelineBypass: true,\n            },\n          },\n        ];\n      }\n      // interacted → the child is (again) actively driven.\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status: \"running\", ...statusLinkage },\n        },\n      ];\n    }\n    case \"collabAgent/turnStarted\":\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status: \"running\", ...statusLinkage },\n        },\n      ];\n    case \"collabAgent/turnCompleted\": {\n      // Idle, not terminal: the identity is resumable via sendInput/resume.\n      const turn =\n        typeof payload.turn === \"object\" && payload.turn !== null\n          ? (payload.turn as Record<string, unknown>)\n          : undefined;\n      const turnStatus = typeof turn?.status === \"string\" ? turn.status : undefined;\n      const status =\n        turnStatus === \"failed\"\n          ? (\"failed\" as const)\n          : turnStatus === \"interrupted\"\n            ? (\"interrupted\" as const)\n            : (\"idle\" as const);\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status, ...statusLinkage },\n        },\n      ];\n    }\n    case \"collabAgent/statusChanged\": {\n      const status =\n        typeof payload.status === \"object\" && payload.status !== null\n          ? (payload.status as Record<string, unknown>)\n          : undefined;\n      const statusType = typeof status?.type === \"string\" ? status.type : undefined;\n      if (statusType === \"systemError\") {\n        // Silently dropping this once left children stuck running forever.\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: \"failed\", ...statusLinkage },\n          },\n        ];\n      }\n      if (statusType === \"active\") {\n        const flags = Array.isArray(status?.activeFlags) ? status.activeFlags : [];\n        const waiting = flags.some(\n          (flag) => flag === \"waitingOnApproval\" || flag === \"waitingOnUserInput\",\n        );\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: waiting ? \"waiting\" : \"running\", ...statusLinkage },\n          },\n        ];\n      }\n      if (statusType === \"idle\") {\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: \"idle\", ...statusLinkage },\n          },\n        ];\n      }\n      return [];\n    }\n    case \"collabAgent/tokenUsage\": {\n      // Cumulative per child thread: always the `total` breakdown, never\n      // `last` (which shrinks on follow-ups). Client folds max-merge.\n      const tokenUsage =\n        typeof payload.tokenUsage === \"object\" && payload.tokenUsage !== null\n          ? (payload.tokenUsage as Record<string, unknown>)\n          : undefined;\n      const total =\n        typeof tokenUsage?.total === \"object\" && tokenUsage.total !== null\n          ? (tokenUsage.total as Record<string, unknown>)\n          : undefined;\n      const count = (value: unknown): number | undefined =>\n        typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n      // Same validation as every other field: RuntimeTaskUsage.totalTokens\n      // is NonNegativeInt, so NaN/Infinity/negative wire values must miss.\n      const totalTokens = count(total?.totalTokens);\n      if (totalTokens === undefined) {\n        return [];\n      }\n      const typedUsage: RuntimeTaskUsage = {\n        totalTokens,\n        ...(count(total?.inputTokens) !== undefined\n          ? { inputTokens: count(total?.inputTokens) }\n          : {}),\n        ...(count(total?.cachedInputTokens) !== undefined\n          ? { cachedInputTokens: count(total?.cachedInputTokens) }\n          : {}),\n        ...(count(total?.outputTokens) !== undefined\n          ? { outputTokens: count(total?.outputTokens) }\n          : {}),\n        ...(count(total?.reasoningOutputTokens) !== undefined\n          ? { reasoningOutputTokens: count(total?.reasoningOutputTokens) }\n          : {}),\n      };\n      return [\n        {\n          ...base,\n          type: \"task.progress\",\n          payload: {\n            taskId,\n            description: title,\n            ...(knownName ? { title: knownName } : {}),\n            typedUsage,\n            timelineBypass: true,\n          },\n        },\n      ];\n    }\n    case \"collabAgent/item\": {\n      const item =\n        typeof payload.item === \"object\" && payload.item !== null\n          ? (payload.item as Record<string, unknown>)\n          : undefined;\n      const itemTypeRaw = typeof item?.type === \"string\" ? item.type : undefined;\n      if (!itemTypeRaw) {\n        return [];\n      }\n      // A loose summary from the raw item: the child stream is untyped at\n      // this boundary (synthetic event payload), so read best-effort fields\n      // rather than force a schema decode.\n      const looseSummary =\n        (typeof item?.command === \"string\" ? item.command : undefined) ??\n        (typeof item?.title === \"string\" ? item.title : undefined) ??\n        (typeof item?.query === \"string\" ? item.query : undefined);\n      const canonical = toCanonicalItemType(itemTypeRaw);\n      const summary = looseSummary ?? canonical.replaceAll(\"_\", \" \");\n      return [\n        {\n          ...base,\n          type: \"task.progress\",\n          payload: {\n            taskId,\n            description: title,\n            ...(knownName ? { title: knownName } : {}),\n            summary,\n            timelineBypass: true,\n          },\n        },\n      ];\n    }\n    case \"collabAgent/closed\":\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status: \"interrupted\", ...statusLinkage },\n        },\n      ];\n    default:\n      return [];\n  }\n}\n\nfunction mapToRuntimeEvents(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n): ReadonlyArray<ProviderRuntimeEvent> {\n  if (event.kind === \"notification\" && event.method.startsWith(\"collabAgent/\")) {\n    return mapCollabAgentEvent(event, canonicalThreadId);\n  }\n  if (event.kind === \"error\") {\n    if (!event.message) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"runtime.error\",\n        payload: {\n          message: event.message,\n          class: \"provider_error\",\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.kind === \"request\") {\n    if (event.method === \"item/tool/requestUserInput\") {\n      const payload =\n        readPayload(EffectCodexSchema.ServerRequest__ToolRequestUserInputParams, event.payload) ??\n        readPayload(EffectCodexSchema.ToolRequestUserInputParams, event.payload);\n      const questions = payload ? toUserInputQuestions(payload.questions) : undefined;\n      if (!questions) {\n        return [];\n      }\n      return [\n        {\n          ...runtimeEventBase(event, canonicalThreadId),\n          type: \"user-input.requested\",\n          payload: {\n            questions,\n          },\n        },\n      ];\n    }\n\n    const detail = (() => {\n      switch (event.method) {\n        case \"item/commandExecution/requestApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__CommandExecutionRequestApprovalParams,\n            event.payload,\n          );\n          return payload?.command ?? payload?.reason ?? undefined;\n        }\n        case \"item/fileChange/requestApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__FileChangeRequestApprovalParams,\n            event.payload,\n          );\n          return payload?.reason ?? undefined;\n        }\n        case \"applyPatchApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__ApplyPatchApprovalParams,\n            event.payload,\n          );\n          return payload?.reason ?? undefined;\n        }\n        case \"execCommandApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__ExecCommandApprovalParams,\n            event.payload,\n          );\n          return payload?.reason ?? payload?.command.join(\" \");\n        }\n        case \"item/tool/call\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__DynamicToolCallParams,\n            event.payload,\n          );\n          return payload?.tool ?? undefined;\n        }\n        default:\n          return undefined;\n      }\n    })();\n\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"request.opened\",\n        payload: {\n          requestType: toRequestTypeFromMethod(event.method),\n          ...(detail ? { detail } : {}),\n          ...(event.payload !== undefined ? { args: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/requestApproval/decision\" && event.requestId) {\n    const payload = readPayload(ApprovalDecisionPayload, event.payload);\n    const requestType =\n      event.requestKind !== undefined\n        ? toRequestTypeFromKind(event.requestKind)\n        : toRequestTypeFromMethod(event.method);\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"request.resolved\",\n        payload: {\n          requestType,\n          ...(payload ? { decision: payload.decision } : {}),\n          ...(event.payload !== undefined ? { resolution: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/connecting\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.state.changed\",\n        payload: {\n          state: \"starting\",\n          ...(event.message ? { reason: event.message } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/ready\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.state.changed\",\n        payload: {\n          state: \"ready\",\n          ...(event.message ? { reason: event.message } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/started\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.started\",\n        payload: {\n          ...(event.message ? { message: event.message } : {}),\n          ...(event.payload !== undefined ? { resume: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/exited\" || event.method === \"session/closed\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.exited\",\n        payload: {\n          ...(event.message ? { reason: event.message } : {}),\n          ...(event.method === \"session/closed\" ? { exitKind: \"graceful\" } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/started\") {\n    const payload = readPayload(EffectCodexSchema.V2ThreadStartedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"thread.started\",\n        payload: {\n          providerThreadId: payload.thread.id,\n        },\n      },\n    ];\n  }\n\n  if (\n    event.method === \"thread/status/changed\" ||\n    event.method === \"thread/archived\" ||\n    event.method === \"thread/unarchived\" ||\n    event.method === \"thread/closed\" ||\n    event.method === \"thread/compacted\"\n  ) {\n    const payload =\n      event.method === \"thread/status/changed\"\n        ? readPayload(EffectCodexSchema.V2ThreadStatusChangedNotification, event.payload)\n        : undefined;\n    return [\n      {\n        type: \"thread.state.changed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          state:\n            event.method === \"thread/archived\"\n              ? \"archived\"\n              : event.method === \"thread/closed\"\n                ? \"closed\"\n                : event.method === \"thread/compacted\"\n                  ? \"compacted\"\n                  : payload\n                    ? toThreadState(payload.status)\n                    : \"active\",\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/name/updated\") {\n    const payload = readPayload(EffectCodexSchema.V2ThreadNameUpdatedNotification, event.payload);\n    return [\n      {\n        type: \"thread.metadata.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          ...(trimText(payload?.threadName) ? { name: trimText(payload?.threadName) } : {}),\n          ...(payload\n            ? {\n                metadata: {\n                  threadId: payload.threadId,\n                  ...(payload.threadName !== undefined && payload.threadName !== null\n                    ? { threadName: payload.threadName }\n                    : {}),\n                },\n              }\n            : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/tokenUsage/updated\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,\n      event.payload,\n    );\n    const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;\n    if (!normalizedUsage) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.token-usage.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          usage: normalizedUsage,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/started\") {\n    const turnId = event.turnId;\n    if (!turnId) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        turnId,\n        type: \"turn.started\",\n        payload: {},\n      },\n    ];\n  }\n\n  if (event.method === \"turn/completed\") {\n    const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    const errorMessage = trimText(payload.turn.error?.message);\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.completed\",\n        payload: {\n          state: toTurnStatus(payload.turn.status),\n          ...(errorMessage ? { errorMessage } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/aborted\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.aborted\",\n        payload: {\n          reason: event.message ?? \"Turn aborted\",\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/plan/updated\") {\n    const payload = readPayload(EffectCodexSchema.V2TurnPlanUpdatedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.plan.updated\",\n        payload: {\n          ...(trimText(payload.explanation) ? { explanation: trimText(payload.explanation) } : {}),\n          plan: payload.plan.map((step) => ({\n            step: trimText(step.step) ?? \"step\",\n            status:\n              step.status === \"completed\" || step.status === \"inProgress\" ? step.status : \"pending\",\n          })),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/diff/updated\") {\n    const payload = readPayload(EffectCodexSchema.V2TurnDiffUpdatedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.diff.updated\",\n        payload: {\n          unifiedDiff: payload.diff,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/started\") {\n    const started = mapItemLifecycle(event, canonicalThreadId, \"item.started\");\n    return started ? [started] : [];\n  }\n\n  if (event.method === \"item/completed\") {\n    const payload = readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);\n    const item = payload?.item;\n    if (!item) {\n      return [];\n    }\n    const itemType = toCanonicalItemType(item.type);\n    if (itemType === \"plan\") {\n      const detail = itemDetail(itemType, item);\n      if (!detail) {\n        return [];\n      }\n      return [\n        {\n          ...runtimeEventBase(event, canonicalThreadId),\n          type: \"turn.proposed.completed\",\n          payload: {\n            planMarkdown: detail,\n          },\n        },\n      ];\n    }\n    const completed = mapItemLifecycle(event, canonicalThreadId, \"item.completed\");\n    return completed ? [completed] : [];\n  }\n\n  if (\n    event.method === \"item/reasoning/summaryPartAdded\" ||\n    event.method === \"item/commandExecution/terminalInteraction\"\n  ) {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"item.updated\",\n        payload: {\n          itemType:\n            event.method === \"item/reasoning/summaryPartAdded\" ? \"reasoning\" : \"command_execution\",\n          ...(event.payload !== undefined ? { data: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/plan/delta\") {\n    const payload = readPayload(EffectCodexSchema.V2PlanDeltaNotification, event.payload);\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.proposed.delta\",\n        payload: {\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/agentMessage/delta\") {\n    const payload = readPayload(EffectCodexSchema.V2AgentMessageDeltaNotification, event.payload);\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: contentStreamKindFromMethod(event.method),\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/commandExecution/outputDelta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2CommandExecutionOutputDeltaNotification,\n      event.payload,\n    );\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"command_output\",\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/fileChange/outputDelta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2FileChangeOutputDeltaNotification,\n      event.payload,\n    );\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"file_change_output\",\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/reasoning/summaryTextDelta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ReasoningSummaryTextDeltaNotification,\n      event.payload,\n    );\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"reasoning_summary_text\",\n          delta,\n          ...(payload ? { summaryIndex: payload.summaryIndex } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/reasoning/textDelta\") {\n    const payload = readPayload(EffectCodexSchema.V2ReasoningTextDeltaNotification, event.payload);\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"reasoning_text\",\n          delta,\n          ...(payload ? { contentIndex: payload.contentIndex } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/mcpToolCall/progress\") {\n    const payload = readPayload(EffectCodexSchema.V2McpToolCallProgressNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"tool.progress\",\n        payload: {\n          summary: payload.message,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"serverRequest/resolved\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ServerRequestResolvedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    const requestType = toRequestTypeFromKind(event.requestKind);\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"request.resolved\",\n        payload: {\n          requestType,\n          ...(event.payload !== undefined ? { resolution: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/tool/requestUserInput/answered\") {\n    const payload = readPayload(EffectCodexSchema.ToolRequestUserInputResponse, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"user-input.resolved\",\n        payload: {\n          answers: toCanonicalUserInputAnswers(payload.answers),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"model/rerouted\") {\n    const payload = readPayload(EffectCodexSchema.V2ModelReroutedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"model.rerouted\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          fromModel: payload.fromModel,\n          toModel: payload.toModel,\n          reason: payload.reason,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"deprecationNotice\") {\n    const payload = readPayload(EffectCodexSchema.V2DeprecationNoticeNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"deprecation.notice\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          summary: payload.summary,\n          ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"configWarning\") {\n    const payload = readPayload(EffectCodexSchema.V2ConfigWarningNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"config.warning\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          summary: payload.summary,\n          ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),\n          ...(trimText(payload.path) ? { path: trimText(payload.path) } : {}),\n          ...(payload.range !== undefined && payload.range !== null\n            ? { range: payload.range }\n            : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"account/updated\") {\n    if (!readPayload(EffectCodexSchema.V2AccountUpdatedNotification, event.payload)) {\n      return [];\n    }\n    return [\n      {\n        type: \"account.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          account: event.payload ?? {},\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"account/rateLimits/updated\") {\n    if (!readPayload(EffectCodexSchema.V2AccountRateLimitsUpdatedNotification, event.payload)) {\n      return [];\n    }\n    return [\n      {\n        type: \"account.rate-limits.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          rateLimits: event.payload ?? {},\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"mcpServer/oauthLogin/completed\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2McpServerOauthLoginCompletedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"mcp.oauth.completed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          success: payload.success,\n          name: payload.name,\n          ...(trimText(payload.error) ? { error: trimText(payload.error) } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/started\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeStartedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.started\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          realtimeSessionId: payload.realtimeSessionId ?? undefined,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/itemAdded\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeItemAddedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.item-added\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          item: payload.item,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/transcript/delta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.transcript.delta\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          role: payload.role,\n          delta: payload.delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/transcript/done\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeTranscriptDoneNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.transcript.done\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          role: payload.role,\n          text: payload.text,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/outputAudio/delta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.audio.delta\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          audio: payload.audio,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/error\") {\n    const payload = readPayload(EffectCodexSchema.V2ThreadRealtimeErrorNotification, event.payload);\n    const message = payload?.message ?? event.message ?? \"Realtime error\";\n    return [\n      {\n        type: \"thread.realtime.error\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          message,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/closed\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeClosedNotification,\n      event.payload,\n    );\n    return [\n      {\n        type: \"thread.realtime.closed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          reason: payload?.reason ?? event.message,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"error\") {\n    const payload = readPayload(EffectCodexSchema.V2ErrorNotification, event.payload);\n    const message = payload?.error.message ?? event.message ?? \"Provider runtime error\";\n    const willRetry = payload?.willRetry === true;\n    return [\n      {\n        type: willRetry ? \"runtime.warning\" : \"runtime.error\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          message,\n          ...(!willRetry ? { class: \"provider_error\" as const } : {}),\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"process/stderr\") {\n    const message = event.message ?? \"Codex process stderr\";\n    const isFatal = isFatalCodexProcessStderrMessage(message);\n    return [\n      isFatal\n        ? {\n            type: \"runtime.error\",\n            ...runtimeEventBase(event, canonicalThreadId),\n            payload: {\n              message,\n              class: \"provider_error\" as const,\n              ...(event.payload !== undefined ? { detail: event.payload } : {}),\n            },\n          }\n        : {\n            type: \"runtime.warning\",\n            ...runtimeEventBase(event, canonicalThreadId),\n            payload: {\n              message,\n              ...(event.payload !== undefined ? { detail: event.payload } : {}),\n            },\n          },\n    ];\n  }\n\n  if (event.method === \"windows/worldWritableWarning\") {\n    if (!readPayload(EffectCodexSchema.V2WindowsWorldWritableWarningNotification, event.payload)) {\n      return [];\n    }\n    return [\n      {\n        type: \"runtime.warning\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          message: event.message ?? \"Windows world-writable warning\",\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"windowsSandbox/setupCompleted\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    const successMessage = event.message ?? \"Windows sandbox setup completed\";\n    const failureMessage = event.message ?? \"Windows sandbox setup failed\";\n\n    return [\n      {\n        type: \"session.state.changed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          state: payload.success === false ? \"error\" : \"ready\",\n          reason: payload.success === false ? failureMessage : successMessage,\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n      ...(payload.success === false\n        ? [\n            {\n              type: \"runtime.warning\" as const,\n              ...runtimeEventBase(event, canonicalThreadId),\n              payload: {\n                message: failureMessage,\n                ...(event.payload !== undefined ? { detail: event.payload } : {}),\n              },\n            },\n          ]\n        : []),\n    ];\n  }\n\n  return [];\n}\n\nfunction unixSecondsToIso(value: number | undefined, fallback: number): string {\n  return new Date((value ?? fallback) * 1_000).toISOString();\n}\n\nfunction summarizeCodexUserInput(\n  input: EffectCodexSchema.V2ThreadReadResponse__UserInput,\n): string {\n  switch (input.type) {\n    case \"text\":\n      return input.text;\n    case \"image\":\n    case \"localImage\":\n      return \"[Image input omitted]\";\n    case \"audio\":\n    case \"localAudio\":\n      return \"[Audio input omitted]\";\n    case \"skill\":\n      return `[Skill: ${input.name}]`;\n    case \"mention\":\n      return `[Mention: ${input.name}]`;\n  }\n}\n\n/** Converts a native `thread/read` snapshot through the same item mapper as live events. */\nexport function mapCodexThreadSnapshot(\n  canonicalThreadId: ThreadId,\n  providerInstanceId: ProviderInstanceId,\n  snapshot: CodexThreadSnapshot,\n): ProviderThreadSnapshot {\n  const makeEvent = (input: {\n    readonly method: \"turn/started\" | \"item/completed\" | \"turn/completed\";\n    readonly turn: CodexThreadSnapshot[\"turns\"][number];\n    readonly item?: CodexThreadSnapshot[\"turns\"][number][\"items\"][number];\n  }): ProviderEvent => {\n    const itemId = input.item ? ProviderItemId.make(input.item.id) : undefined;\n    const suffix = itemId ? `item:${itemId}:completed` : input.method.replace(\"/\", \":\");\n    const createdAt = unixSecondsToIso(\n      input.method === \"turn/started\" ? input.turn.startedAt : input.turn.completedAt,\n      input.method === \"turn/started\" ? snapshot.createdAt : snapshot.updatedAt,\n    );\n    const payload =\n      input.method === \"item/completed\" && input.item\n        ? {\n            completedAtMs: Date.parse(createdAt),\n            threadId: snapshot.threadId,\n            turnId: input.turn.id,\n            item: input.item,\n          }\n        : {\n            threadId: snapshot.threadId,\n            turn: input.turn,\n          };\n    return {\n      id: EventId.make(\n        `codex-snapshot:${snapshot.threadId}:turn:${input.turn.id}:${suffix}`,\n      ),\n      kind: \"notification\",\n      provider: PROVIDER,\n      providerInstanceId,\n      threadId: canonicalThreadId,\n      createdAt,\n      method: input.method,\n      turnId: input.turn.id,\n      ...(itemId ? { itemId } : {}),\n      payload,\n    };\n  };\n\n  return {\n    threadId: canonicalThreadId,\n    providerThreadId: snapshot.threadId,\n    status: snapshot.status.type,\n    activeFlags: snapshot.status.type === \"active\" ? snapshot.status.activeFlags : [],\n    turns: snapshot.turns.map((turn) => {\n      const terminal = turn.status !== \"inProgress\";\n      const nativeEvents = [\n        makeEvent({ method: \"turn/started\", turn }),\n        ...(terminal\n          ? turn.items.map((item) => makeEvent({ method: \"item/completed\", turn, item }))\n          : []),\n        ...(terminal ? [makeEvent({ method: \"turn/completed\", turn })] : []),\n      ];\n      const userMessages = turn.items.flatMap((item) => {\n        if (item.type !== \"userMessage\") return [];\n        const text = item.content\n          .map(summarizeCodexUserInput)\n          .filter((part) => part.trim().length > 0)\n          .join(\"\\n\");\n        return [\n          {\n            id: ProviderItemId.make(item.id),\n            text: text.length > 0 ? text : \"[Empty user message]\",\n          },\n        ];\n      });\n      return {\n        id: turn.id,\n        status: turn.status,\n        ...(turn.startedAt !== undefined\n          ? { startedAt: unixSecondsToIso(turn.startedAt, snapshot.createdAt) }\n          : {}),\n        ...(turn.completedAt !== undefined\n          ? { completedAt: unixSecondsToIso(turn.completedAt, snapshot.updatedAt) }\n          : {}),\n        items: turn.items,\n        userMessages,\n        runtimeEvents: nativeEvents.flatMap((event) =>\n          mapToRuntimeEvents(event, canonicalThreadId),\n        ),\n      };\n    }),\n  };\n}\n\n/**\n * Build a Codex provider adapter bound to a specific `CodexSettings` payload.\n *\n * The adapter is a captured closure over `codexConfig` — the `binaryPath` and\n * `homePath` are read from that payload, not from `ServerSettingsService`.\n * This is what makes multi-instance routing possible: each `ProviderInstance`\n * in the registry owns its own closure with its own config, so two Codex\n * instances with different `homePath`s cannot step on each other.\n */\nexport const makeCodexAdapter = Effect.fn(\"makeCodexAdapter\")(function* (\n  codexConfig: CodexSettings,\n  options?: CodexAdapterLiveOptions,\n) {\n  const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"codex\");\n  const fileSystem = yield* FileSystem.FileSystem;\n  const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const crypto = yield* Crypto.Crypto;\n  const serverConfig = yield* Effect.service(ServerConfig);\n  const nativeEventLogger =\n    options?.nativeEventLogger ??\n    (options?.nativeEventLogPath !== undefined\n      ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n          stream: \"native\",\n        })\n      : undefined);\n  const managedNativeEventLogger =\n    options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n  const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();\n  const sessions = new Map<ThreadId, CodexAdapterSessionContext>();\n  const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime;\n  const toRuntimeInput = (\n    input: Parameters<CodexAdapterShape[\"startSession\"]>[0],\n  ): CodexSessionRuntimeOptions => {\n    const serviceTier =\n      input.modelSelection?.instanceId === boundInstanceId\n        ? getCodexServiceTierOptionValue(input.modelSelection)\n        : undefined;\n    return {\n      threadId: input.threadId,\n      providerInstanceId: boundInstanceId,\n      cwd: input.cwd ?? process.cwd(),\n      binaryPath: codexConfig.binaryPath,\n      launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),\n      ...(options?.environment ? { environment: options.environment } : {}),\n      ...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),\n      ...(isCodexResumeCursorSchema(input.resumeCursor) ? { resumeCursor: input.resumeCursor } : {}),\n      runtimeMode: input.runtimeMode,\n      ...(input.modelSelection?.instanceId === boundInstanceId\n        ? { model: input.modelSelection.model }\n        : {}),\n      ...(serviceTier ? { serviceTier } : {}),\n    };\n  };\n\n  const startSession: CodexAdapterShape[\"startSession\"] = (input) =>\n    Effect.scoped(\n      Effect.gen(function* () {\n        if (input.provider !== undefined && input.provider !== PROVIDER) {\n          return yield* new ProviderAdapterValidationError({\n            provider: PROVIDER,\n            operation: \"startSession\",\n            issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n          });\n        }\n\n        const existing = sessions.get(input.threadId);\n        if (existing && !existing.stopped) {\n          yield* Effect.suspend(() => stopSessionInternal(existing));\n        }\n\n        const runtimeInput = toRuntimeInput(input);\n        const sessionScope = yield* Scope.make(\"sequential\");\n        let sessionScopeTransferred = false;\n        yield* Effect.addFinalizer(() =>\n          sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),\n        );\n        const runtime = yield* createRuntime(runtimeInput).pipe(\n          Effect.provideService(Scope.Scope, sessionScope),\n          Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),\n          Effect.provideService(Crypto.Crypto, crypto),\n          Effect.mapError(\n            (cause) =>\n              new ProviderAdapterProcessError({\n                provider: PROVIDER,\n                threadId: input.threadId,\n                detail: cause.message,\n                cause,\n              }),\n          ),\n        );\n\n        const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>\n          Effect.gen(function* () {\n            yield* writeNativeEvent(event);\n            const runtimeEvents = mapToRuntimeEvents(event, event.threadId);\n            if (runtimeEvents.length === 0) {\n              yield* Effect.logDebug(\"ignoring unhandled Codex provider event\", {\n                method: event.method,\n                threadId: event.threadId,\n                turnId: event.turnId,\n                itemId: event.itemId,\n              });\n              return;\n            }\n            yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);\n          }),\n        ).pipe(Effect.forkIn(sessionScope));\n\n        const started = yield* runtime.start().pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderAdapterProcessError({\n                provider: PROVIDER,\n                threadId: input.threadId,\n                detail: cause.message,\n                cause,\n              }),\n          ),\n          Effect.onError(() =>\n            runtime.close.pipe(\n              Effect.andThen(Effect.ignore(Scope.close(sessionScope, Exit.void))),\n              Effect.andThen(Fiber.interrupt(eventFiber)),\n              Effect.ignore,\n            ),\n          ),\n        );\n\n        sessions.set(input.threadId, {\n          threadId: input.threadId,\n          scope: sessionScope,\n          runtime,\n          eventFiber,\n          stopped: false,\n        });\n        sessionScopeTransferred = true;\n\n        return started;\n      }),\n    );\n\n  const resolveAttachment = Effect.fn(\"resolveAttachment\")(function* (\n    input: ProviderSendTurnInput,\n    attachment: NonNullable<ProviderSendTurnInput[\"attachments\"]>[number],\n  ) {\n    const attachmentPath = resolveAttachmentPath({\n      attachmentsDir: serverConfig.attachmentsDir,\n      attachment,\n    });\n    if (!attachmentPath) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"turn/start\",\n        detail: `Invalid attachment id '${attachment.id}'.`,\n      });\n    }\n    const bytes = yield* fileSystem.readFile(attachmentPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"turn/start\",\n            detail: `Failed to read attachment file: ${cause.message}.`,\n            cause,\n          }),\n      ),\n    );\n    return {\n      type: \"image\" as const,\n      url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString(\"base64\")}`,\n    };\n  });\n\n  const sendTurn: CodexAdapterShape[\"sendTurn\"] = Effect.fn(\"sendTurn\")(function* (input) {\n    const codexAttachments = yield* Effect.forEach(\n      input.attachments ?? [],\n      (attachment) => resolveAttachment(input, attachment),\n      { concurrency: 1 },\n    );\n\n    const session = yield* requireSession(input.threadId);\n    const reasoningEffort =\n      input.modelSelection?.instanceId === boundInstanceId\n        ? getModelSelectionStringOptionValue(input.modelSelection, \"reasoningEffort\")\n        : undefined;\n    const serviceTier =\n      input.modelSelection?.instanceId === boundInstanceId\n        ? getCodexServiceTierOptionValue(input.modelSelection)\n        : undefined;\n    return yield* session.runtime\n      .sendTurn({\n        ...(input.input !== undefined ? { input: input.input } : {}),\n        ...(input.modelSelection?.instanceId === boundInstanceId\n          ? { model: input.modelSelection.model }\n          : {}),\n        ...(reasoningEffort\n          ? {\n              effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,\n            }\n          : {}),\n        ...(serviceTier ? { serviceTier } : {}),\n        ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),\n        ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),\n      })\n      .pipe(Effect.mapError((cause) => mapCodexRuntimeError(input.threadId, \"turn/start\", cause)));\n  });\n\n  const requireSession = Effect.fn(\"requireSession\")(function* (threadId: ThreadId) {\n    const session = sessions.get(threadId);\n    if (!session || session.stopped) {\n      return yield* new ProviderAdapterSessionNotFoundError({\n        provider: PROVIDER,\n        threadId,\n      });\n    }\n    return session;\n  });\n\n  const interruptTurn: CodexAdapterShape[\"interruptTurn\"] = (threadId, turnId) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.interruptTurn(turnId)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"turn/interrupt\", cause),\n      ),\n    );\n\n  const startRealtimeVoiceInput = (threadId: ThreadId) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.startRealtimeVoiceInput()),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"thread/realtime/start\", cause),\n      ),\n    );\n\n  const appendRealtimeVoiceAudio = (\n    threadId: ThreadId,\n    audio: Parameters<NonNullable<CodexAdapterShape[\"realtimeVoiceInput\"]>[\"appendAudio\"]>[1],\n  ) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.appendRealtimeVoiceAudio(audio)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"thread/realtime/appendAudio\", cause),\n      ),\n    );\n\n  const stopRealtimeVoiceInput = (threadId: ThreadId) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.stopRealtimeVoiceInput()),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"thread/realtime/stop\", cause),\n      ),\n    );\n\n  const readThread: CodexAdapterShape[\"readThread\"] = (input) => {\n    const active = sessions.get(input.threadId);\n    const readSnapshot =\n      active && !active.stopped\n        ? active.runtime.readThread.pipe(\n            Effect.mapError((cause) => mapCodexRuntimeError(input.threadId, \"thread/read\", cause)),\n          )\n        : Effect.scoped(\n            Effect.gen(function* () {\n              const runtime = yield* createRuntime(toRuntimeInput(input)).pipe(\n                Effect.provideService(\n                  ChildProcessSpawner.ChildProcessSpawner,\n                  childProcessSpawner,\n                ),\n                Effect.provideService(Crypto.Crypto, crypto),\n                Effect.mapError(\n                  (cause) =>\n                    new ProviderAdapterProcessError({\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      detail: cause.message,\n                      cause,\n                    }),\n                ),\n              );\n              return yield* runtime.readThread.pipe(\n                Effect.mapError((cause) =>\n                  mapCodexRuntimeError(input.threadId, \"thread/read\", cause),\n                ),\n              );\n            }),\n          );\n\n    return readSnapshot.pipe(\n      Effect.map((snapshot) =>\n        mapCodexThreadSnapshot(input.threadId, boundInstanceId, snapshot),\n      ),\n    );\n  };\n\n  const rollbackThread: CodexAdapterShape[\"rollbackThread\"] = (threadId, numTurns) => {\n    if (!Number.isInteger(numTurns) || numTurns < 1) {\n      return Effect.fail(\n        new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"rollbackThread\",\n          issue: \"numTurns must be an integer >= 1.\",\n        }),\n      );\n    }\n\n    return requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"thread/rollback\", cause),\n      ),\n      Effect.map((snapshot) => mapCodexThreadSnapshot(threadId, boundInstanceId, snapshot)),\n    );\n  };\n\n  const respondToRequest: CodexAdapterShape[\"respondToRequest\"] = (threadId, requestId, decision) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.respondToRequest(requestId, decision)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"item/requestApproval/decision\", cause),\n      ),\n    );\n\n  const respondToUserInput: CodexAdapterShape[\"respondToUserInput\"] = (\n    threadId,\n    requestId,\n    answers,\n  ) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.respondToUserInput(requestId, answers)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"item/tool/requestUserInput\", cause),\n      ),\n    );\n\n  const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {\n    if (!nativeEventLogger) {\n      return;\n    }\n    yield* nativeEventLogger.write(event, event.threadId);\n  });\n\n  const stopSessionInternal = Effect.fn(\"stopSessionInternal\")(function* (\n    session: CodexAdapterSessionContext,\n  ) {\n    if (session.stopped) {\n      return;\n    }\n    session.stopped = true;\n    sessions.delete(session.threadId);\n    yield* session.runtime.close.pipe(Effect.ignore);\n    yield* Effect.ignore(Scope.close(session.scope, Exit.void));\n    yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore);\n  });\n\n  const stopSession: CodexAdapterShape[\"stopSession\"] = (threadId) =>\n    Effect.gen(function* () {\n      const session = sessions.get(threadId);\n      if (!session) {\n        return;\n      }\n      yield* stopSessionInternal(session);\n    });\n\n  const listSessions: CodexAdapterShape[\"listSessions\"] = () =>\n    Effect.forEach(\n      Array.from(sessions.values()).filter((session) => !session.stopped),\n      (session) => session.runtime.getSession,\n      { concurrency: 1 },\n    );\n\n  const hasSession: CodexAdapterShape[\"hasSession\"] = (threadId) =>\n    Effect.succeed(Boolean(sessions.get(threadId) && !sessions.get(threadId)?.stopped));\n\n  const stopAll: CodexAdapterShape[\"stopAll\"] = () =>\n    Effect.forEach(Array.from(sessions.values()), stopSessionInternal, {\n      concurrency: 1,\n      discard: true,\n    }).pipe(Effect.asVoid);\n\n  yield* Effect.acquireRelease(Effect.void, () =>\n    stopAll().pipe(\n      Effect.andThen(Queue.shutdown(runtimeEventQueue)),\n      Effect.andThen(managedNativeEventLogger?.close() ?? Effect.void),\n      Effect.ignore,\n    ),\n  );\n\n  return {\n    provider: PROVIDER,\n    capabilities: {\n      sessionModelSwitch: \"in-session\",\n      realtimeVoiceInput: true,\n    },\n    startSession,\n    sendTurn,\n    interruptTurn,\n    realtimeVoiceInput: {\n      start: startRealtimeVoiceInput,\n      appendAudio: appendRealtimeVoiceAudio,\n      stop: stopRealtimeVoiceInput,\n    },\n    readThread,\n    rollbackThread,\n    respondToRequest,\n    respondToUserInput,\n    stopSession,\n    listSessions,\n    hasSession,\n    stopAll,\n    get streamEvents() {\n      return Stream.fromQueue(runtimeEventQueue);\n    },\n  } satisfies CodexAdapterShape;\n});\n\n// NOTE: the old `CodexAdapterLive` / `makeCodexAdapterLive` singleton Layer\n// exports have been removed as part of the per-instance-driver refactor.\n// `makeCodexAdapter(codexConfig, options?)` is now invoked directly by\n// `CodexDriver.create()` for each configured instance; downstream consumers\n// (server bootstrap, integration harness, this module's tests) will be\n// migrated to the registry in a follow-up pass.\n","import * as NodeOS from \"node:os\";\n\nimport { ProviderDriverKind, type CodexSettings } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as PlatformError from \"effect/PlatformError\";\n\nimport { expandHomePath } from \"../../pathExpansion.ts\";\n\nexport interface CodexHomeLayout {\n  readonly mode: \"direct\" | \"authOverlay\";\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string | undefined;\n  readonly continuationKey: string;\n}\n\nconst KNOWN_SHARED_DIRECTORIES = [\n  \"sessions\",\n  \"archived_sessions\",\n  \"sqlite\",\n  \"shell_snapshots\",\n  \"worktrees\",\n  \"skills\",\n  \"plugins\",\n  \"cache\",\n  \"logs\",\n  \"mcp-oauth-locks\",\n] as const;\n\nconst PRIVATE_ENTRY_NAMES = new Set([\"auth.json\", \"models_cache.json\"]);\nconst SHADOW_LOCAL_ENTRY_NAMES = new Set([\"log\", \"memories\", \"tmp\"]);\nconst REPLACEABLE_SHARED_RUNTIME_DIRECTORIES = new Set([\"mcp-oauth-locks\"]);\n\nfunction resolveHomePath(path: Path.Path, value: string | undefined): string {\n  const expanded =\n    value && value.trim().length > 0\n      ? expandHomePath(value)\n      : path.join(NodeOS.homedir(), \".codex\");\n  return path.resolve(expanded);\n}\n\nexport const resolveCodexHomeLayout = Effect.fn(\"resolveCodexHomeLayout\")(function* (\n  config: CodexSettings,\n): Effect.fn.Return<CodexHomeLayout, never, Path.Path> {\n  const path = yield* Path.Path;\n  const sharedHomePath = resolveHomePath(path, config.homePath);\n  const shadowHomePath = config.shadowHomePath.trim();\n  if (shadowHomePath.length === 0) {\n    return {\n      mode: \"direct\",\n      sharedHomePath,\n      effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined,\n      continuationKey: `codex:home:${sharedHomePath}`,\n    };\n  }\n\n  const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath));\n  return {\n    mode: \"authOverlay\",\n    sharedHomePath,\n    effectiveHomePath,\n    continuationKey: `codex:home:${sharedHomePath}`,\n  };\n});\n\nconst CodexShadowHomeContext = {\n  sharedHomePath: Schema.String,\n  effectiveHomePath: Schema.String,\n};\n\nexport class CodexShadowHomeFileSystemError extends Schema.TaggedErrorClass<CodexShadowHomeFileSystemError>()(\n  \"CodexShadowHomeFileSystemError\",\n  {\n    ...CodexShadowHomeContext,\n    operation: Schema.Literals([\"readLink\", \"makeDirectory\", \"readDirectory\", \"remove\", \"symlink\"]),\n    path: Schema.String,\n    targetPath: Schema.optional(Schema.String),\n    entryName: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const target = this.targetPath === undefined ? \"\" : ` to '${this.targetPath}'`;\n    return `Codex shadow home filesystem operation '${this.operation}' failed for '${this.path}'${target}.`;\n  }\n}\n\nexport class CodexShadowHomePathConflictError extends Schema.TaggedErrorClass<CodexShadowHomePathConflictError>()(\n  \"CodexShadowHomePathConflictError\",\n  CodexShadowHomeContext,\n) {\n  override get message(): string {\n    return `Codex shadow home path '${this.effectiveHomePath}' must be different from the shared home path '${this.sharedHomePath}'.`;\n  }\n}\n\nexport class CodexShadowHomeEntryConflictError extends Schema.TaggedErrorClass<CodexShadowHomeEntryConflictError>()(\n  \"CodexShadowHomeEntryConflictError\",\n  {\n    ...CodexShadowHomeContext,\n    entryName: Schema.String,\n    linkPath: Schema.String,\n    targetPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Cannot create Codex shadow home entry '${this.entryName}' because '${this.linkPath}' already exists and is not a symlink.`;\n  }\n}\n\nexport class CodexShadowHomePrivateEntrySymlinkError extends Schema.TaggedErrorClass<CodexShadowHomePrivateEntrySymlinkError>()(\n  \"CodexShadowHomePrivateEntrySymlinkError\",\n  {\n    ...CodexShadowHomeContext,\n    entryName: Schema.String,\n    path: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Codex shadow home private entry '${this.entryName}' at '${this.path}' must be a real file, not a symlink.`;\n  }\n}\n\nexport const CodexShadowHomeError = Schema.Union([\n  CodexShadowHomeFileSystemError,\n  CodexShadowHomePathConflictError,\n  CodexShadowHomeEntryConflictError,\n  CodexShadowHomePrivateEntrySymlinkError,\n]);\nexport type CodexShadowHomeError = typeof CodexShadowHomeError.Type;\n\ntype LinkState =\n  | {\n      readonly _tag: \"Missing\";\n    }\n  | {\n      readonly _tag: \"NotSymlink\";\n    }\n  | {\n      readonly _tag: \"Symlink\";\n      readonly target: string;\n    };\n\nfunction isNotSymlinkError(error: PlatformError.PlatformError): boolean {\n  const cause = error.reason.cause;\n  return (\n    error.reason._tag === \"Unknown\" &&\n    typeof cause === \"object\" &&\n    cause !== null &&\n    \"code\" in cause &&\n    cause.code === \"EINVAL\"\n  );\n}\n\nconst readLinkState = Effect.fn(\"CodexHomeLayout.readLinkState\")(function* (input: {\n  readonly fileSystem: FileSystem.FileSystem;\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string;\n  readonly entryName: string;\n  readonly linkPath: string;\n}): Effect.fn.Return<LinkState, CodexShadowHomeError> {\n  return yield* input.fileSystem.readLink(input.linkPath).pipe(\n    Effect.map((target): LinkState => ({ _tag: \"Symlink\", target })),\n    Effect.catchTags({\n      PlatformError: (cause) => {\n        if (cause.reason._tag === \"NotFound\") {\n          return Effect.succeed<LinkState>({ _tag: \"Missing\" });\n        }\n        if (isNotSymlinkError(cause)) {\n          return Effect.succeed<LinkState>({ _tag: \"NotSymlink\" });\n        }\n        return new CodexShadowHomeFileSystemError({\n          sharedHomePath: input.sharedHomePath,\n          effectiveHomePath: input.effectiveHomePath,\n          operation: \"readLink\",\n          path: input.linkPath,\n          entryName: input.entryName,\n          cause,\n        });\n      },\n    }),\n  );\n});\n\nconst removePrivateSymlink = Effect.fn(\"CodexHomeLayout.removePrivateSymlink\")(function* (input: {\n  readonly fileSystem: FileSystem.FileSystem;\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string;\n  readonly entryName: string;\n}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n  const path = yield* Path.Path;\n  const privatePath = path.join(input.effectiveHomePath, input.entryName);\n  const state = yield* readLinkState({\n    ...input,\n    linkPath: privatePath,\n  });\n  if (state._tag === \"Symlink\") {\n    yield* input.fileSystem.remove(privatePath).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: input.sharedHomePath,\n            effectiveHomePath: input.effectiveHomePath,\n            operation: \"remove\",\n            path: privatePath,\n            entryName: input.entryName,\n            cause,\n          }),\n      }),\n    );\n  }\n});\n\nconst ensureSymlink = Effect.fn(\"CodexHomeLayout.ensureSymlink\")(function* (input: {\n  readonly fileSystem: FileSystem.FileSystem;\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string;\n  readonly entryName: string;\n}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n  const path = yield* Path.Path;\n  const target = path.join(input.sharedHomePath, input.entryName);\n  const link = path.join(input.effectiveHomePath, input.entryName);\n  const state = yield* readLinkState({\n    ...input,\n    linkPath: link,\n  });\n\n  const createLink = input.fileSystem.symlink(target, link).pipe(\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        new CodexShadowHomeFileSystemError({\n          sharedHomePath: input.sharedHomePath,\n          effectiveHomePath: input.effectiveHomePath,\n          operation: \"symlink\",\n          path: link,\n          targetPath: target,\n          entryName: input.entryName,\n          cause,\n        }),\n    }),\n  );\n\n  if (state._tag === \"NotSymlink\") {\n    if (!REPLACEABLE_SHARED_RUNTIME_DIRECTORIES.has(input.entryName)) {\n      return yield* new CodexShadowHomeEntryConflictError({\n        sharedHomePath: input.sharedHomePath,\n        effectiveHomePath: input.effectiveHomePath,\n        entryName: input.entryName,\n        linkPath: link,\n        targetPath: target,\n      });\n    }\n\n    yield* input.fileSystem.remove(link, { recursive: true }).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: input.sharedHomePath,\n            effectiveHomePath: input.effectiveHomePath,\n            operation: \"remove\",\n            path: link,\n            entryName: input.entryName,\n            cause,\n          }),\n      }),\n    );\n    return yield* createLink;\n  }\n\n  if (state._tag === \"Missing\") {\n    return yield* createLink;\n  }\n\n  const resolvedExisting = path.resolve(path.dirname(link), state.target);\n  if (resolvedExisting !== target) {\n    yield* input.fileSystem.remove(link).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: input.sharedHomePath,\n            effectiveHomePath: input.effectiveHomePath,\n            operation: \"remove\",\n            path: link,\n            entryName: input.entryName,\n            cause,\n          }),\n      }),\n    );\n    yield* createLink;\n  }\n});\n\nconst ensureShadowAuthIsPrivate = Effect.fn(\"CodexHomeLayout.ensureShadowAuthIsPrivate\")(\n  function* (input: {\n    readonly fileSystem: FileSystem.FileSystem;\n    readonly sharedHomePath: string;\n    readonly effectiveHomePath: string;\n  }): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n    const path = yield* Path.Path;\n    const entryName = \"auth.json\";\n    const authPath = path.join(input.effectiveHomePath, entryName);\n    const state = yield* readLinkState({\n      ...input,\n      entryName,\n      linkPath: authPath,\n    });\n    if (state._tag === \"Symlink\") {\n      return yield* new CodexShadowHomePrivateEntrySymlinkError({\n        sharedHomePath: input.sharedHomePath,\n        effectiveHomePath: input.effectiveHomePath,\n        entryName,\n        path: authPath,\n      });\n    }\n  },\n);\n\nexport const materializeCodexShadowHome = Effect.fn(\"materializeCodexShadowHome\")(function* (\n  layout: CodexHomeLayout,\n) {\n  if (layout.mode !== \"authOverlay\") return;\n  const effectiveHomePath = layout.effectiveHomePath;\n  if (!effectiveHomePath) return;\n  if (layout.sharedHomePath === effectiveHomePath) {\n    return yield* new CodexShadowHomePathConflictError({\n      sharedHomePath: layout.sharedHomePath,\n      effectiveHomePath,\n    });\n  }\n\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const makeDirectory = (directoryPath: string) =>\n    fileSystem.makeDirectory(directoryPath, { recursive: true }).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: layout.sharedHomePath,\n            effectiveHomePath,\n            operation: \"makeDirectory\",\n            path: directoryPath,\n            cause,\n          }),\n      }),\n    );\n\n  yield* Effect.all(\n    [\n      makeDirectory(layout.sharedHomePath),\n      makeDirectory(effectiveHomePath),\n      ...KNOWN_SHARED_DIRECTORIES.map((directory) =>\n        makeDirectory(path.join(layout.sharedHomePath, directory)),\n      ),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n\n  const sharedEntryNames = yield* fileSystem.readDirectory(layout.sharedHomePath).pipe(\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        new CodexShadowHomeFileSystemError({\n          sharedHomePath: layout.sharedHomePath,\n          effectiveHomePath,\n          operation: \"readDirectory\",\n          path: layout.sharedHomePath,\n          cause,\n        }),\n    }),\n  );\n  const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);\n  for (const entryName of sharedEntryNames) {\n    if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {\n      entries.add(entryName);\n    }\n  }\n\n  yield* Effect.forEach(\n    PRIVATE_ENTRY_NAMES,\n    (entryName) =>\n      entryName === \"auth.json\"\n        ? Effect.void\n        : removePrivateSymlink({\n            fileSystem,\n            sharedHomePath: layout.sharedHomePath,\n            effectiveHomePath,\n            entryName,\n          }),\n    { discard: true },\n  );\n\n  yield* Effect.forEach(\n    entries,\n    (entryName) => {\n      if (PRIVATE_ENTRY_NAMES.has(entryName)) {\n        return Effect.void;\n      }\n      return ensureSymlink({\n        fileSystem,\n        sharedHomePath: layout.sharedHomePath,\n        effectiveHomePath,\n        entryName,\n      });\n    },\n    { discard: true },\n  );\n\n  yield* ensureShadowAuthIsPrivate({\n    fileSystem,\n    sharedHomePath: layout.sharedHomePath,\n    effectiveHomePath,\n  });\n});\n\nexport function codexContinuationIdentity(layout: CodexHomeLayout) {\n  return {\n    driverKind: ProviderDriverKind.make(\"codex\"),\n    continuationKey: layout.continuationKey,\n  };\n}\n","/**\n * CodexDriver — first concrete `ProviderDriver` in the new per-instance model.\n *\n * A driver is a plain value (not a Context.Service) whose `create()` returns\n * one `ProviderInstance` bundling:\n *   - `snapshot`   — the live `ServerProviderShape` for this instance;\n *   - `adapter`    — the Codex session/turn/approval runtime;\n *   - `textGeneration` — commit/PR/branch/title generation via `codex exec`.\n *\n * Each call to `create()` captures the `codexConfig` argument in closures\n * owned by the returned instance. Two instances created with different\n * `homePath`s (e.g. `codex_personal` + `codex_work`) therefore run with\n * fully independent Codex app-server processes and `CODEX_HOME`\n * environments — no shared mutable state.\n *\n * Resource lifecycle: `create()` runs in a scope handed in by the registry.\n * Closing that scope releases the adapter's child processes, the managed\n * snapshot's refresh fibre, and the text-generation binaries' transient\n * scratch files. The registry uses this to tear down an instance when its\n * `providerInstances` entry disappears or its config changes.\n *\n * @module provider/Drivers/CodexDriver\n */\nimport { CodexSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { makeCodexTextGeneration } from \"../../textGeneration/CodexTextGeneration.ts\";\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeCodexAdapter } from \"../Layers/CodexAdapter.ts\";\nimport { checkCodexProviderStatus, makePendingCodexProvider } from \"../Layers/CodexProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport type { ProviderDriver, ProviderInstance } from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  makePackageManagedProviderMaintenanceResolver,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nimport {\n  codexContinuationIdentity,\n  materializeCodexShadowHome,\n  resolveCodexHomeLayout,\n} from \"./CodexHomeLayout.ts\";\nconst decodeCodexSettings = Schema.decodeSync(CodexSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"codex\");\nconst UPDATE = makePackageManagedProviderMaintenanceResolver({\n  provider: DRIVER_KIND,\n  npmPackageName: \"@openai/codex\",\n  homebrewFormula: \"codex\",\n  nativeUpdate: null,\n});\n\n/**\n * Services the driver needs to materialize an instance. Surfaced as the\n * driver's `R` so the registry layer aggregates these across every\n * registered driver and the runtime satisfies them once.\n */\nexport type CodexDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\n/**\n * Stamp instance identity onto a `ServerProvider` snapshot produced by the\n * driver-kind-only codex helpers. Once `buildServerProvider` in\n * `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this\n * wrapper disappears.\n */\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"Codex\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: CodexSettings,\n  defaultConfig: (): CodexSettings => decodeCodexSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const homeLayout = yield* resolveCodexHomeLayout(config);\n      const continuationIdentity = codexContinuationIdentity(homeLayout);\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey: continuationIdentity.continuationKey,\n      });\n      yield* materializeCodexShadowHome(homeLayout).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: cause.message,\n              cause,\n            }),\n        ),\n      );\n      const effectiveConfig = {\n        ...config,\n        enabled,\n        homePath: homeLayout.effectiveHomePath ?? \"\",\n      } satisfies CodexSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n\n      // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error\n      // channels at construction time — their failure modes are all on the\n      // per-operation closures they return. No `mapError` wrapper is needed\n      // here; the registry only has to worry about snapshot-build and\n      // spawner-availability failures surfaced from `checkCodexProviderStatus`\n      // below.\n      const adapter = yield* makeCodexAdapter(effectiveConfig, {\n        instanceId,\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n      });\n      const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);\n\n      // Build a managed snapshot whose settings never change — mutations come\n      // in as instance rebuilds from the registry rather than in-place\n      // updates. Pre-provide `ChildProcessSpawner` so the check fits\n      // `makeManagedServerProvider.checkProvider`'s `R = never`.\n      const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(\n        Effect.map(stampIdentity),\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n      );\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({\n        maintenanceCapabilities,\n        getSettings: snapshotSettings.getSettings,\n        streamSettings: snapshotSettings.streamSettings,\n        haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n        initialSnapshot: (settings) =>\n          makePendingCodexProvider(settings.provider).pipe(Effect.map(stampIdentity)),\n        checkProvider,\n        enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>\n          enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {\n            enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n          }).pipe(\n            Effect.provideService(HttpClient.HttpClient, httpClient),\n            Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),\n          ),\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity,\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","/**\n * GeminiAcpAgent — descriptor for Google's Gemini CLI (`gemini`,\n * `@google/gemini-cli`). `gemini --experimental-acp` starts it as an ACP\n * agent over stdio. Gemini CLI does not advertise ACP `loadSession`, so\n * resume cursors are ignored and every session starts fresh.\n *\n * @module provider/acp/GeminiAcpAgent\n */\nimport { ProviderDriverKind } from \"@t3tools/contracts\";\n\nimport type { AcpAgentDescriptor } from \"./AcpAgentSupport.ts\";\n\nexport const GeminiAcpAgent: AcpAgentDescriptor = {\n  provider: ProviderDriverKind.make(\"gemini\"),\n  displayName: \"Gemini CLI\",\n  defaultBinary: \"gemini\",\n  acpArgs: [\"--experimental-acp\"],\n  defaultModel: \"gemini-2.5-pro\",\n  builtInModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n  supportsSessionLoad: false,\n};\n","// This file is generated by the effect-acp package. Do not edit manually.\n// Current ACP schema release: v0.11.3\n\nimport * as Schema from \"effect/Schema\";\n\nexport type AuthEnvVar = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly label?: string | null;\n  readonly name: string;\n  readonly optional?: boolean;\n  readonly secret?: boolean;\n};\nexport const AuthEnvVar = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  label: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Human-readable label for this variable, displayed in client UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({\n    description: 'The environment variable name (e.g. `\"OPENAI_API_KEY\"`).',\n  }),\n  optional: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether this variable is optional.\\n\\nDefaults to `false`.\",\n      default: false,\n    }),\n  ),\n  secret: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this value is a secret (e.g. API key, token).\\nClients should use a password-style input for secret vars.\\n\\nDefaults to `true`.\",\n      default: true,\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nDescribes a single environment variable for an [`AuthMethodEnvVar`] authentication method.\",\n});\n\nexport type AvailableCommandInput = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly hint: string;\n};\nexport const AvailableCommandInput = Schema.Union([\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    hint: Schema.String.annotate({\n      description: \"A hint to display when the input hasn't been provided yet\",\n    }),\n  }).annotate({\n    title: \"unstructured\",\n    description: \"All text that was typed after the command name is provided as input.\",\n  }),\n]).annotate({ description: \"The input specification for a command.\" });\n\nexport type Cost = { readonly amount: number; readonly currency: string };\nexport const Cost = Schema.Struct({\n  amount: Schema.Number.annotate({\n    description: \"Total cumulative cost for session.\",\n    format: \"double\",\n  }).check(Schema.isFinite()),\n  currency: Schema.String.annotate({ description: 'ISO 4217 currency code (e.g., \"USD\", \"EUR\").' }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCost information for a session.\",\n});\n\nexport type ElicitationContentValue = string | number | number | boolean | ReadonlyArray<string>;\nexport const ElicitationContentValue = Schema.Union([\n  Schema.String.annotate({ title: \"String\" }),\n  Schema.Number.annotate({ title: \"Integer\", format: \"int64\" }).check(Schema.isInt()),\n  Schema.Number.annotate({ title: \"Number\", format: \"double\" }).check(Schema.isFinite()),\n  Schema.Boolean.annotate({ title: \"Boolean\" }),\n  Schema.Array(Schema.String).annotate({ title: \"StringArray\" }),\n]);\n\nexport type ElicitationFormCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const ElicitationFormCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nForm-based elicitation capabilities.\",\n});\n\nexport type ElicitationUrlCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const ElicitationUrlCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nURL-based elicitation capabilities.\",\n});\n\nexport type EmbeddedResourceResource =\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly mimeType?: string | null;\n      readonly text: string;\n      readonly uri: string;\n    }\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly blob: string;\n      readonly mimeType?: string | null;\n      readonly uri: string;\n    };\nexport const EmbeddedResourceResource = Schema.Union([\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    text: Schema.String,\n    uri: Schema.String,\n  }).annotate({ title: \"TextResourceContents\", description: \"Text-based resource contents.\" }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    blob: Schema.String,\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    uri: Schema.String,\n  }).annotate({ title: \"BlobResourceContents\", description: \"Binary resource contents.\" }),\n]).annotate({ description: \"Resource content that can be embedded in a message.\" });\n\nexport type EnumOption = { readonly const: string; readonly title: string };\nexport const EnumOption = Schema.Struct({\n  const: Schema.String.annotate({ description: \"The constant value for this option.\" }),\n  title: Schema.String.annotate({ description: \"Human-readable title for this option.\" }),\n}).annotate({ description: \"A titled enum option with a const value and human-readable title.\" });\n\nexport type EnvVariable = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly name: string;\n  readonly value: string;\n};\nexport const EnvVariable = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({ description: \"The name of the environment variable.\" }),\n  value: Schema.String.annotate({ description: \"The value to set for the environment variable.\" }),\n}).annotate({ description: \"An environment variable to set when launching an MCP server.\" });\n\nexport type Error = {\n  readonly code:\n    | -32700\n    | -32600\n    | -32601\n    | -32602\n    | -32603\n    | -32800\n    | -32000\n    | -32002\n    | -32042\n    | number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const Error = Schema.Struct({\n  code: Schema.Union([\n    Schema.Literal(-32700).annotate({\n      title: \"Parse error\",\n      description:\n        \"**Parse error**: Invalid JSON was received by the server.\\nAn error occurred on the server while parsing the JSON text.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32600).annotate({\n      title: \"Invalid request\",\n      description: \"**Invalid request**: The JSON sent is not a valid Request object.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32601).annotate({\n      title: \"Method not found\",\n      description: \"**Method not found**: The method does not exist or is not available.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32602).annotate({\n      title: \"Invalid params\",\n      description: \"**Invalid params**: Invalid method parameter(s).\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32603).annotate({\n      title: \"Internal error\",\n      description:\n        \"**Internal error**: Internal JSON-RPC error.\\nReserved for implementation-defined server errors.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32800).annotate({\n      title: \"Request cancelled\",\n      description:\n        \"**Request cancelled**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nExecution of the method was aborted either due to a cancellation request from the caller or\\nbecause of resource constraints or shutdown.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32000).annotate({\n      title: \"Authentication required\",\n      description:\n        \"**Authentication required**: Authentication is required before this operation can be performed.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32002).annotate({\n      title: \"Resource not found\",\n      description: \"**Resource not found**: A given resource, such as a file, was not found.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32042).annotate({\n      title: \"URL elicitation required\",\n      description:\n        \"**URL elicitation required**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe agent requires user input via a URL-based elicitation before it can proceed.\",\n      format: \"int32\",\n    }),\n    Schema.Number.annotate({\n      title: \"Other\",\n      description: \"Other undefined error code.\",\n      format: \"int32\",\n    }).check(Schema.isInt()),\n  ]).annotate({\n    description:\n      \"Predefined error codes for common JSON-RPC and ACP-specific errors.\\n\\nThese codes follow the JSON-RPC 2.0 specification for standard errors\\nand use the reserved range (-32000 to -32099) for protocol-specific errors.\",\n  }),\n  data: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Optional primitive or structured value that contains additional information about the error.\\nThis may include debugging information or context-specific details.\",\n    }),\n  ),\n  message: Schema.String.annotate({\n    description:\n      \"A string providing a short description of the error.\\nThe message should be limited to a concise single sentence.\",\n  }),\n}).annotate({\n  description:\n    \"JSON-RPC error object.\\n\\nRepresents an error that occurred during method execution, following the\\nJSON-RPC 2.0 error object specification with optional additional data.\\n\\nSee protocol docs: [JSON-RPC Error Object](https://www.jsonrpc.org/specification#error_object)\",\n});\n\nexport type HttpHeader = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly name: string;\n  readonly value: string;\n};\nexport const HttpHeader = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({ description: \"The name of the HTTP header.\" }),\n  value: Schema.String.annotate({ description: \"The value to set for the HTTP header.\" }),\n}).annotate({ description: \"An HTTP header to set when making requests to the MCP server.\" });\n\nexport type Implementation = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n};\nexport const Implementation = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({\n    description:\n      \"Intended for programmatic or logical use, but can be used as a display\\nname fallback if title isn’t present.\",\n  }),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Intended for UI and end-user contexts — optimized to be human-readable\\nand easily understood.\\n\\nIf not provided, the name should be used for display.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  version: Schema.String.annotate({\n    description:\n      'Version of the implementation. Can be displayed to the user or used\\nfor debugging or metrics purposes. (e.g. \"1.0.0\").',\n  }),\n}).annotate({\n  description:\n    \"Metadata about the implementation of the client or agent.\\nDescribes the name and version of an MCP implementation, with an optional\\ntitle for UI representation.\",\n});\n\nexport type LogoutCapabilities = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const LogoutCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nLogout capabilities supported by the agent.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n});\n\nexport type ModelInfo = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly modelId: string;\n  readonly name: string;\n};\nexport const ModelInfo = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional description of the model.\" }),\n      Schema.Null,\n    ]),\n  ),\n  modelId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name of the model.\" }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInformation about a selectable model.\",\n});\n\nexport type PermissionOption = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly kind: \"allow_once\" | \"allow_always\" | \"reject_once\" | \"reject_always\";\n  readonly name: string;\n  readonly optionId: string;\n};\nexport const PermissionOption = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  kind: Schema.Literals([\"allow_once\", \"allow_always\", \"reject_once\", \"reject_always\"]).annotate({\n    description:\n      \"The type of permission option being presented to the user.\\n\\nHelps clients choose appropriate icons and UI treatment.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable label to display to the user.\" }),\n  optionId: Schema.String.annotate({ description: \"Unique identifier for a permission option.\" }),\n}).annotate({ description: \"An option presented to the user when requesting permission.\" });\n\nexport type PlanEntry = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content: string;\n  readonly priority: \"high\" | \"medium\" | \"low\";\n  readonly status: \"pending\" | \"in_progress\" | \"completed\";\n};\nexport const PlanEntry = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.String.annotate({\n    description: \"Human-readable description of what this task aims to accomplish.\",\n  }),\n  priority: Schema.Literals([\"high\", \"medium\", \"low\"]).annotate({\n    description:\n      \"Priority levels for plan entries.\\n\\nUsed to indicate the relative importance or urgency of different\\ntasks in the execution plan.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n  }),\n  status: Schema.Literals([\"pending\", \"in_progress\", \"completed\"]).annotate({\n    description:\n      \"Status of a plan entry in the execution flow.\\n\\nTracks the lifecycle of each task from planning through completion.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n  }),\n}).annotate({\n  description:\n    \"A single entry in the execution plan.\\n\\nRepresents a task or goal that the assistant intends to accomplish\\nas part of fulfilling the user's request.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n});\n\nexport type RequestId = null | number | string;\nexport const RequestId = Schema.Union([\n  Schema.Null.annotate({ title: \"Null\" }),\n  Schema.Number.annotate({ title: \"Number\", format: \"int64\" }).check(Schema.isInt()),\n  Schema.String.annotate({ title: \"Str\" }),\n]).annotate({\n  description:\n    \"JSON RPC Request Id\\n\\nAn identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null [1] and Numbers SHOULD NOT contain fractional parts [2]\\n\\nThe Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.\\n\\n[1] The use of Null as a value for the id member in a Request object is discouraged, because this specification uses a value of Null for Responses with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null for Notifications this could cause confusion in handling.\\n\\n[2] Fractional parts may be problematic, since many decimal fractions cannot be represented exactly as binary fractions.\",\n});\n\nexport type Role = \"assistant\" | \"user\";\nexport const Role = Schema.Literals([\"assistant\", \"user\"]).annotate({\n  description: \"The sender or recipient of messages and data in a conversation.\",\n});\n\nexport type SessionCloseCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const SessionCloseCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCapabilities for the `session/close` method.\\n\\nBy supplying `{}` it means that the agent supports closing of sessions.\",\n});\n\nexport type SessionConfigOptionCategory = \"mode\" | \"model\" | \"thought_level\" | string;\nexport const SessionConfigOptionCategory = Schema.Union([\n  Schema.Literal(\"mode\").annotate({ description: \"Session mode selector.\" }),\n  Schema.Literal(\"model\").annotate({ description: \"Model selector.\" }),\n  Schema.Literal(\"thought_level\").annotate({ description: \"Thought/reasoning level selector.\" }),\n  Schema.String.annotate({ title: \"other\", description: \"Unknown / uncategorized selector.\" }),\n]).annotate({\n  description:\n    \"Semantic category for a session configuration option.\\n\\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\\ncategories gracefully.\\n\\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\\nCategory names that do not begin with `_` are reserved for the ACP spec.\",\n});\n\nexport type SessionConfigSelectOption = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly name: string;\n  readonly value: string;\n};\nexport const SessionConfigSelectOption = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional description for this option value.\" }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({ description: \"Human-readable label for this option value.\" }),\n  value: Schema.String.annotate({\n    description: \"Unique identifier for a session configuration option value.\",\n  }),\n}).annotate({ description: \"A possible value for a session configuration option.\" });\n\nexport type SessionForkCapabilities = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SessionForkCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCapabilities for the `session/fork` method.\\n\\nBy supplying `{}` it means that the agent supports forking of sessions.\",\n});\n\nexport type SessionInfo = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly sessionId: string;\n  readonly title?: string | null;\n  readonly updatedAt?: string | null;\n};\nexport const SessionInfo = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({\n    description: \"The working directory for this session. Must be an absolute path.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable title for the session\" }),\n      Schema.Null,\n    ]),\n  ),\n  updatedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"ISO 8601 timestamp of last activity\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Information about a session returned by session/list\" });\n\nexport type SessionListCapabilities = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SessionListCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Capabilities for the `session/list` method.\\n\\nBy supplying `{}` it means that the agent supports listing of sessions.\",\n});\n\nexport type SessionModeId = string;\nexport const SessionModeId = Schema.String.annotate({\n  description: \"Unique identifier for a Session Mode.\",\n});\n\nexport type SessionResumeCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const SessionResumeCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCapabilities for the `session/resume` method.\\n\\nBy supplying `{}` it means that the agent supports resuming of sessions.\",\n});\n\nexport type StringFormat = \"email\" | \"uri\" | \"date\" | \"date-time\";\nexport const StringFormat = Schema.Literals([\"email\", \"uri\", \"date\", \"date-time\"]).annotate({\n  description: \"String format types for string properties in elicitation schemas.\",\n});\n\nexport type TerminalExitStatus = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly exitCode?: number | null;\n  readonly signal?: string | null;\n};\nexport const TerminalExitStatus = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  exitCode: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"The process exit code (may be null if terminated by signal).\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  signal: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"The signal that terminated the process (may be null if exited normally).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Exit status of a terminal command.\" });\n\nexport type ToolCallLocation = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly line?: number | null;\n  readonly path: string;\n};\nexport const ToolCallLocation = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  line: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional line number within the file.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({ description: \"The file path being accessed or modified.\" }),\n}).annotate({\n  description:\n    'A file location being accessed or modified by a tool.\\n\\nEnables clients to implement \"follow-along\" features that track\\nwhich files the agent is working with in real-time.\\n\\nSee protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/tool-calls#following-the-agent)',\n});\n\nexport type ToolCallStatus = \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\nexport const ToolCallStatus = Schema.Literals([\n  \"pending\",\n  \"in_progress\",\n  \"completed\",\n  \"failed\",\n]).annotate({\n  description:\n    \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n});\n\nexport type ToolKind =\n  | \"read\"\n  | \"edit\"\n  | \"delete\"\n  | \"move\"\n  | \"search\"\n  | \"execute\"\n  | \"think\"\n  | \"fetch\"\n  | \"switch_mode\"\n  | \"other\";\nexport const ToolKind = Schema.Literals([\n  \"read\",\n  \"edit\",\n  \"delete\",\n  \"move\",\n  \"search\",\n  \"execute\",\n  \"think\",\n  \"fetch\",\n  \"switch_mode\",\n  \"other\",\n]).annotate({\n  description:\n    \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n});\n\nexport type Usage = {\n  readonly cachedReadTokens?: number | null;\n  readonly cachedWriteTokens?: number | null;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly thoughtTokens?: number | null;\n  readonly totalTokens: number;\n};\nexport const Usage = Schema.Struct({\n  cachedReadTokens: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Total cache read tokens.\", format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  cachedWriteTokens: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Total cache write tokens.\", format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  inputTokens: Schema.Number.annotate({\n    description: \"Total input tokens across all turns.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  outputTokens: Schema.Number.annotate({\n    description: \"Total output tokens across all turns.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  thoughtTokens: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Total thought/reasoning tokens\", format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  totalTokens: Schema.Number.annotate({\n    description: \"Sum of all token types across session.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nToken usage information for a prompt turn.\",\n});\n\nexport type AuthMethod =\n  | {\n      readonly type: \"env_var\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly link?: string | null;\n      readonly name: string;\n      readonly vars: ReadonlyArray<AuthEnvVar>;\n    }\n  | {\n      readonly type: \"terminal\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly args?: ReadonlyArray<string>;\n      readonly description?: string | null;\n      readonly env?: { readonly [x: string]: string };\n      readonly id: string;\n      readonly name: string;\n    }\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly name: string;\n    };\nexport const AuthMethod = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"env_var\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional description providing more details about this authentication method.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for this authentication method.\",\n    }),\n    link: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional link to a page where the user can obtain their credentials.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    name: Schema.String.annotate({\n      description: \"Human-readable name of the authentication method.\",\n    }),\n    vars: Schema.Array(AuthEnvVar).annotate({\n      description: \"The environment variables the client should set.\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nEnvironment variable authentication method.\\n\\nThe user provides credentials that the client passes to the agent as environment variables.\",\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"terminal\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    args: Schema.optionalKey(\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Additional arguments to pass when running the agent binary for terminal auth.\",\n      }),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional description providing more details about this authentication method.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    env: Schema.optionalKey(\n      Schema.Record(Schema.String, Schema.String).annotate({\n        description:\n          \"Additional environment variables to set when running the agent binary for terminal auth.\",\n      }),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for this authentication method.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name of the authentication method.\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nTerminal-based authentication method.\\n\\nThe client runs an interactive terminal for the user to authenticate via a TUI.\",\n  }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional description providing more details about this authentication method.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for this authentication method.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name of the authentication method.\",\n    }),\n  }).annotate({\n    title: \"agent\",\n    description:\n      \"Agent handles authentication itself.\\n\\nThis is the default authentication method type.\",\n  }),\n]).annotate({\n  description:\n    \"Describes an available authentication method.\\n\\nThe `type` field acts as the discriminator in the serialized JSON form.\\nWhen no `type` is present, the method is treated as `agent`.\",\n});\n\nexport type AvailableCommand = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description: string;\n  readonly input?: AvailableCommandInput | null;\n  readonly name: string;\n};\nexport const AvailableCommand = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String.annotate({\n    description: \"Human-readable description of what the command does.\",\n  }),\n  input: Schema.optionalKey(\n    Schema.Union([AvailableCommandInput, Schema.Null]).annotate({\n      description: \"Input for the command if required\",\n    }),\n  ),\n  name: Schema.String.annotate({\n    description: \"Command name (e.g., `create_plan`, `research_codebase`).\",\n  }),\n}).annotate({ description: \"Information about a command.\" });\n\nexport type ElicitationCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly form?: ElicitationFormCapabilities | null;\n  readonly url?: ElicitationUrlCapabilities | null;\n};\nexport const ElicitationCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  form: Schema.optionalKey(\n    Schema.Union([ElicitationFormCapabilities, Schema.Null]).annotate({\n      description: \"Whether the client supports form-based elicitation.\",\n    }),\n  ),\n  url: Schema.optionalKey(\n    Schema.Union([ElicitationUrlCapabilities, Schema.Null]).annotate({\n      description: \"Whether the client supports URL-based elicitation.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\",\n});\n\nexport type McpServer =\n  | {\n      readonly type: \"http\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly headers: ReadonlyArray<HttpHeader>;\n      readonly name: string;\n      readonly url: string;\n    }\n  | {\n      readonly type: \"sse\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly headers: ReadonlyArray<HttpHeader>;\n      readonly name: string;\n      readonly url: string;\n    }\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly args: ReadonlyArray<string>;\n      readonly command: string;\n      readonly env: ReadonlyArray<EnvVariable>;\n      readonly name: string;\n    };\nexport const McpServer = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"http\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    headers: Schema.Array(HttpHeader).annotate({\n      description: \"HTTP headers to set when making requests to the MCP server.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name identifying this MCP server.\",\n    }),\n    url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n  }).annotate({ description: \"HTTP transport configuration for MCP.\" }),\n  Schema.Struct({\n    type: Schema.Literal(\"sse\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    headers: Schema.Array(HttpHeader).annotate({\n      description: \"HTTP headers to set when making requests to the MCP server.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name identifying this MCP server.\",\n    }),\n    url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n  }).annotate({ description: \"SSE transport configuration for MCP.\" }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    args: Schema.Array(Schema.String).annotate({\n      description: \"Command-line arguments to pass to the MCP server.\",\n    }),\n    command: Schema.String.annotate({ description: \"Path to the MCP server executable.\" }),\n    env: Schema.Array(EnvVariable).annotate({\n      description: \"Environment variables to set when launching the MCP server.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name identifying this MCP server.\",\n    }),\n  }).annotate({ title: \"stdio\", description: \"Stdio transport configuration for MCP.\" }),\n]).annotate({\n  description:\n    \"Configuration for connecting to an MCP (Model Context Protocol) server.\\n\\nMCP servers provide tools and context that the agent can use when\\nprocessing prompts.\\n\\nSee protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/session-setup#mcp-servers)\",\n});\n\nexport type SessionModelState = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly availableModels: ReadonlyArray<ModelInfo>;\n  readonly currentModelId: string;\n};\nexport const SessionModelState = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  availableModels: Schema.Array(ModelInfo).annotate({\n    description: \"The set of models that the Agent can use\",\n  }),\n  currentModelId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe set of models and the one currently active.\",\n});\n\nexport type Annotations = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly audience?: ReadonlyArray<Role> | null;\n  readonly lastModified?: string | null;\n  readonly priority?: number | null;\n};\nexport const Annotations = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  audience: Schema.optionalKey(Schema.Union([Schema.Array(Role), Schema.Null])),\n  lastModified: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  priority: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Optional annotations for the client. The client can use annotations to inform how objects are used or displayed\",\n});\n\nexport type SessionConfigSelectGroup = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly group: string;\n  readonly name: string;\n  readonly options: ReadonlyArray<SessionConfigSelectOption>;\n};\nexport const SessionConfigSelectGroup = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  group: Schema.String.annotate({\n    description: \"Unique identifier for a session configuration option value group.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable label for this group.\" }),\n  options: Schema.Array(SessionConfigSelectOption).annotate({\n    description: \"The set of option values in this group.\",\n  }),\n}).annotate({ description: \"A group of possible values for a session configuration option.\" });\n\nexport type SessionMode = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly id: SessionModeId;\n  readonly name: string;\n};\nexport const SessionMode = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: SessionModeId,\n  name: Schema.String,\n}).annotate({\n  description:\n    \"A mode the agent can operate in.\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n});\n\nexport type ElicitationPropertySchema =\n  | {\n      readonly type: \"string\";\n      readonly default?: string | null;\n      readonly description?: string | null;\n      readonly enum?: ReadonlyArray<string> | null;\n      readonly format?: StringFormat | null;\n      readonly maxLength?: number | null;\n      readonly minLength?: number | null;\n      readonly oneOf?: ReadonlyArray<EnumOption> | null;\n      readonly pattern?: string | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"number\";\n      readonly default?: number | null;\n      readonly description?: string | null;\n      readonly maximum?: number | null;\n      readonly minimum?: number | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"integer\";\n      readonly default?: number | null;\n      readonly description?: string | null;\n      readonly maximum?: number | null;\n      readonly minimum?: number | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"boolean\";\n      readonly default?: boolean | null;\n      readonly description?: string | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"array\";\n      readonly default?: ReadonlyArray<string> | null;\n      readonly description?: string | null;\n      readonly items:\n        | { readonly enum: ReadonlyArray<string>; readonly type: \"string\" }\n        | { readonly anyOf: ReadonlyArray<EnumOption> };\n      readonly maxItems?: number | null;\n      readonly minItems?: number | null;\n      readonly title?: string | null;\n    };\nexport const ElicitationPropertySchema = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"string\"),\n      default: Schema.optionalKey(\n        Schema.Union([Schema.String.annotate({ description: \"Default value.\" }), Schema.Null]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      enum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.String).annotate({\n            description: \"Enum values for untitled single-select enums.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      format: Schema.optionalKey(\n        Schema.Union([StringFormat, Schema.Null]).annotate({ description: \"String format.\" }),\n      ),\n      maxLength: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Maximum string length.\", format: \"uint32\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      minLength: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Minimum string length.\", format: \"uint32\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      oneOf: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(EnumOption).annotate({\n            description: \"Titled enum options for titled single-select enums.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pattern: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Pattern the string must match.\" }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description:\n        'Schema for string properties in an elicitation form.\\n\\nWhen `enum` or `oneOf` is set, this represents a single-select enum\\nwith `\"type\": \"string\"`.',\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"number\"),\n      default: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Default value.\", format: \"double\" }).check(\n            Schema.isFinite(),\n          ),\n          Schema.Null,\n        ]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      maximum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Maximum value (inclusive).\",\n            format: \"double\",\n          }).check(Schema.isFinite()),\n          Schema.Null,\n        ]),\n      ),\n      minimum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Minimum value (inclusive).\",\n            format: \"double\",\n          }).check(Schema.isFinite()),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description: \"Schema for number (floating-point) properties in an elicitation form.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"integer\"),\n      default: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Default value.\", format: \"int64\" }).check(\n            Schema.isInt(),\n          ),\n          Schema.Null,\n        ]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      maximum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Maximum value (inclusive).\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      minimum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Minimum value (inclusive).\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"Schema for integer properties in an elicitation form.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"boolean\"),\n      default: Schema.optionalKey(\n        Schema.Union([Schema.Boolean.annotate({ description: \"Default value.\" }), Schema.Null]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"Schema for boolean properties in an elicitation form.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"array\"),\n      default: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.String).annotate({ description: \"Default selected values.\" }),\n          Schema.Null,\n        ]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      items: Schema.Union([\n        Schema.Struct({\n          enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n          type: Schema.Literal(\"string\").annotate({\n            description: \"Items definition for untitled multi-select enum properties.\",\n          }),\n        }).annotate({\n          title: \"Untitled\",\n          description: \"Items definition for untitled multi-select enum properties.\",\n        }),\n        Schema.Struct({\n          anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n        }).annotate({\n          title: \"Titled\",\n          description: \"Items definition for titled multi-select enum properties.\",\n        }),\n      ]).annotate({ description: \"Items for a multi-select (array) property schema.\" }),\n      maxItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Maximum number of items to select.\",\n            format: \"uint64\",\n          })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      minItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Minimum number of items to select.\",\n            format: \"uint64\",\n          })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description: \"Schema for multi-select (array) properties in an elicitation form.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    'Property schema for elicitation form fields.\\n\\nEach variant corresponds to a JSON Schema `\"type\"` value.\\nSingle-select enums use the `String` variant with `enum` or `oneOf` set.\\nMulti-select enums use the `Array` variant.',\n});\n\nexport type ContentBlock =\n  | {\n      readonly type: \"text\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly text: string;\n    }\n  | {\n      readonly type: \"image\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly data: string;\n      readonly mimeType: string;\n      readonly uri?: string | null;\n    }\n  | {\n      readonly type: \"audio\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly data: string;\n      readonly mimeType: string;\n    }\n  | {\n      readonly type: \"resource_link\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly description?: string | null;\n      readonly mimeType?: string | null;\n      readonly name: string;\n      readonly size?: number | null;\n      readonly title?: string | null;\n      readonly uri: string;\n    }\n  | {\n      readonly type: \"resource\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly resource: EmbeddedResourceResource;\n    };\nexport const ContentBlock = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"text\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      text: Schema.String,\n    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"image\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      data: Schema.String,\n      mimeType: Schema.String,\n      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      data: Schema.String,\n      mimeType: Schema.String,\n    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"resource_link\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      name: Schema.String,\n      size: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      uri: Schema.String,\n    }).annotate({\n      description:\n        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"resource\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      resource: EmbeddedResourceResource,\n    }).annotate({\n      description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n});\n\nexport type ToolCallContent =\n  | {\n      readonly type: \"content\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n    }\n  | {\n      readonly type: \"diff\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly newText: string;\n      readonly oldText?: string | null;\n      readonly path: string;\n    }\n  | {\n      readonly type: \"terminal\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly terminalId: string;\n    };\nexport const ToolCallContent = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"content\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n    }).annotate({ description: \"Standard content block (text, images, resources).\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"diff\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      newText: Schema.String.annotate({ description: \"The new content after modification.\" }),\n      oldText: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"The original content (None for new files).\" }),\n          Schema.Null,\n        ]),\n      ),\n      path: Schema.String.annotate({ description: \"The file path being modified.\" }),\n    }).annotate({\n      description:\n        \"A diff representing file modifications.\\n\\nShows changes to files in a format suitable for display in the client UI.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"terminal\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      terminalId: Schema.String,\n    }).annotate({\n      description:\n        \"Embed a terminal created with `terminal/create` by its id.\\n\\nThe terminal must be added before calling `terminal/release`.\\n\\nSee protocol docs: [Terminal](https://agentclientprotocol.com/protocol/terminals)\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Content produced by a tool call.\\n\\nTool calls can produce different types of content including\\nstandard content blocks (text, images) or file diffs.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\",\n});\n\nexport type SessionConfigOption =\n  | {\n      readonly type: \"select\";\n      readonly currentValue: string;\n      readonly options:\n        | ReadonlyArray<SessionConfigSelectOption>\n        | ReadonlyArray<SessionConfigSelectGroup>;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly category?: SessionConfigOptionCategory | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly name: string;\n    }\n  | {\n      readonly type: \"boolean\";\n      readonly currentValue: boolean;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly category?: SessionConfigOptionCategory | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly name: string;\n    };\nexport const SessionConfigOption = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"select\"),\n    currentValue: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option value.\",\n    }),\n    options: Schema.Union([\n      Schema.Array(SessionConfigSelectOption).annotate({\n        title: \"Ungrouped\",\n        description: \"A flat list of options with no grouping.\",\n      }),\n      Schema.Array(SessionConfigSelectGroup).annotate({\n        title: \"Grouped\",\n        description: \"A list of options grouped under headers.\",\n      }),\n    ]).annotate({ description: \"Possible values for a session configuration option.\" }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    category: Schema.optionalKey(\n      Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({\n        description: \"Optional semantic category for this option (UX only).\",\n      }),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional description for the Client to display to the user.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    name: Schema.String.annotate({ description: \"Human-readable label for the option.\" }),\n  }).annotate({ description: \"A session configuration option selector and its current state.\" }),\n  Schema.Struct({\n    type: Schema.Literal(\"boolean\"),\n    currentValue: Schema.Boolean.annotate({\n      description: \"The current value of the boolean option.\",\n    }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    category: Schema.optionalKey(\n      Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({\n        description: \"Optional semantic category for this option (UX only).\",\n      }),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional description for the Client to display to the user.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    name: Schema.String.annotate({ description: \"Human-readable label for the option.\" }),\n  }).annotate({ description: \"A session configuration option selector and its current state.\" }),\n]);\n\nexport type SessionModeState = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly availableModes: ReadonlyArray<SessionMode>;\n  readonly currentModeId: string;\n};\nexport const SessionModeState = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  availableModes: Schema.Array(SessionMode).annotate({\n    description: \"The set of modes that the Agent can operate in\",\n  }),\n  currentModeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n}).annotate({ description: \"The set of modes and the one currently active.\" });\n\nexport type AgentAuthCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly logout?: LogoutCapabilities | null;\n};\nexport const AgentAuthCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  logout: Schema.optionalKey(\n    Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n      description:\n        \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n});\n\nexport type AgentCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly auth?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly logout?: LogoutCapabilities | null;\n  };\n  readonly loadSession?: boolean;\n  readonly mcpCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly http?: boolean;\n    readonly sse?: boolean;\n  };\n  readonly promptCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly audio?: boolean;\n    readonly embeddedContext?: boolean;\n    readonly image?: boolean;\n  };\n  readonly sessionCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly close?: SessionCloseCapabilities | null;\n    readonly fork?: SessionForkCapabilities | null;\n    readonly list?: SessionListCapabilities | null;\n    readonly resume?: SessionResumeCapabilities | null;\n  };\n};\nexport const AgentCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  auth: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      logout: Schema.optionalKey(\n        Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n          description:\n            \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n        }),\n      ),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n      default: {},\n    }),\n  ),\n  loadSession: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the agent supports `session/load`.\",\n      default: false,\n    }),\n  ),\n  mcpCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      http: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`McpServer::Http`].\",\n          default: false,\n        }),\n      ),\n      sse: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`McpServer::Sse`].\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description: \"MCP capabilities supported by the agent\",\n      default: { http: false, sse: false },\n    }),\n  ),\n  promptCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      audio: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`ContentBlock::Audio`].\",\n          default: false,\n        }),\n      ),\n      embeddedContext: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description:\n            \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n          default: false,\n        }),\n      ),\n      image: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`ContentBlock::Image`].\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n      default: { audio: false, embeddedContext: false, image: false },\n    }),\n  ),\n  sessionCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      close: Schema.optionalKey(\n        Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n        }),\n      ),\n      fork: Schema.optionalKey(\n        Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n        }),\n      ),\n      list: Schema.optionalKey(\n        Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n          description: \"Whether the agent supports `session/list`.\",\n        }),\n      ),\n      resume: Schema.optionalKey(\n        Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n        }),\n      ),\n    }).annotate({\n      default: {},\n      description:\n        \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Capabilities supported by the agent.\\n\\nAdvertised during initialization to inform the client about\\navailable features and content types.\\n\\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)\",\n});\n\nexport type AgentNotification = {\n  readonly method: string;\n  readonly params?:\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly update:\n          | {\n              readonly sessionUpdate: \"user_message_chunk\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content:\n                | {\n                    readonly type: \"text\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly text: string;\n                  }\n                | {\n                    readonly type: \"image\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                    readonly uri?: string | null;\n                  }\n                | {\n                    readonly type: \"audio\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                  }\n                | {\n                    readonly type: \"resource_link\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly description?: string | null;\n                    readonly mimeType?: string | null;\n                    readonly name: string;\n                    readonly size?: number | null;\n                    readonly title?: string | null;\n                    readonly uri: string;\n                  }\n                | {\n                    readonly type: \"resource\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly resource: EmbeddedResourceResource;\n                  };\n              readonly messageId?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"agent_message_chunk\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content:\n                | {\n                    readonly type: \"text\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly text: string;\n                  }\n                | {\n                    readonly type: \"image\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                    readonly uri?: string | null;\n                  }\n                | {\n                    readonly type: \"audio\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                  }\n                | {\n                    readonly type: \"resource_link\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly description?: string | null;\n                    readonly mimeType?: string | null;\n                    readonly name: string;\n                    readonly size?: number | null;\n                    readonly title?: string | null;\n                    readonly uri: string;\n                  }\n                | {\n                    readonly type: \"resource\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly resource: EmbeddedResourceResource;\n                  };\n              readonly messageId?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"agent_thought_chunk\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content:\n                | {\n                    readonly type: \"text\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly text: string;\n                  }\n                | {\n                    readonly type: \"image\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                    readonly uri?: string | null;\n                  }\n                | {\n                    readonly type: \"audio\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                  }\n                | {\n                    readonly type: \"resource_link\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly description?: string | null;\n                    readonly mimeType?: string | null;\n                    readonly name: string;\n                    readonly size?: number | null;\n                    readonly title?: string | null;\n                    readonly uri: string;\n                  }\n                | {\n                    readonly type: \"resource\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly resource: EmbeddedResourceResource;\n                  };\n              readonly messageId?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"tool_call\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content?: ReadonlyArray<ToolCallContent>;\n              readonly kind?:\n                | \"read\"\n                | \"edit\"\n                | \"delete\"\n                | \"move\"\n                | \"search\"\n                | \"execute\"\n                | \"think\"\n                | \"fetch\"\n                | \"switch_mode\"\n                | \"other\";\n              readonly locations?: ReadonlyArray<ToolCallLocation>;\n              readonly rawInput?: unknown;\n              readonly rawOutput?: unknown;\n              readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n              readonly title: string;\n              readonly toolCallId: string;\n            }\n          | {\n              readonly sessionUpdate: \"tool_call_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content?: ReadonlyArray<ToolCallContent> | null;\n              readonly kind?: ToolKind | null;\n              readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n              readonly rawInput?: unknown;\n              readonly rawOutput?: unknown;\n              readonly status?: ToolCallStatus | null;\n              readonly title?: string | null;\n              readonly toolCallId: string;\n            }\n          | {\n              readonly sessionUpdate: \"plan\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly entries: ReadonlyArray<PlanEntry>;\n            }\n          | {\n              readonly sessionUpdate: \"available_commands_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly availableCommands: ReadonlyArray<AvailableCommand>;\n            }\n          | {\n              readonly sessionUpdate: \"current_mode_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly currentModeId: string;\n            }\n          | {\n              readonly sessionUpdate: \"config_option_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly configOptions: ReadonlyArray<SessionConfigOption>;\n            }\n          | {\n              readonly sessionUpdate: \"session_info_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly title?: string | null;\n              readonly updatedAt?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"usage_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly cost?: Cost | null;\n              readonly size: number;\n              readonly used: number;\n            };\n      }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly elicitationId: string }\n    | unknown\n    | null;\n};\nexport const AgentNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          update: Schema.Union(\n            [\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"user_message_chunk\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.Union(\n                  [\n                    Schema.Struct({\n                      type: Schema.Literal(\"text\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      text: Schema.String,\n                    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"image\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"audio\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource_link\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      name: Schema.String,\n                      size: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                          Schema.Null,\n                        ]),\n                      ),\n                      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      uri: Schema.String,\n                    }).annotate({\n                      description:\n                        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n                    }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      resource: EmbeddedResourceResource,\n                    }).annotate({\n                      description:\n                        \"The contents of a resource, embedded into a prompt or tool call result.\",\n                    }),\n                  ],\n                  { mode: \"oneOf\" },\n                ).annotate({\n                  description:\n                    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n                }),\n                messageId: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description:\n                        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({ description: \"A streamed item of content\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"agent_message_chunk\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.Union(\n                  [\n                    Schema.Struct({\n                      type: Schema.Literal(\"text\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      text: Schema.String,\n                    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"image\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"audio\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource_link\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      name: Schema.String,\n                      size: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                          Schema.Null,\n                        ]),\n                      ),\n                      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      uri: Schema.String,\n                    }).annotate({\n                      description:\n                        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n                    }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      resource: EmbeddedResourceResource,\n                    }).annotate({\n                      description:\n                        \"The contents of a resource, embedded into a prompt or tool call result.\",\n                    }),\n                  ],\n                  { mode: \"oneOf\" },\n                ).annotate({\n                  description:\n                    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n                }),\n                messageId: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description:\n                        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({ description: \"A streamed item of content\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"agent_thought_chunk\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.Union(\n                  [\n                    Schema.Struct({\n                      type: Schema.Literal(\"text\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      text: Schema.String,\n                    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"image\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"audio\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource_link\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      name: Schema.String,\n                      size: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                          Schema.Null,\n                        ]),\n                      ),\n                      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      uri: Schema.String,\n                    }).annotate({\n                      description:\n                        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n                    }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      resource: EmbeddedResourceResource,\n                    }).annotate({\n                      description:\n                        \"The contents of a resource, embedded into a prompt or tool call result.\",\n                    }),\n                  ],\n                  { mode: \"oneOf\" },\n                ).annotate({\n                  description:\n                    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n                }),\n                messageId: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description:\n                        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({ description: \"A streamed item of content\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"tool_call\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.optionalKey(\n                  Schema.Array(ToolCallContent).annotate({\n                    description: \"Content produced by the tool call.\",\n                  }),\n                ),\n                kind: Schema.optionalKey(\n                  Schema.Literals([\n                    \"read\",\n                    \"edit\",\n                    \"delete\",\n                    \"move\",\n                    \"search\",\n                    \"execute\",\n                    \"think\",\n                    \"fetch\",\n                    \"switch_mode\",\n                    \"other\",\n                  ]).annotate({\n                    description:\n                      \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n                  }),\n                ),\n                locations: Schema.optionalKey(\n                  Schema.Array(ToolCallLocation).annotate({\n                    description:\n                      'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n                  }),\n                ),\n                rawInput: Schema.optionalKey(\n                  Schema.Unknown.annotate({\n                    description: \"Raw input parameters sent to the tool.\",\n                  }),\n                ),\n                rawOutput: Schema.optionalKey(\n                  Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n                ),\n                status: Schema.optionalKey(\n                  Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n                    description:\n                      \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n                  }),\n                ),\n                title: Schema.String.annotate({\n                  description: \"Human-readable title describing what the tool is doing.\",\n                }),\n                toolCallId: Schema.String.annotate({\n                  description: \"Unique identifier for a tool call within a session.\",\n                }),\n              }).annotate({\n                description:\n                  \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"tool_call_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Array(ToolCallContent).annotate({\n                      description: \"Replace the content collection.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                kind: Schema.optionalKey(\n                  Schema.Union([ToolKind, Schema.Null]).annotate({\n                    description: \"Update the tool kind.\",\n                  }),\n                ),\n                locations: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Array(ToolCallLocation).annotate({\n                      description: \"Replace the locations collection.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                rawInput: Schema.optionalKey(\n                  Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n                ),\n                rawOutput: Schema.optionalKey(\n                  Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n                ),\n                status: Schema.optionalKey(\n                  Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n                    description: \"Update the execution status.\",\n                  }),\n                ),\n                title: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n                    Schema.Null,\n                  ]),\n                ),\n                toolCallId: Schema.String.annotate({\n                  description: \"Unique identifier for a tool call within a session.\",\n                }),\n              }).annotate({\n                description:\n                  \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"plan\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                entries: Schema.Array(PlanEntry).annotate({\n                  description:\n                    \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n                }),\n              }).annotate({\n                description:\n                  \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"available_commands_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                availableCommands: Schema.Array(AvailableCommand).annotate({\n                  description: \"Commands the agent can execute\",\n                }),\n              }).annotate({ description: \"Available commands are ready or have changed\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"current_mode_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                currentModeId: Schema.String.annotate({\n                  description: \"Unique identifier for a Session Mode.\",\n                }),\n              }).annotate({\n                description:\n                  \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"config_option_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                configOptions: Schema.Array(SessionConfigOption).annotate({\n                  description: \"The full set of configuration options and their current values.\",\n                }),\n              }).annotate({ description: \"Session configuration options have been updated.\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"session_info_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                title: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description: \"Human-readable title for the session. Set to null to clear.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                updatedAt: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({\n                description:\n                  \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"usage_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                cost: Schema.optionalKey(\n                  Schema.Union([Cost, Schema.Null]).annotate({\n                    description: \"Cumulative session cost (optional).\",\n                  }),\n                ),\n                size: Schema.Number.annotate({\n                  description: \"Total context window size in tokens.\",\n                  format: \"uint64\",\n                })\n                  .check(Schema.isInt())\n                  .check(Schema.isGreaterThanOrEqualTo(0)),\n                used: Schema.Number.annotate({\n                  description: \"Tokens currently in context.\",\n                  format: \"uint64\",\n                })\n                  .check(Schema.isInt())\n                  .check(Schema.isGreaterThanOrEqualTo(0)),\n              }).annotate({\n                description:\n                  \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n              }),\n            ],\n            { mode: \"oneOf\" },\n          ).annotate({\n            description:\n              \"Different types of updates that can be sent during session processing.\\n\\nThese updates provide real-time feedback about the agent's progress.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n          }),\n        }).annotate({\n          title: \"SessionNotification\",\n          description:\n            \"Notification containing a session update from the agent.\\n\\nUsed to stream real-time progress and results during prompt processing.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          elicitationId: Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n          }),\n        }).annotate({\n          title: \"ElicitationCompleteNotification\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nNotification sent by the agent when a URL-based elicitation is complete.\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtNotification\",\n          description:\n            \"Allows the Agent to send an arbitrary notification that is not part of the ACP spec.\\nExtension notifications provide a way to send one-way messages for custom functionality\\nwhile maintaining protocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible notifications that an agent can send to a client.\\n\\nThis enum is used internally for routing RPC notifications. You typically won't need\\nto use this directly - use the notification methods on the [`Client`] trait instead.\\n\\nNotifications do not expect a response.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type AgentRequest = {\n  readonly id: RequestId;\n  readonly method: string;\n  readonly params?:\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content: string;\n        readonly path: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly limit?: number | null;\n        readonly line?: number | null;\n        readonly path: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly options: ReadonlyArray<PermissionOption>;\n        readonly sessionId: string;\n        readonly toolCall: {\n          readonly _meta?: { readonly [x: string]: unknown } | null;\n          readonly content?: ReadonlyArray<ToolCallContent> | null;\n          readonly kind?: ToolKind | null;\n          readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n          readonly rawInput?: unknown;\n          readonly rawOutput?: unknown;\n          readonly status?: ToolCallStatus | null;\n          readonly title?: string | null;\n          readonly toolCallId: string;\n        };\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly args?: ReadonlyArray<string>;\n        readonly command: string;\n        readonly cwd?: string | null;\n        readonly env?: ReadonlyArray<EnvVariable>;\n        readonly outputByteLimit?: number | null;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly mode: \"form\";\n        readonly requestedSchema: {\n          readonly description?: string | null;\n          readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n          readonly required?: ReadonlyArray<string> | null;\n          readonly title?: string | null;\n          readonly type?: \"object\";\n        };\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly message: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly mode: \"url\";\n        readonly elicitationId: string;\n        readonly url: string;\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly message: string;\n        readonly sessionId: string;\n      }\n    | unknown\n    | null;\n};\nexport const AgentRequest = Schema.Struct({\n  id: RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          content: Schema.String.annotate({\n            description: \"The text content to write to the file.\",\n          }),\n          path: Schema.String.annotate({ description: \"Absolute path to the file to write.\" }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"WriteTextFileRequest\",\n          description:\n            \"Request to write content to a text file.\\n\\nOnly available if the client supports the `fs.writeTextFile` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          limit: Schema.optionalKey(\n            Schema.Union([\n              Schema.Number.annotate({\n                description: \"Maximum number of lines to read.\",\n                format: \"uint32\",\n              })\n                .check(Schema.isInt())\n                .check(Schema.isGreaterThanOrEqualTo(0)),\n              Schema.Null,\n            ]),\n          ),\n          line: Schema.optionalKey(\n            Schema.Union([\n              Schema.Number.annotate({\n                description: \"Line number to start reading from (1-based).\",\n                format: \"uint32\",\n              })\n                .check(Schema.isInt())\n                .check(Schema.isGreaterThanOrEqualTo(0)),\n              Schema.Null,\n            ]),\n          ),\n          path: Schema.String.annotate({ description: \"Absolute path to the file to read.\" }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"ReadTextFileRequest\",\n          description:\n            \"Request to read content from a text file.\\n\\nOnly available if the client supports the `fs.readTextFile` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          options: Schema.Array(PermissionOption).annotate({\n            description: \"Available permission options for the user to choose from.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          toolCall: Schema.Struct({\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            content: Schema.optionalKey(\n              Schema.Union([\n                Schema.Array(ToolCallContent).annotate({\n                  description: \"Replace the content collection.\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            kind: Schema.optionalKey(\n              Schema.Union([ToolKind, Schema.Null]).annotate({\n                description: \"Update the tool kind.\",\n              }),\n            ),\n            locations: Schema.optionalKey(\n              Schema.Union([\n                Schema.Array(ToolCallLocation).annotate({\n                  description: \"Replace the locations collection.\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            rawInput: Schema.optionalKey(\n              Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n            ),\n            rawOutput: Schema.optionalKey(\n              Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n            ),\n            status: Schema.optionalKey(\n              Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n                description: \"Update the execution status.\",\n              }),\n            ),\n            title: Schema.optionalKey(\n              Schema.Union([\n                Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n                Schema.Null,\n              ]),\n            ),\n            toolCallId: Schema.String.annotate({\n              description: \"Unique identifier for a tool call within a session.\",\n            }),\n          }).annotate({\n            description:\n              \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n          }),\n        }).annotate({\n          title: \"RequestPermissionRequest\",\n          description:\n            \"Request for user permission to execute a tool call.\\n\\nSent when the agent needs authorization before performing a sensitive operation.\\n\\nSee protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          args: Schema.optionalKey(\n            Schema.Array(Schema.String).annotate({ description: \"Array of command arguments.\" }),\n          ),\n          command: Schema.String.annotate({ description: \"The command to execute.\" }),\n          cwd: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description: \"Working directory for the command (absolute path).\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          env: Schema.optionalKey(\n            Schema.Array(EnvVariable).annotate({\n              description: \"Environment variables for the command.\",\n            }),\n          ),\n          outputByteLimit: Schema.optionalKey(\n            Schema.Union([\n              Schema.Number.annotate({\n                description:\n                  \"Maximum number of output bytes to retain.\\n\\nWhen the limit is exceeded, the Client truncates from the beginning of the output\\nto stay within the limit.\\n\\nThe Client MUST ensure truncation happens at a character boundary to maintain valid\\nstring output, even if this means the retained output is slightly less than the\\nspecified limit.\",\n                format: \"uint64\",\n              })\n                .check(Schema.isInt())\n                .check(Schema.isGreaterThanOrEqualTo(0)),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"CreateTerminalRequest\",\n          description: \"Request to create a new terminal and execute a command.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({\n            description: \"The ID of the terminal to get output from.\",\n          }),\n        }).annotate({\n          title: \"TerminalOutputRequest\",\n          description: \"Request to get the current output and status of a terminal.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({ description: \"The ID of the terminal to release.\" }),\n        }).annotate({\n          title: \"ReleaseTerminalRequest\",\n          description: \"Request to release a terminal and free its resources.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({\n            description: \"The ID of the terminal to wait for.\",\n          }),\n        }).annotate({\n          title: \"WaitForTerminalExitRequest\",\n          description: \"Request to wait for a terminal command to exit.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({ description: \"The ID of the terminal to kill.\" }),\n        }).annotate({\n          title: \"KillTerminalRequest\",\n          description: \"Request to kill a terminal without releasing it.\",\n        }),\n        Schema.Union([\n          Schema.Struct({\n            mode: Schema.Literal(\"form\"),\n            requestedSchema: Schema.Struct({\n              description: Schema.optionalKey(\n                Schema.Union([\n                  Schema.String.annotate({\n                    description: \"Optional description of what this schema represents.\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              properties: Schema.optionalKey(\n                Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n                  description: \"Property definitions (must be primitive types).\",\n                  default: {},\n                }),\n              ),\n              required: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Array(Schema.String).annotate({\n                    description: \"List of required property names.\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(\n                Schema.Union([\n                  Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n                  Schema.Null,\n                ]),\n              ),\n              type: Schema.optionalKey(\n                Schema.Literal(\"object\").annotate({\n                  description: \"Type discriminator for elicitation schemas.\",\n                  default: \"object\",\n                }),\n              ),\n            }).annotate({\n              description:\n                \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n            }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            message: Schema.String.annotate({\n              description: \"A human-readable message describing what input is needed.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n          }),\n          Schema.Struct({\n            mode: Schema.Literal(\"url\"),\n            elicitationId: Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n            }),\n            url: Schema.String.annotate({\n              description: \"The URL to direct the user to.\",\n              format: \"uri\",\n            }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            message: Schema.String.annotate({\n              description: \"A human-readable message describing what input is needed.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n          }),\n        ]).annotate({\n          title: \"ElicitationRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequests structured user input via a form or URL.\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtMethodRequest\",\n          description:\n            \"Allows for sending an arbitrary request that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible requests that an agent can send to a client.\\n\\nThis enum is used internally for routing RPC requests. You typically won't need\\nto use this directly - instead, use the methods on the [`Client`] trait.\\n\\nThis enum encompasses all method calls from agent to client.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type AgentResponse =\n  | {\n      readonly id: RequestId;\n      readonly result:\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly agentCapabilities?: {\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly auth?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly logout?: LogoutCapabilities | null;\n              };\n              readonly loadSession?: boolean;\n              readonly mcpCapabilities?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly http?: boolean;\n                readonly sse?: boolean;\n              };\n              readonly promptCapabilities?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly audio?: boolean;\n                readonly embeddedContext?: boolean;\n                readonly image?: boolean;\n              };\n              readonly sessionCapabilities?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly close?: SessionCloseCapabilities | null;\n                readonly fork?: SessionForkCapabilities | null;\n                readonly list?: SessionListCapabilities | null;\n                readonly resume?: SessionResumeCapabilities | null;\n              };\n            };\n            readonly agentInfo?: Implementation | null;\n            readonly authMethods?: ReadonlyArray<AuthMethod>;\n            readonly protocolVersion: number;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n            readonly sessionId: string;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly nextCursor?: string | null;\n            readonly sessions: ReadonlyArray<SessionInfo>;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n            readonly sessionId: string;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions: ReadonlyArray<SessionConfigOption>;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly stopReason:\n              | \"end_turn\"\n              | \"max_tokens\"\n              | \"max_turn_requests\"\n              | \"refusal\"\n              | \"cancelled\";\n            readonly usage?: Usage | null;\n            readonly userMessageId?: string | null;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | unknown;\n    }\n  | { readonly error: Error; readonly id: RequestId };\nexport const AgentResponse = Schema.Union([\n  Schema.Struct({\n    id: RequestId,\n    result: Schema.Union([\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        agentCapabilities: Schema.optionalKey(\n          Schema.Struct({\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            auth: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                logout: Schema.optionalKey(\n                  Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n                  }),\n                ),\n              }).annotate({\n                description:\n                  \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n                default: {},\n              }),\n            ),\n            loadSession: Schema.optionalKey(\n              Schema.Boolean.annotate({\n                description: \"Whether the agent supports `session/load`.\",\n                default: false,\n              }),\n            ),\n            mcpCapabilities: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                http: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`McpServer::Http`].\",\n                    default: false,\n                  }),\n                ),\n                sse: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`McpServer::Sse`].\",\n                    default: false,\n                  }),\n                ),\n              }).annotate({\n                description: \"MCP capabilities supported by the agent\",\n                default: { http: false, sse: false },\n              }),\n            ),\n            promptCapabilities: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                audio: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`ContentBlock::Audio`].\",\n                    default: false,\n                  }),\n                ),\n                embeddedContext: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description:\n                      \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n                    default: false,\n                  }),\n                ),\n                image: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`ContentBlock::Image`].\",\n                    default: false,\n                  }),\n                ),\n              }).annotate({\n                description:\n                  \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n                default: { audio: false, embeddedContext: false, image: false },\n              }),\n            ),\n            sessionCapabilities: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                close: Schema.optionalKey(\n                  Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n                  }),\n                ),\n                fork: Schema.optionalKey(\n                  Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n                  }),\n                ),\n                list: Schema.optionalKey(\n                  Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n                    description: \"Whether the agent supports `session/list`.\",\n                  }),\n                ),\n                resume: Schema.optionalKey(\n                  Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n                  }),\n                ),\n              }).annotate({\n                default: {},\n                description:\n                  \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n              }),\n            ),\n          }).annotate({\n            description:\n              \"Capabilities supported by the agent.\\n\\nAdvertised during initialization to inform the client about\\navailable features and content types.\\n\\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)\",\n            default: {\n              auth: {},\n              loadSession: false,\n              mcpCapabilities: { http: false, sse: false },\n              promptCapabilities: { audio: false, embeddedContext: false, image: false },\n              sessionCapabilities: {},\n            },\n          }),\n        ),\n        agentInfo: Schema.optionalKey(\n          Schema.Union([Implementation, Schema.Null]).annotate({\n            description:\n              \"Information about the Agent name and version sent to the Client.\\n\\nNote: in future versions of the protocol, this will be required.\",\n          }),\n        ),\n        authMethods: Schema.optionalKey(\n          Schema.Array(AuthMethod).annotate({\n            description: \"Authentication methods supported by the agent.\",\n            default: [],\n          }),\n        ),\n        protocolVersion: Schema.Number.annotate({\n          description:\n            \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n          format: \"uint16\",\n        })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0))\n          .check(Schema.isLessThanOrEqualTo(65535)),\n      }).annotate({\n        title: \"InitializeResponse\",\n        description:\n          \"Response to the `initialize` method.\\n\\nContains the negotiated protocol version and agent capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"AuthenticateResponse\",\n        description: \"Response to the `authenticate` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"LogoutResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to the `logout` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n        sessionId: Schema.String.annotate({\n          description:\n            \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n        }),\n      }).annotate({\n        title: \"NewSessionResponse\",\n        description:\n          \"Response from creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n      }).annotate({\n        title: \"LoadSessionResponse\",\n        description: \"Response from loading an existing session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        nextCursor: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"Opaque cursor token. If present, pass this in the next request's cursor parameter\\nto fetch the next page. If absent, there are no more results.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        sessions: Schema.Array(SessionInfo).annotate({\n          description: \"Array of session information objects\",\n        }),\n      }).annotate({\n        title: \"ListSessionsResponse\",\n        description: \"Response from listing sessions.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n        sessionId: Schema.String.annotate({\n          description:\n            \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n        }),\n      }).annotate({\n        title: \"ForkSessionResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from forking an existing session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n      }).annotate({\n        title: \"ResumeSessionResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from resuming an existing session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"CloseSessionResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from closing a session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"SetSessionModeResponse\",\n        description: \"Response to `session/set_mode` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.Array(SessionConfigOption).annotate({\n          description: \"The full set of configuration options and their current values.\",\n        }),\n      }).annotate({\n        title: \"SetSessionConfigOptionResponse\",\n        description: \"Response to `session/set_config_option` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        stopReason: Schema.Literals([\n          \"end_turn\",\n          \"max_tokens\",\n          \"max_turn_requests\",\n          \"refusal\",\n          \"cancelled\",\n        ]).annotate({\n          description:\n            \"Reasons why an agent stops processing a prompt turn.\\n\\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)\",\n        }),\n        usage: Schema.optionalKey(\n          Schema.Union([Usage, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nToken usage for this turn (optional).\",\n          }),\n        ),\n        userMessageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe acknowledged user message ID.\\n\\nIf the client provided a `messageId` in the [`PromptRequest`], the agent echoes it here\\nto confirm it was recorded. If the client did not provide one, the agent MAY assign one\\nand return it here. Absence of this field indicates the agent did not record a message ID.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"PromptResponse\",\n        description:\n          \"Response from processing a user prompt.\\n\\nSee protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/prompt-turn#4-check-for-completion)\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"SetSessionModelResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to `session/set_model` method.\",\n      }),\n      Schema.Unknown.annotate({\n        title: \"ExtMethodResponse\",\n        description:\n          \"Allows for sending an arbitrary response to an [`ExtRequest`] that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n    ]).annotate({\n      description:\n        \"All possible responses that an agent can send to a client.\\n\\nThis enum is used internally for routing RPC responses. You typically won't need\\nto use this directly - the responses are handled automatically by the connection.\\n\\nThese are responses to the corresponding `ClientRequest` variants.\",\n    }),\n  }).annotate({ title: \"Result\" }),\n  Schema.Struct({ error: Error, id: RequestId }).annotate({ title: \"Error\" }),\n]);\n\nexport type AudioContent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly data: string;\n  readonly mimeType: string;\n};\nexport const AudioContent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  data: Schema.String,\n  mimeType: Schema.String,\n}).annotate({ description: \"Audio provided to or from an LLM.\" });\n\nexport type AuthCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly terminal?: boolean;\n};\nexport const AuthCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  terminal: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n});\n\nexport type AuthenticateRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly methodId: string;\n};\nexport const AuthenticateRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  methodId: Schema.String.annotate({\n    description:\n      \"The ID of the authentication method to use.\\nMust be one of the methods advertised in the initialize response.\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for the authenticate method.\\n\\nSpecifies which authentication method to use.\",\n});\n\nexport type AuthenticateResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const AuthenticateResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to the `authenticate` method.\" });\n\nexport type AuthMethodAgent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly name: string;\n};\nexport const AuthMethodAgent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional description providing more details about this authentication method.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({ description: \"Unique identifier for this authentication method.\" }),\n  name: Schema.String.annotate({\n    description: \"Human-readable name of the authentication method.\",\n  }),\n}).annotate({\n  description:\n    \"Agent handles authentication itself.\\n\\nThis is the default authentication method type.\",\n});\n\nexport type AuthMethodEnvVar = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly link?: string | null;\n  readonly name: string;\n  readonly vars: ReadonlyArray<AuthEnvVar>;\n};\nexport const AuthMethodEnvVar = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional description providing more details about this authentication method.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({ description: \"Unique identifier for this authentication method.\" }),\n  link: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional link to a page where the user can obtain their credentials.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({\n    description: \"Human-readable name of the authentication method.\",\n  }),\n  vars: Schema.Array(AuthEnvVar).annotate({\n    description: \"The environment variables the client should set.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nEnvironment variable authentication method.\\n\\nThe user provides credentials that the client passes to the agent as environment variables.\",\n});\n\nexport type AuthMethodTerminal = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly args?: ReadonlyArray<string>;\n  readonly description?: string | null;\n  readonly env?: { readonly [x: string]: string };\n  readonly id: string;\n  readonly name: string;\n};\nexport const AuthMethodTerminal = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  args: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"Additional arguments to pass when running the agent binary for terminal auth.\",\n    }),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional description providing more details about this authentication method.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  env: Schema.optionalKey(\n    Schema.Record(Schema.String, Schema.String).annotate({\n      description:\n        \"Additional environment variables to set when running the agent binary for terminal auth.\",\n    }),\n  ),\n  id: Schema.String.annotate({ description: \"Unique identifier for this authentication method.\" }),\n  name: Schema.String.annotate({\n    description: \"Human-readable name of the authentication method.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nTerminal-based authentication method.\\n\\nThe client runs an interactive terminal for the user to authenticate via a TUI.\",\n});\n\nexport type AvailableCommandsUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly availableCommands: ReadonlyArray<AvailableCommand>;\n};\nexport const AvailableCommandsUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  availableCommands: Schema.Array(AvailableCommand).annotate({\n    description: \"Commands the agent can execute\",\n  }),\n}).annotate({ description: \"Available commands are ready or have changed\" });\n\nexport type BlobResourceContents = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly blob: string;\n  readonly mimeType?: string | null;\n  readonly uri: string;\n};\nexport const BlobResourceContents = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  blob: Schema.String,\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({ description: \"Binary resource contents.\" });\n\nexport type BooleanPropertySchema = {\n  readonly default?: boolean | null;\n  readonly description?: string | null;\n  readonly title?: string | null;\n};\nexport const BooleanPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([Schema.Boolean.annotate({ description: \"Default value.\" }), Schema.Null]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Schema for boolean properties in an elicitation form.\" });\n\nexport type CancelNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n};\nexport const CancelNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Notification to cancel ongoing operations for a session.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n});\n\nexport type CancelRequestNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly requestId: null | number | string;\n};\nexport const CancelRequestNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  requestId: Schema.Union([\n    Schema.Null.annotate({ title: \"Null\" }),\n    Schema.Number.annotate({ title: \"Number\", format: \"int64\" }).check(Schema.isInt()),\n    Schema.String.annotate({ title: \"Str\" }),\n  ]).annotate({\n    description:\n      \"JSON RPC Request Id\\n\\nAn identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null [1] and Numbers SHOULD NOT contain fractional parts [2]\\n\\nThe Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.\\n\\n[1] The use of Null as a value for the id member in a Request object is discouraged, because this specification uses a value of Null for Responses with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null for Notifications this could cause confusion in handling.\\n\\n[2] Fractional parts may be problematic, since many decimal fractions cannot be represented exactly as binary fractions.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nNotification to cancel an ongoing request.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/cancellation)\",\n});\n\nexport type ClientCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly auth?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly terminal?: boolean;\n  };\n  readonly elicitation?: ElicitationCapabilities | null;\n  readonly fs?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly readTextFile?: boolean;\n    readonly writeTextFile?: boolean;\n  };\n  readonly terminal?: boolean;\n};\nexport const ClientCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  auth: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      terminal: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description:\n            \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n      default: { terminal: false },\n    }),\n  ),\n  elicitation: Schema.optionalKey(\n    Schema.Union([ElicitationCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\\nDetermines which elicitation modes the agent may use.\",\n    }),\n  ),\n  fs: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      readTextFile: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the Client supports `fs/read_text_file` requests.\",\n          default: false,\n        }),\n      ),\n      writeTextFile: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the Client supports `fs/write_text_file` requests.\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n      default: { readTextFile: false, writeTextFile: false },\n    }),\n  ),\n  terminal: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the Client support all `terminal/*` methods.\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"Capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent about\\navailable features and methods.\\n\\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)\",\n});\n\nexport type ClientNotification = {\n  readonly method: string;\n  readonly params?:\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly sessionId: string }\n    | unknown\n    | null;\n};\nexport const ClientNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"CancelNotification\",\n          description:\n            \"Notification to cancel ongoing operations for a session.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtNotification\",\n          description:\n            \"Allows the Agent to send an arbitrary notification that is not part of the ACP spec.\\nExtension notifications provide a way to send one-way messages for custom functionality\\nwhile maintaining protocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible notifications that a client can send to an agent.\\n\\nThis enum is used internally for routing RPC notifications. You typically won't need\\nto use this directly - use the notification methods on the [`Agent`] trait instead.\\n\\nNotifications do not expect a response.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest = {\n  readonly id: RequestId;\n  readonly method: string;\n  readonly params?:\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly clientCapabilities?: {\n          readonly _meta?: { readonly [x: string]: unknown } | null;\n          readonly auth?: {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly terminal?: boolean;\n          };\n          readonly elicitation?: ElicitationCapabilities | null;\n          readonly fs?: {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly readTextFile?: boolean;\n            readonly writeTextFile?: boolean;\n          };\n          readonly terminal?: boolean;\n        };\n        readonly clientInfo?: Implementation | null;\n        readonly protocolVersion: number;\n      }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly methodId: string }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers: ReadonlyArray<McpServer>;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers: ReadonlyArray<McpServer>;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cursor?: string | null;\n        readonly cwd?: string | null;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers?: ReadonlyArray<McpServer>;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers?: ReadonlyArray<McpServer>;\n        readonly sessionId: string;\n      }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly sessionId: string }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly modeId: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly type: \"boolean\";\n        readonly value: boolean;\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly configId: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly value: string;\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly configId: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly messageId?: string | null;\n        readonly prompt: ReadonlyArray<ContentBlock>;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly modelId: string;\n        readonly sessionId: string;\n      }\n    | unknown\n    | null;\n};\nexport const ClientRequest = Schema.Struct({\n  id: RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          clientCapabilities: Schema.optionalKey(\n            Schema.Struct({\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              auth: Schema.optionalKey(\n                Schema.Struct({\n                  _meta: Schema.optionalKey(\n                    Schema.Union([\n                      Schema.Record(Schema.String, Schema.Unknown).annotate({\n                        description:\n                          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                      }),\n                      Schema.Null,\n                    ]),\n                  ),\n                  terminal: Schema.optionalKey(\n                    Schema.Boolean.annotate({\n                      description:\n                        \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n                      default: false,\n                    }),\n                  ),\n                }).annotate({\n                  description:\n                    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n                  default: { terminal: false },\n                }),\n              ),\n              elicitation: Schema.optionalKey(\n                Schema.Union([ElicitationCapabilities, Schema.Null]).annotate({\n                  description:\n                    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\\nDetermines which elicitation modes the agent may use.\",\n                }),\n              ),\n              fs: Schema.optionalKey(\n                Schema.Struct({\n                  _meta: Schema.optionalKey(\n                    Schema.Union([\n                      Schema.Record(Schema.String, Schema.Unknown).annotate({\n                        description:\n                          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                      }),\n                      Schema.Null,\n                    ]),\n                  ),\n                  readTextFile: Schema.optionalKey(\n                    Schema.Boolean.annotate({\n                      description: \"Whether the Client supports `fs/read_text_file` requests.\",\n                      default: false,\n                    }),\n                  ),\n                  writeTextFile: Schema.optionalKey(\n                    Schema.Boolean.annotate({\n                      description: \"Whether the Client supports `fs/write_text_file` requests.\",\n                      default: false,\n                    }),\n                  ),\n                }).annotate({\n                  description:\n                    \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n                  default: { readTextFile: false, writeTextFile: false },\n                }),\n              ),\n              terminal: Schema.optionalKey(\n                Schema.Boolean.annotate({\n                  description: \"Whether the Client support all `terminal/*` methods.\",\n                  default: false,\n                }),\n              ),\n            }).annotate({\n              description:\n                \"Capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent about\\navailable features and methods.\\n\\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)\",\n              default: {\n                auth: { terminal: false },\n                fs: { readTextFile: false, writeTextFile: false },\n                terminal: false,\n              },\n            }),\n          ),\n          clientInfo: Schema.optionalKey(\n            Schema.Union([Implementation, Schema.Null]).annotate({\n              description:\n                \"Information about the Client name and version sent to the Agent.\\n\\nNote: in future versions of the protocol, this will be required.\",\n            }),\n          ),\n          protocolVersion: Schema.Number.annotate({\n            description:\n              \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n            format: \"uint16\",\n          })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0))\n            .check(Schema.isLessThanOrEqualTo(65535)),\n        }).annotate({\n          title: \"InitializeRequest\",\n          description:\n            \"Request parameters for the initialize method.\\n\\nSent by the client to establish connection and negotiate capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          methodId: Schema.String.annotate({\n            description:\n              \"The ID of the authentication method to use.\\nMust be one of the methods advertised in the initialize response.\",\n          }),\n        }).annotate({\n          title: \"AuthenticateRequest\",\n          description:\n            \"Request parameters for the authenticate method.\\n\\nSpecifies which authentication method to use.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n        }).annotate({\n          title: \"LogoutRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for the logout method.\\n\\nTerminates the current authenticated session.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({\n            description: \"The working directory for this session. Must be an absolute path.\",\n          }),\n          mcpServers: Schema.Array(McpServer).annotate({\n            description:\n              \"List of MCP (Model Context Protocol) servers the agent should connect to.\",\n          }),\n        }).annotate({\n          title: \"NewSessionRequest\",\n          description:\n            \"Request parameters for creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n          mcpServers: Schema.Array(McpServer).annotate({\n            description: \"List of MCP servers to connect to for this session.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"LoadSessionRequest\",\n          description:\n            \"Request parameters for loading an existing session.\\n\\nOnly available if the Agent supports the `loadSession` capability.\\n\\nSee protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cursor: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description:\n                  \"Opaque cursor token from a previous response's nextCursor field for cursor-based pagination\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description: \"Filter sessions by working directory. Must be an absolute path.\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n        }).annotate({\n          title: \"ListSessionsRequest\",\n          description:\n            \"Request parameters for listing existing sessions.\\n\\nOnly available if the Agent supports the `sessionCapabilities.list` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n          mcpServers: Schema.optionalKey(\n            Schema.Array(McpServer).annotate({\n              description: \"List of MCP servers to connect to for this session.\",\n            }),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"ForkSessionRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for forking an existing session.\\n\\nCreates a new session based on the context of an existing one, allowing\\noperations like generating summaries without affecting the original session's history.\\n\\nOnly available if the Agent supports the `session.fork` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n          mcpServers: Schema.optionalKey(\n            Schema.Array(McpServer).annotate({\n              description: \"List of MCP servers to connect to for this session.\",\n            }),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"ResumeSessionRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for resuming an existing session.\\n\\nResumes an existing session without returning previous messages (unlike `session/load`).\\nThis is useful for agents that can resume sessions but don't implement full session loading.\\n\\nOnly available if the Agent supports the `session.resume` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"CloseSessionRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for closing an active session.\\n\\nIf supported, the agent **must** cancel any ongoing work related to the session\\n(treat it as if `session/cancel` was called) and then free up any resources\\nassociated with the session.\\n\\nOnly available if the Agent supports the `session.close` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          modeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"SetSessionModeRequest\",\n          description: \"Request parameters for setting a session mode.\",\n        }),\n        Schema.Union([\n          Schema.Struct({\n            type: Schema.Literal(\"boolean\"),\n            value: Schema.Boolean.annotate({ description: \"The boolean value.\" }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            configId: Schema.String.annotate({\n              description: \"Unique identifier for a session configuration option.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            description: \"Request parameters for setting a session configuration option.\",\n          }),\n          Schema.Struct({\n            value: Schema.String.annotate({\n              description: \"Unique identifier for a session configuration option value.\",\n            }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            configId: Schema.String.annotate({\n              description: \"Unique identifier for a session configuration option.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            title: \"value_id\",\n            description: \"Request parameters for setting a session configuration option.\",\n          }),\n        ]).annotate({\n          title: \"SetSessionConfigOptionRequest\",\n          description: \"Sets the current value for a session configuration option.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          messageId: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description:\n                  \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA client-generated unique identifier for this user message.\\n\\nIf provided, the Agent SHOULD echo this value as `userMessageId` in the\\n[`PromptResponse`] to confirm it was recorded.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          prompt: Schema.Array(ContentBlock).annotate({\n            description:\n              \"The blocks of content that compose the user's message.\\n\\nAs a baseline, the Agent MUST support [`ContentBlock::Text`] and [`ContentBlock::ResourceLink`],\\nwhile other variants are optionally enabled via [`PromptCapabilities`].\\n\\nThe Client MUST adapt its interface according to [`PromptCapabilities`].\\n\\nThe client MAY include referenced pieces of context as either\\n[`ContentBlock::Resource`] or [`ContentBlock::ResourceLink`].\\n\\nWhen available, [`ContentBlock::Resource`] is preferred\\nas it avoids extra round-trips and allows the message to include\\npieces of context from sources the agent may not have access to.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"PromptRequest\",\n          description:\n            \"Request parameters for sending a user prompt to the agent.\\n\\nContains the user's message and any additional context.\\n\\nSee protocol docs: [User Message](https://agentclientprotocol.com/protocol/prompt-turn#1-user-message)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          modelId: Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"SetSessionModelRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for setting a session model.\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtMethodRequest\",\n          description:\n            \"Allows for sending an arbitrary request that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible requests that a client can send to an agent.\\n\\nThis enum is used internally for routing RPC requests. You typically won't need\\nto use this directly - instead, use the methods on the [`Agent`] trait.\\n\\nThis enum encompasses all method calls from client to agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientResponse =\n  | {\n      readonly id: RequestId;\n      readonly result:\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly content: string }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly outcome:\n              | { readonly outcome: \"cancelled\" }\n              | {\n                  readonly outcome: \"selected\";\n                  readonly _meta?: { readonly [x: string]: unknown } | null;\n                  readonly optionId: string;\n                };\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly terminalId: string }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly exitStatus?: TerminalExitStatus | null;\n            readonly output: string;\n            readonly truncated: boolean;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly exitCode?: number | null;\n            readonly signal?: string | null;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly action:\n              | {\n                  readonly action: \"accept\";\n                  readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n                }\n              | { readonly action: \"decline\" }\n              | { readonly action: \"cancel\" };\n          }\n        | unknown;\n    }\n  | { readonly error: Error; readonly id: RequestId };\nexport const ClientResponse = Schema.Union([\n  Schema.Struct({\n    id: RequestId,\n    result: Schema.Union([\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"WriteTextFileResponse\",\n        description: \"Response to `fs/write_text_file`\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.String,\n      }).annotate({\n        title: \"ReadTextFileResponse\",\n        description: \"Response containing the contents of a text file.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        outcome: Schema.Union(\n          [\n            Schema.Struct({ outcome: Schema.Literal(\"cancelled\") }).annotate({\n              description:\n                \"The prompt turn was cancelled before the user responded.\\n\\nWhen a client sends a `session/cancel` notification to cancel an ongoing\\nprompt turn, it MUST respond to all pending `session/request_permission`\\nrequests with this `Cancelled` outcome.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n            }),\n            Schema.Struct({\n              outcome: Schema.Literal(\"selected\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              optionId: Schema.String.annotate({\n                description: \"Unique identifier for a permission option.\",\n              }),\n            }).annotate({ description: \"The user selected one of the provided options.\" }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({ description: \"The outcome of a permission request.\" }),\n      }).annotate({\n        title: \"RequestPermissionResponse\",\n        description: \"Response to a permission request.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        terminalId: Schema.String.annotate({\n          description: \"The unique identifier for the created terminal.\",\n        }),\n      }).annotate({\n        title: \"CreateTerminalResponse\",\n        description: \"Response containing the ID of the created terminal.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        exitStatus: Schema.optionalKey(\n          Schema.Union([TerminalExitStatus, Schema.Null]).annotate({\n            description: \"Exit status if the command has completed.\",\n          }),\n        ),\n        output: Schema.String.annotate({ description: \"The terminal output captured so far.\" }),\n        truncated: Schema.Boolean.annotate({\n          description: \"Whether the output was truncated due to byte limits.\",\n        }),\n      }).annotate({\n        title: \"TerminalOutputResponse\",\n        description: \"Response containing the terminal output and exit status.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"ReleaseTerminalResponse\",\n        description: \"Response to terminal/release method\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        exitCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({\n              description: \"The process exit code (may be null if terminated by signal).\",\n              format: \"uint32\",\n            })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n        signal: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"The signal that terminated the process (may be null if exited normally).\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"WaitForTerminalExitResponse\",\n        description: \"Response containing the exit status of a terminal command.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"KillTerminalResponse\",\n        description: \"Response to `terminal/kill` method\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        action: Schema.Union(\n          [\n            Schema.Struct({\n              action: Schema.Literal(\"accept\"),\n              content: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, ElicitationContentValue).annotate({\n                    description:\n                      \"The user-provided content, if any, as an object matching the requested schema.\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n            }).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n            }),\n            Schema.Struct({ action: Schema.Literal(\"decline\") }).annotate({\n              description: \"The user declined the elicitation.\",\n            }),\n            Schema.Struct({ action: Schema.Literal(\"cancel\") }).annotate({\n              description: \"The elicitation was cancelled.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user's action in response to an elicitation.\",\n        }),\n      }).annotate({\n        title: \"ElicitationResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from the client to an elicitation request.\",\n      }),\n      Schema.Unknown.annotate({\n        title: \"ExtMethodResponse\",\n        description:\n          \"Allows for sending an arbitrary response to an [`ExtRequest`] that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n    ]).annotate({\n      description:\n        \"All possible responses that a client can send to an agent.\\n\\nThis enum is used internally for routing RPC responses. You typically won't need\\nto use this directly - the responses are handled automatically by the connection.\\n\\nThese are responses to the corresponding `AgentRequest` variants.\",\n    }),\n  }).annotate({ title: \"Result\" }),\n  Schema.Struct({ error: Error, id: RequestId }).annotate({ title: \"Error\" }),\n]);\n\nexport type CloseSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n};\nexport const CloseSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for closing an active session.\\n\\nIf supported, the agent **must** cancel any ongoing work related to the session\\n(treat it as if `session/cancel` was called) and then free up any resources\\nassociated with the session.\\n\\nOnly available if the Agent supports the `session.close` capability.\",\n});\n\nexport type CloseSessionResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const CloseSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from closing a session.\",\n});\n\nexport type ConfigOptionUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions: ReadonlyArray<SessionConfigOption>;\n};\nexport const ConfigOptionUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.Array(SessionConfigOption).annotate({\n    description: \"The full set of configuration options and their current values.\",\n  }),\n}).annotate({ description: \"Session configuration options have been updated.\" });\n\nexport type Content = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content:\n    | {\n        readonly type: \"text\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly text: string;\n      }\n    | {\n        readonly type: \"image\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n        readonly uri?: string | null;\n      }\n    | {\n        readonly type: \"audio\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n      }\n    | {\n        readonly type: \"resource_link\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly description?: string | null;\n        readonly mimeType?: string | null;\n        readonly name: string;\n        readonly size?: number | null;\n        readonly title?: string | null;\n        readonly uri: string;\n      }\n    | {\n        readonly type: \"resource\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly resource: EmbeddedResourceResource;\n      };\n};\nexport const Content = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"text\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        text: Schema.String,\n      }).annotate({ description: \"Text provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"image\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n        uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      }).annotate({ description: \"An image provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"audio\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n      }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource_link\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        name: Schema.String,\n        size: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n            Schema.Null,\n          ]),\n        ),\n        title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        uri: Schema.String,\n      }).annotate({\n        description:\n          \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n      }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        resource: EmbeddedResourceResource,\n      }).annotate({\n        description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n  }),\n}).annotate({ description: \"Standard content block (text, images, resources).\" });\n\nexport type ContentChunk = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content:\n    | {\n        readonly type: \"text\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly text: string;\n      }\n    | {\n        readonly type: \"image\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n        readonly uri?: string | null;\n      }\n    | {\n        readonly type: \"audio\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n      }\n    | {\n        readonly type: \"resource_link\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly description?: string | null;\n        readonly mimeType?: string | null;\n        readonly name: string;\n        readonly size?: number | null;\n        readonly title?: string | null;\n        readonly uri: string;\n      }\n    | {\n        readonly type: \"resource\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly resource: EmbeddedResourceResource;\n      };\n  readonly messageId?: string | null;\n};\nexport const ContentChunk = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"text\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        text: Schema.String,\n      }).annotate({ description: \"Text provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"image\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n        uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      }).annotate({ description: \"An image provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"audio\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n      }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource_link\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        name: Schema.String,\n        size: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n            Schema.Null,\n          ]),\n        ),\n        title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        uri: Schema.String,\n      }).annotate({\n        description:\n          \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n      }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        resource: EmbeddedResourceResource,\n      }).annotate({\n        description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n  }),\n  messageId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"A streamed item of content\" });\n\nexport type CreateTerminalRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly args?: ReadonlyArray<string>;\n  readonly command: string;\n  readonly cwd?: string | null;\n  readonly env?: ReadonlyArray<EnvVariable>;\n  readonly outputByteLimit?: number | null;\n  readonly sessionId: string;\n};\nexport const CreateTerminalRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  args: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({ description: \"Array of command arguments.\" }),\n  ),\n  command: Schema.String.annotate({ description: \"The command to execute.\" }),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Working directory for the command (absolute path).\" }),\n      Schema.Null,\n    ]),\n  ),\n  env: Schema.optionalKey(\n    Schema.Array(EnvVariable).annotate({ description: \"Environment variables for the command.\" }),\n  ),\n  outputByteLimit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Maximum number of output bytes to retain.\\n\\nWhen the limit is exceeded, the Client truncates from the beginning of the output\\nto stay within the limit.\\n\\nThe Client MUST ensure truncation happens at a character boundary to maintain valid\\nstring output, even if this means the retained output is slightly less than the\\nspecified limit.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({ description: \"Request to create a new terminal and execute a command.\" });\n\nexport type CreateTerminalResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly terminalId: string;\n};\nexport const CreateTerminalResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  terminalId: Schema.String.annotate({\n    description: \"The unique identifier for the created terminal.\",\n  }),\n}).annotate({ description: \"Response containing the ID of the created terminal.\" });\n\nexport type CurrentModeUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly currentModeId: string;\n};\nexport const CurrentModeUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  currentModeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n}).annotate({\n  description:\n    \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n});\n\nexport type Diff = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly newText: string;\n  readonly oldText?: string | null;\n  readonly path: string;\n};\nexport const Diff = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  newText: Schema.String.annotate({ description: \"The new content after modification.\" }),\n  oldText: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"The original content (None for new files).\" }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({ description: \"The file path being modified.\" }),\n}).annotate({\n  description:\n    \"A diff representing file modifications.\\n\\nShows changes to files in a format suitable for display in the client UI.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\",\n});\n\nexport type ElicitationAcceptAction = {\n  readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n};\nexport const ElicitationAcceptAction = Schema.Struct({\n  content: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, ElicitationContentValue).annotate({\n        description:\n          \"The user-provided content, if any, as an object matching the requested schema.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n});\n\nexport type ElicitationAction =\n  | {\n      readonly action: \"accept\";\n      readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n    }\n  | { readonly action: \"decline\" }\n  | { readonly action: \"cancel\" };\nexport const ElicitationAction = Schema.Union(\n  [\n    Schema.Struct({\n      action: Schema.Literal(\"accept\"),\n      content: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, ElicitationContentValue).annotate({\n            description:\n              \"The user-provided content, if any, as an object matching the requested schema.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n    }),\n    Schema.Struct({ action: Schema.Literal(\"decline\") }).annotate({\n      description: \"The user declined the elicitation.\",\n    }),\n    Schema.Struct({ action: Schema.Literal(\"cancel\") }).annotate({\n      description: \"The elicitation was cancelled.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user's action in response to an elicitation.\",\n});\n\nexport type ElicitationCompleteNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly elicitationId: string;\n};\nexport const ElicitationCompleteNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  elicitationId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nNotification sent by the agent when a URL-based elicitation is complete.\",\n});\n\nexport type ElicitationFormMode = {\n  readonly requestedSchema: {\n    readonly description?: string | null;\n    readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n    readonly required?: ReadonlyArray<string> | null;\n    readonly title?: string | null;\n    readonly type?: \"object\";\n  };\n};\nexport const ElicitationFormMode = Schema.Struct({\n  requestedSchema: Schema.Struct({\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional description of what this schema represents.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    properties: Schema.optionalKey(\n      Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n        description: \"Property definitions (must be primitive types).\",\n        default: {},\n      }),\n    ),\n    required: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(Schema.String).annotate({ description: \"List of required property names.\" }),\n        Schema.Null,\n      ]),\n    ),\n    title: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n        Schema.Null,\n      ]),\n    ),\n    type: Schema.optionalKey(\n      Schema.Literal(\"object\").annotate({\n        description: \"Type discriminator for elicitation schemas.\",\n        default: \"object\",\n      }),\n    ),\n  }).annotate({\n    description:\n      \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nForm-based elicitation mode where the client renders a form from the provided schema.\",\n});\n\nexport type ElicitationId = string;\nexport const ElicitationId = Schema.String.annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n});\n\nexport type ElicitationRequest =\n  | {\n      readonly mode: \"form\";\n      readonly requestedSchema: {\n        readonly description?: string | null;\n        readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n        readonly required?: ReadonlyArray<string> | null;\n        readonly title?: string | null;\n        readonly type?: \"object\";\n      };\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly message: string;\n      readonly sessionId: string;\n    }\n  | {\n      readonly mode: \"url\";\n      readonly elicitationId: string;\n      readonly url: string;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly message: string;\n      readonly sessionId: string;\n    };\nexport const ElicitationRequest = Schema.Union([\n  Schema.Struct({\n    mode: Schema.Literal(\"form\"),\n    requestedSchema: Schema.Struct({\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Optional description of what this schema represents.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      properties: Schema.optionalKey(\n        Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n          description: \"Property definitions (must be primitive types).\",\n          default: {},\n        }),\n      ),\n      required: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.String).annotate({ description: \"List of required property names.\" }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.optionalKey(\n        Schema.Literal(\"object\").annotate({\n          description: \"Type discriminator for elicitation schemas.\",\n          default: \"object\",\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n    }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    message: Schema.String.annotate({\n      description: \"A human-readable message describing what input is needed.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n  }),\n  Schema.Struct({\n    mode: Schema.Literal(\"url\"),\n    elicitationId: Schema.String.annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n    }),\n    url: Schema.String.annotate({ description: \"The URL to direct the user to.\", format: \"uri\" }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    message: Schema.String.annotate({\n      description: \"A human-readable message describing what input is needed.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n  }),\n]);\n\nexport type ElicitationResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly action:\n    | {\n        readonly action: \"accept\";\n        readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n      }\n    | { readonly action: \"decline\" }\n    | { readonly action: \"cancel\" };\n};\nexport const ElicitationResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  action: Schema.Union(\n    [\n      Schema.Struct({\n        action: Schema.Literal(\"accept\"),\n        content: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, ElicitationContentValue).annotate({\n              description:\n                \"The user-provided content, if any, as an object matching the requested schema.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n      }),\n      Schema.Struct({ action: Schema.Literal(\"decline\") }).annotate({\n        description: \"The user declined the elicitation.\",\n      }),\n      Schema.Struct({ action: Schema.Literal(\"cancel\") }).annotate({\n        description: \"The elicitation was cancelled.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user's action in response to an elicitation.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from the client to an elicitation request.\",\n});\n\nexport type ElicitationSchema = {\n  readonly description?: string | null;\n  readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n  readonly required?: ReadonlyArray<string> | null;\n  readonly title?: string | null;\n  readonly type?: \"object\";\n};\nexport const ElicitationSchema = Schema.Struct({\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional description of what this schema represents.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  properties: Schema.optionalKey(\n    Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n      description: \"Property definitions (must be primitive types).\",\n      default: {},\n    }),\n  ),\n  required: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({ description: \"List of required property names.\" }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n      Schema.Null,\n    ]),\n  ),\n  type: Schema.optionalKey(\n    Schema.Literal(\"object\").annotate({\n      description: \"Type discriminator for elicitation schemas.\",\n      default: \"object\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n});\n\nexport type ElicitationSchemaType = \"object\";\nexport const ElicitationSchemaType = Schema.Literal(\"object\").annotate({\n  description: \"Type discriminator for elicitation schemas.\",\n});\n\nexport type ElicitationStringType = \"string\";\nexport const ElicitationStringType = Schema.Literal(\"string\").annotate({\n  description: \"Items definition for untitled multi-select enum properties.\",\n});\n\nexport type ElicitationUrlMode = { readonly elicitationId: string; readonly url: string };\nexport const ElicitationUrlMode = Schema.Struct({\n  elicitationId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n  }),\n  url: Schema.String.annotate({ description: \"The URL to direct the user to.\", format: \"uri\" }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nURL-based elicitation mode where the client directs the user to a URL.\",\n});\n\nexport type EmbeddedResource = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly resource: EmbeddedResourceResource;\n};\nexport const EmbeddedResource = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  resource: EmbeddedResourceResource,\n}).annotate({\n  description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n});\n\nexport type ErrorCode =\n  | -32700\n  | -32600\n  | -32601\n  | -32602\n  | -32603\n  | -32800\n  | -32000\n  | -32002\n  | -32042\n  | number;\nexport const ErrorCode = Schema.Union([\n  Schema.Literal(-32700).annotate({\n    title: \"Parse error\",\n    description:\n      \"**Parse error**: Invalid JSON was received by the server.\\nAn error occurred on the server while parsing the JSON text.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32600).annotate({\n    title: \"Invalid request\",\n    description: \"**Invalid request**: The JSON sent is not a valid Request object.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32601).annotate({\n    title: \"Method not found\",\n    description: \"**Method not found**: The method does not exist or is not available.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32602).annotate({\n    title: \"Invalid params\",\n    description: \"**Invalid params**: Invalid method parameter(s).\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32603).annotate({\n    title: \"Internal error\",\n    description:\n      \"**Internal error**: Internal JSON-RPC error.\\nReserved for implementation-defined server errors.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32800).annotate({\n    title: \"Request cancelled\",\n    description:\n      \"**Request cancelled**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nExecution of the method was aborted either due to a cancellation request from the caller or\\nbecause of resource constraints or shutdown.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32000).annotate({\n    title: \"Authentication required\",\n    description:\n      \"**Authentication required**: Authentication is required before this operation can be performed.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32002).annotate({\n    title: \"Resource not found\",\n    description: \"**Resource not found**: A given resource, such as a file, was not found.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32042).annotate({\n    title: \"URL elicitation required\",\n    description:\n      \"**URL elicitation required**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe agent requires user input via a URL-based elicitation before it can proceed.\",\n    format: \"int32\",\n  }),\n  Schema.Number.annotate({\n    title: \"Other\",\n    description: \"Other undefined error code.\",\n    format: \"int32\",\n  }).check(Schema.isInt()),\n]).annotate({\n  description:\n    \"Predefined error codes for common JSON-RPC and ACP-specific errors.\\n\\nThese codes follow the JSON-RPC 2.0 specification for standard errors\\nand use the reserved range (-32000 to -32099) for protocol-specific errors.\",\n});\n\nexport type ExtNotification = unknown;\nexport const ExtNotification = Schema.Unknown.annotate({\n  description:\n    \"Allows the Agent to send an arbitrary notification that is not part of the ACP spec.\\nExtension notifications provide a way to send one-way messages for custom functionality\\nwhile maintaining protocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n});\n\nexport type ExtRequest = unknown;\nexport const ExtRequest = Schema.Unknown.annotate({\n  description:\n    \"Allows for sending an arbitrary request that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n});\n\nexport type ExtResponse = unknown;\nexport const ExtResponse = Schema.Unknown.annotate({\n  description:\n    \"Allows for sending an arbitrary response to an [`ExtRequest`] that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n});\n\nexport type FileSystemCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly readTextFile?: boolean;\n  readonly writeTextFile?: boolean;\n};\nexport const FileSystemCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  readTextFile: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the Client supports `fs/read_text_file` requests.\",\n      default: false,\n    }),\n  ),\n  writeTextFile: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the Client supports `fs/write_text_file` requests.\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n});\n\nexport type ForkSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers?: ReadonlyArray<McpServer>;\n  readonly sessionId: string;\n};\nexport const ForkSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(McpServer).annotate({\n      description: \"List of MCP servers to connect to for this session.\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for forking an existing session.\\n\\nCreates a new session based on the context of an existing one, allowing\\noperations like generating summaries without affecting the original session's history.\\n\\nOnly available if the Agent supports the `session.fork` capability.\",\n});\n\nexport type ForkSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n  readonly sessionId: string;\n};\nexport const ForkSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from forking an existing session.\",\n});\n\nexport type ImageContent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly data: string;\n  readonly mimeType: string;\n  readonly uri?: string | null;\n};\nexport const ImageContent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  data: Schema.String,\n  mimeType: Schema.String,\n  uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"An image provided to or from an LLM.\" });\n\nexport type InitializeRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly clientCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly auth?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly terminal?: boolean;\n    };\n    readonly elicitation?: ElicitationCapabilities | null;\n    readonly fs?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly readTextFile?: boolean;\n      readonly writeTextFile?: boolean;\n    };\n    readonly terminal?: boolean;\n  };\n  readonly clientInfo?: Implementation | null;\n  readonly protocolVersion: number;\n};\nexport const InitializeRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  clientCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      auth: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          terminal: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description:\n                \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n          default: { terminal: false },\n        }),\n      ),\n      elicitation: Schema.optionalKey(\n        Schema.Union([ElicitationCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\\nDetermines which elicitation modes the agent may use.\",\n        }),\n      ),\n      fs: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          readTextFile: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Whether the Client supports `fs/read_text_file` requests.\",\n              default: false,\n            }),\n          ),\n          writeTextFile: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Whether the Client supports `fs/write_text_file` requests.\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description:\n            \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n          default: { readTextFile: false, writeTextFile: false },\n        }),\n      ),\n      terminal: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the Client support all `terminal/*` methods.\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent about\\navailable features and methods.\\n\\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)\",\n      default: {\n        auth: { terminal: false },\n        fs: { readTextFile: false, writeTextFile: false },\n        terminal: false,\n      },\n    }),\n  ),\n  clientInfo: Schema.optionalKey(\n    Schema.Union([Implementation, Schema.Null]).annotate({\n      description:\n        \"Information about the Client name and version sent to the Agent.\\n\\nNote: in future versions of the protocol, this will be required.\",\n    }),\n  ),\n  protocolVersion: Schema.Number.annotate({\n    description:\n      \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0))\n    .check(Schema.isLessThanOrEqualTo(65535)),\n}).annotate({\n  description:\n    \"Request parameters for the initialize method.\\n\\nSent by the client to establish connection and negotiate capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n});\n\nexport type InitializeResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly agentCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly auth?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly logout?: LogoutCapabilities | null;\n    };\n    readonly loadSession?: boolean;\n    readonly mcpCapabilities?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly http?: boolean;\n      readonly sse?: boolean;\n    };\n    readonly promptCapabilities?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly audio?: boolean;\n      readonly embeddedContext?: boolean;\n      readonly image?: boolean;\n    };\n    readonly sessionCapabilities?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly close?: SessionCloseCapabilities | null;\n      readonly fork?: SessionForkCapabilities | null;\n      readonly list?: SessionListCapabilities | null;\n      readonly resume?: SessionResumeCapabilities | null;\n    };\n  };\n  readonly agentInfo?: Implementation | null;\n  readonly authMethods?: ReadonlyArray<AuthMethod>;\n  readonly protocolVersion: number;\n};\nexport const InitializeResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      auth: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          logout: Schema.optionalKey(\n            Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n              description:\n                \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n            }),\n          ),\n        }).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n          default: {},\n        }),\n      ),\n      loadSession: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the agent supports `session/load`.\",\n          default: false,\n        }),\n      ),\n      mcpCapabilities: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          http: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`McpServer::Http`].\",\n              default: false,\n            }),\n          ),\n          sse: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`McpServer::Sse`].\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description: \"MCP capabilities supported by the agent\",\n          default: { http: false, sse: false },\n        }),\n      ),\n      promptCapabilities: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          audio: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`ContentBlock::Audio`].\",\n              default: false,\n            }),\n          ),\n          embeddedContext: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description:\n                \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n              default: false,\n            }),\n          ),\n          image: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`ContentBlock::Image`].\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description:\n            \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n          default: { audio: false, embeddedContext: false, image: false },\n        }),\n      ),\n      sessionCapabilities: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          close: Schema.optionalKey(\n            Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n            }),\n          ),\n          fork: Schema.optionalKey(\n            Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n            }),\n          ),\n          list: Schema.optionalKey(\n            Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n              description: \"Whether the agent supports `session/list`.\",\n            }),\n          ),\n          resume: Schema.optionalKey(\n            Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n            }),\n          ),\n        }).annotate({\n          default: {},\n          description:\n            \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Capabilities supported by the agent.\\n\\nAdvertised during initialization to inform the client about\\navailable features and content types.\\n\\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)\",\n      default: {\n        auth: {},\n        loadSession: false,\n        mcpCapabilities: { http: false, sse: false },\n        promptCapabilities: { audio: false, embeddedContext: false, image: false },\n        sessionCapabilities: {},\n      },\n    }),\n  ),\n  agentInfo: Schema.optionalKey(\n    Schema.Union([Implementation, Schema.Null]).annotate({\n      description:\n        \"Information about the Agent name and version sent to the Client.\\n\\nNote: in future versions of the protocol, this will be required.\",\n    }),\n  ),\n  authMethods: Schema.optionalKey(\n    Schema.Array(AuthMethod).annotate({\n      description: \"Authentication methods supported by the agent.\",\n      default: [],\n    }),\n  ),\n  protocolVersion: Schema.Number.annotate({\n    description:\n      \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0))\n    .check(Schema.isLessThanOrEqualTo(65535)),\n}).annotate({\n  description:\n    \"Response to the `initialize` method.\\n\\nContains the negotiated protocol version and agent capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n});\n\nexport type IntegerPropertySchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n};\nexport const IntegerPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Default value.\", format: \"int64\" }).check(\n        Schema.isInt(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum value (inclusive).\", format: \"int64\" }).check(\n        Schema.isInt(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Minimum value (inclusive).\", format: \"int64\" }).check(\n        Schema.isInt(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Schema for integer properties in an elicitation form.\" });\n\nexport type KillTerminalRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const KillTerminalRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to kill.\" }),\n}).annotate({ description: \"Request to kill a terminal without releasing it.\" });\n\nexport type KillTerminalResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const KillTerminalResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to `terminal/kill` method\" });\n\nexport type ListSessionsRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cursor?: string | null;\n  readonly cwd?: string | null;\n};\nexport const ListSessionsRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor token from a previous response's nextCursor field for cursor-based pagination\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Filter sessions by working directory. Must be an absolute path.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Request parameters for listing existing sessions.\\n\\nOnly available if the Agent supports the `sessionCapabilities.list` capability.\",\n});\n\nexport type ListSessionsResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly nextCursor?: string | null;\n  readonly sessions: ReadonlyArray<SessionInfo>;\n};\nexport const ListSessionsResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor token. If present, pass this in the next request's cursor parameter\\nto fetch the next page. If absent, there are no more results.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessions: Schema.Array(SessionInfo).annotate({\n    description: \"Array of session information objects\",\n  }),\n}).annotate({ description: \"Response from listing sessions.\" });\n\nexport type LoadSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers: ReadonlyArray<McpServer>;\n  readonly sessionId: string;\n};\nexport const LoadSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n  mcpServers: Schema.Array(McpServer).annotate({\n    description: \"List of MCP servers to connect to for this session.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for loading an existing session.\\n\\nOnly available if the Agent supports the `loadSession` capability.\\n\\nSee protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)\",\n});\n\nexport type LoadSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n};\nexport const LoadSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n}).annotate({ description: \"Response from loading an existing session.\" });\n\nexport type LogoutRequest = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const LogoutRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for the logout method.\\n\\nTerminates the current authenticated session.\",\n});\n\nexport type LogoutResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const LogoutResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to the `logout` method.\",\n});\n\nexport type McpCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly http?: boolean;\n  readonly sse?: boolean;\n};\nexport const McpCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  http: Schema.optionalKey(\n    Schema.Boolean.annotate({ description: \"Agent supports [`McpServer::Http`].\", default: false }),\n  ),\n  sse: Schema.optionalKey(\n    Schema.Boolean.annotate({ description: \"Agent supports [`McpServer::Sse`].\", default: false }),\n  ),\n}).annotate({ description: \"MCP capabilities supported by the agent\" });\n\nexport type McpServerHttp = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly headers: ReadonlyArray<HttpHeader>;\n  readonly name: string;\n  readonly url: string;\n};\nexport const McpServerHttp = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  headers: Schema.Array(HttpHeader).annotate({\n    description: \"HTTP headers to set when making requests to the MCP server.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name identifying this MCP server.\" }),\n  url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n}).annotate({ description: \"HTTP transport configuration for MCP.\" });\n\nexport type McpServerSse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly headers: ReadonlyArray<HttpHeader>;\n  readonly name: string;\n  readonly url: string;\n};\nexport const McpServerSse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  headers: Schema.Array(HttpHeader).annotate({\n    description: \"HTTP headers to set when making requests to the MCP server.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name identifying this MCP server.\" }),\n  url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n}).annotate({ description: \"SSE transport configuration for MCP.\" });\n\nexport type McpServerStdio = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly args: ReadonlyArray<string>;\n  readonly command: string;\n  readonly env: ReadonlyArray<EnvVariable>;\n  readonly name: string;\n};\nexport const McpServerStdio = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  args: Schema.Array(Schema.String).annotate({\n    description: \"Command-line arguments to pass to the MCP server.\",\n  }),\n  command: Schema.String.annotate({ description: \"Path to the MCP server executable.\" }),\n  env: Schema.Array(EnvVariable).annotate({\n    description: \"Environment variables to set when launching the MCP server.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name identifying this MCP server.\" }),\n}).annotate({ description: \"Stdio transport configuration for MCP.\" });\n\nexport type ModelId = string;\nexport const ModelId = Schema.String.annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n});\n\nexport type MultiSelectItems =\n  | { readonly enum: ReadonlyArray<string>; readonly type: \"string\" }\n  | { readonly anyOf: ReadonlyArray<EnumOption> };\nexport const MultiSelectItems = Schema.Union([\n  Schema.Struct({\n    enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n    type: Schema.Literal(\"string\").annotate({\n      description: \"Items definition for untitled multi-select enum properties.\",\n    }),\n  }).annotate({\n    title: \"Untitled\",\n    description: \"Items definition for untitled multi-select enum properties.\",\n  }),\n  Schema.Struct({\n    anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n  }).annotate({\n    title: \"Titled\",\n    description: \"Items definition for titled multi-select enum properties.\",\n  }),\n]).annotate({ description: \"Items for a multi-select (array) property schema.\" });\n\nexport type MultiSelectPropertySchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items:\n    | { readonly enum: ReadonlyArray<string>; readonly type: \"string\" }\n    | { readonly anyOf: ReadonlyArray<EnumOption> };\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n};\nexport const MultiSelectPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({ description: \"Default selected values.\" }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  items: Schema.Union([\n    Schema.Struct({\n      enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n      type: Schema.Literal(\"string\").annotate({\n        description: \"Items definition for untitled multi-select enum properties.\",\n      }),\n    }).annotate({\n      title: \"Untitled\",\n      description: \"Items definition for untitled multi-select enum properties.\",\n    }),\n    Schema.Struct({\n      anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n    }).annotate({\n      title: \"Titled\",\n      description: \"Items definition for titled multi-select enum properties.\",\n    }),\n  ]).annotate({ description: \"Items for a multi-select (array) property schema.\" }),\n  maxItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Maximum number of items to select.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Minimum number of items to select.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Schema for multi-select (array) properties in an elicitation form.\" });\n\nexport type NewSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers: ReadonlyArray<McpServer>;\n};\nexport const NewSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({\n    description: \"The working directory for this session. Must be an absolute path.\",\n  }),\n  mcpServers: Schema.Array(McpServer).annotate({\n    description: \"List of MCP (Model Context Protocol) servers the agent should connect to.\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n});\n\nexport type NewSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n  readonly sessionId: string;\n};\nexport const NewSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Response from creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n});\n\nexport type NumberPropertySchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n};\nexport const NumberPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Default value.\", format: \"double\" }).check(\n        Schema.isFinite(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum value (inclusive).\", format: \"double\" }).check(\n        Schema.isFinite(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Minimum value (inclusive).\", format: \"double\" }).check(\n        Schema.isFinite(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description: \"Schema for number (floating-point) properties in an elicitation form.\",\n});\n\nexport type PermissionOptionId = string;\nexport const PermissionOptionId = Schema.String.annotate({\n  description: \"Unique identifier for a permission option.\",\n});\n\nexport type PermissionOptionKind = \"allow_once\" | \"allow_always\" | \"reject_once\" | \"reject_always\";\nexport const PermissionOptionKind = Schema.Literals([\n  \"allow_once\",\n  \"allow_always\",\n  \"reject_once\",\n  \"reject_always\",\n]).annotate({\n  description:\n    \"The type of permission option being presented to the user.\\n\\nHelps clients choose appropriate icons and UI treatment.\",\n});\n\nexport type Plan = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly entries: ReadonlyArray<PlanEntry>;\n};\nexport const Plan = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  entries: Schema.Array(PlanEntry).annotate({\n    description:\n      \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n  }),\n}).annotate({\n  description:\n    \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n});\n\nexport type PlanEntryPriority = \"high\" | \"medium\" | \"low\";\nexport const PlanEntryPriority = Schema.Literals([\"high\", \"medium\", \"low\"]).annotate({\n  description:\n    \"Priority levels for plan entries.\\n\\nUsed to indicate the relative importance or urgency of different\\ntasks in the execution plan.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n});\n\nexport type PlanEntryStatus = \"pending\" | \"in_progress\" | \"completed\";\nexport const PlanEntryStatus = Schema.Literals([\"pending\", \"in_progress\", \"completed\"]).annotate({\n  description:\n    \"Status of a plan entry in the execution flow.\\n\\nTracks the lifecycle of each task from planning through completion.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n});\n\nexport type PromptCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly audio?: boolean;\n  readonly embeddedContext?: boolean;\n  readonly image?: boolean;\n};\nexport const PromptCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  audio: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Agent supports [`ContentBlock::Audio`].\",\n      default: false,\n    }),\n  ),\n  embeddedContext: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n      default: false,\n    }),\n  ),\n  image: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Agent supports [`ContentBlock::Image`].\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n});\n\nexport type PromptRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly messageId?: string | null;\n  readonly prompt: ReadonlyArray<ContentBlock>;\n  readonly sessionId: string;\n};\nexport const PromptRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  messageId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA client-generated unique identifier for this user message.\\n\\nIf provided, the Agent SHOULD echo this value as `userMessageId` in the\\n[`PromptResponse`] to confirm it was recorded.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  prompt: Schema.Array(ContentBlock).annotate({\n    description:\n      \"The blocks of content that compose the user's message.\\n\\nAs a baseline, the Agent MUST support [`ContentBlock::Text`] and [`ContentBlock::ResourceLink`],\\nwhile other variants are optionally enabled via [`PromptCapabilities`].\\n\\nThe Client MUST adapt its interface according to [`PromptCapabilities`].\\n\\nThe client MAY include referenced pieces of context as either\\n[`ContentBlock::Resource`] or [`ContentBlock::ResourceLink`].\\n\\nWhen available, [`ContentBlock::Resource`] is preferred\\nas it avoids extra round-trips and allows the message to include\\npieces of context from sources the agent may not have access to.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for sending a user prompt to the agent.\\n\\nContains the user's message and any additional context.\\n\\nSee protocol docs: [User Message](https://agentclientprotocol.com/protocol/prompt-turn#1-user-message)\",\n});\n\nexport type PromptResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly stopReason: \"end_turn\" | \"max_tokens\" | \"max_turn_requests\" | \"refusal\" | \"cancelled\";\n  readonly usage?: Usage | null;\n  readonly userMessageId?: string | null;\n};\nexport const PromptResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  stopReason: Schema.Literals([\n    \"end_turn\",\n    \"max_tokens\",\n    \"max_turn_requests\",\n    \"refusal\",\n    \"cancelled\",\n  ]).annotate({\n    description:\n      \"Reasons why an agent stops processing a prompt turn.\\n\\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)\",\n  }),\n  usage: Schema.optionalKey(\n    Schema.Union([Usage, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nToken usage for this turn (optional).\",\n    }),\n  ),\n  userMessageId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe acknowledged user message ID.\\n\\nIf the client provided a `messageId` in the [`PromptRequest`], the agent echoes it here\\nto confirm it was recorded. If the client did not provide one, the agent MAY assign one\\nand return it here. Absence of this field indicates the agent did not record a message ID.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Response from processing a user prompt.\\n\\nSee protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/prompt-turn#4-check-for-completion)\",\n});\n\nexport type ProtocolVersion = number;\nexport const ProtocolVersion = Schema.Number.annotate({\n  description:\n    \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n  format: \"uint16\",\n})\n  .check(Schema.isInt())\n  .check(Schema.isGreaterThanOrEqualTo(0))\n  .check(Schema.isLessThanOrEqualTo(65535));\n\nexport type ReadTextFileRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly limit?: number | null;\n  readonly line?: number | null;\n  readonly path: string;\n  readonly sessionId: string;\n};\nexport const ReadTextFileRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum number of lines to read.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  line: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Line number to start reading from (1-based).\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({ description: \"Absolute path to the file to read.\" }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request to read content from a text file.\\n\\nOnly available if the client supports the `fs.readTextFile` capability.\",\n});\n\nexport type ReadTextFileResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content: string;\n};\nexport const ReadTextFileResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.String,\n}).annotate({ description: \"Response containing the contents of a text file.\" });\n\nexport type ReleaseTerminalRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const ReleaseTerminalRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to release.\" }),\n}).annotate({ description: \"Request to release a terminal and free its resources.\" });\n\nexport type ReleaseTerminalResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const ReleaseTerminalResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to terminal/release method\" });\n\nexport type RequestPermissionOutcome =\n  | { readonly outcome: \"cancelled\" }\n  | {\n      readonly outcome: \"selected\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly optionId: string;\n    };\nexport const RequestPermissionOutcome = Schema.Union(\n  [\n    Schema.Struct({ outcome: Schema.Literal(\"cancelled\") }).annotate({\n      description:\n        \"The prompt turn was cancelled before the user responded.\\n\\nWhen a client sends a `session/cancel` notification to cancel an ongoing\\nprompt turn, it MUST respond to all pending `session/request_permission`\\nrequests with this `Cancelled` outcome.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n    }),\n    Schema.Struct({\n      outcome: Schema.Literal(\"selected\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      optionId: Schema.String.annotate({\n        description: \"Unique identifier for a permission option.\",\n      }),\n    }).annotate({ description: \"The user selected one of the provided options.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"The outcome of a permission request.\" });\n\nexport type RequestPermissionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly options: ReadonlyArray<PermissionOption>;\n  readonly sessionId: string;\n  readonly toolCall: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly content?: ReadonlyArray<ToolCallContent> | null;\n    readonly kind?: ToolKind | null;\n    readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n    readonly rawInput?: unknown;\n    readonly rawOutput?: unknown;\n    readonly status?: ToolCallStatus | null;\n    readonly title?: string | null;\n    readonly toolCallId: string;\n  };\n};\nexport const RequestPermissionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  options: Schema.Array(PermissionOption).annotate({\n    description: \"Available permission options for the user to choose from.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  toolCall: Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    content: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(ToolCallContent).annotate({ description: \"Replace the content collection.\" }),\n        Schema.Null,\n      ]),\n    ),\n    kind: Schema.optionalKey(\n      Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n    ),\n    locations: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(ToolCallLocation).annotate({\n          description: \"Replace the locations collection.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    rawInput: Schema.optionalKey(Schema.Unknown.annotate({ description: \"Update the raw input.\" })),\n    rawOutput: Schema.optionalKey(\n      Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n    ),\n    status: Schema.optionalKey(\n      Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n        description: \"Update the execution status.\",\n      }),\n    ),\n    title: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n        Schema.Null,\n      ]),\n    ),\n    toolCallId: Schema.String.annotate({\n      description: \"Unique identifier for a tool call within a session.\",\n    }),\n  }).annotate({\n    description:\n      \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n  }),\n}).annotate({\n  description:\n    \"Request for user permission to execute a tool call.\\n\\nSent when the agent needs authorization before performing a sensitive operation.\\n\\nSee protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)\",\n});\n\nexport type RequestPermissionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly outcome:\n    | { readonly outcome: \"cancelled\" }\n    | {\n        readonly outcome: \"selected\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly optionId: string;\n      };\n};\nexport const RequestPermissionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outcome: Schema.Union(\n    [\n      Schema.Struct({ outcome: Schema.Literal(\"cancelled\") }).annotate({\n        description:\n          \"The prompt turn was cancelled before the user responded.\\n\\nWhen a client sends a `session/cancel` notification to cancel an ongoing\\nprompt turn, it MUST respond to all pending `session/request_permission`\\nrequests with this `Cancelled` outcome.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n      }),\n      Schema.Struct({\n        outcome: Schema.Literal(\"selected\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        optionId: Schema.String.annotate({\n          description: \"Unique identifier for a permission option.\",\n        }),\n      }).annotate({ description: \"The user selected one of the provided options.\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"The outcome of a permission request.\" }),\n}).annotate({ description: \"Response to a permission request.\" });\n\nexport type ResourceLink = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly description?: string | null;\n  readonly mimeType?: string | null;\n  readonly name: string;\n  readonly size?: number | null;\n  readonly title?: string | null;\n  readonly uri: string;\n};\nexport const ResourceLink = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  size: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({\n  description:\n    \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n});\n\nexport type ResumeSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers?: ReadonlyArray<McpServer>;\n  readonly sessionId: string;\n};\nexport const ResumeSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(McpServer).annotate({\n      description: \"List of MCP servers to connect to for this session.\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for resuming an existing session.\\n\\nResumes an existing session without returning previous messages (unlike `session/load`).\\nThis is useful for agents that can resume sessions but don't implement full session loading.\\n\\nOnly available if the Agent supports the `session.resume` capability.\",\n});\n\nexport type ResumeSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n};\nexport const ResumeSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from resuming an existing session.\",\n});\n\nexport type SelectedPermissionOutcome = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly optionId: string;\n};\nexport const SelectedPermissionOutcome = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  optionId: Schema.String.annotate({ description: \"Unique identifier for a permission option.\" }),\n}).annotate({ description: \"The user selected one of the provided options.\" });\n\nexport type SessionCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly close?: SessionCloseCapabilities | null;\n  readonly fork?: SessionForkCapabilities | null;\n  readonly list?: SessionListCapabilities | null;\n  readonly resume?: SessionResumeCapabilities | null;\n};\nexport const SessionCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  close: Schema.optionalKey(\n    Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n    }),\n  ),\n  fork: Schema.optionalKey(\n    Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n    }),\n  ),\n  list: Schema.optionalKey(\n    Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n      description: \"Whether the agent supports `session/list`.\",\n    }),\n  ),\n  resume: Schema.optionalKey(\n    Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n});\n\nexport type SessionConfigBoolean = { readonly currentValue: boolean };\nexport const SessionConfigBoolean = Schema.Struct({\n  currentValue: Schema.Boolean.annotate({\n    description: \"The current value of the boolean option.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA boolean on/off toggle session configuration option payload.\",\n});\n\nexport type SessionConfigGroupId = string;\nexport const SessionConfigGroupId = Schema.String.annotate({\n  description: \"Unique identifier for a session configuration option value group.\",\n});\n\nexport type SessionConfigId = string;\nexport const SessionConfigId = Schema.String.annotate({\n  description: \"Unique identifier for a session configuration option.\",\n});\n\nexport type SessionConfigSelect = {\n  readonly currentValue: string;\n  readonly options:\n    | ReadonlyArray<SessionConfigSelectOption>\n    | ReadonlyArray<SessionConfigSelectGroup>;\n};\nexport const SessionConfigSelect = Schema.Struct({\n  currentValue: Schema.String.annotate({\n    description: \"Unique identifier for a session configuration option value.\",\n  }),\n  options: Schema.Union([\n    Schema.Array(SessionConfigSelectOption).annotate({\n      title: \"Ungrouped\",\n      description: \"A flat list of options with no grouping.\",\n    }),\n    Schema.Array(SessionConfigSelectGroup).annotate({\n      title: \"Grouped\",\n      description: \"A list of options grouped under headers.\",\n    }),\n  ]).annotate({ description: \"Possible values for a session configuration option.\" }),\n}).annotate({\n  description: \"A single-value selector (dropdown) session configuration option payload.\",\n});\n\nexport type SessionConfigSelectOptions =\n  | ReadonlyArray<SessionConfigSelectOption>\n  | ReadonlyArray<SessionConfigSelectGroup>;\nexport const SessionConfigSelectOptions = Schema.Union([\n  Schema.Array(SessionConfigSelectOption).annotate({\n    title: \"Ungrouped\",\n    description: \"A flat list of options with no grouping.\",\n  }),\n  Schema.Array(SessionConfigSelectGroup).annotate({\n    title: \"Grouped\",\n    description: \"A list of options grouped under headers.\",\n  }),\n]).annotate({ description: \"Possible values for a session configuration option.\" });\n\nexport type SessionConfigValueId = string;\nexport const SessionConfigValueId = Schema.String.annotate({\n  description: \"Unique identifier for a session configuration option value.\",\n});\n\nexport type SessionId = string;\nexport const SessionId = Schema.String.annotate({\n  description:\n    \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n});\n\nexport type SessionInfoUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly title?: string | null;\n  readonly updatedAt?: string | null;\n};\nexport const SessionInfoUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Human-readable title for the session. Set to null to clear.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  updatedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n});\n\nexport type SessionNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly update:\n    | {\n        readonly sessionUpdate: \"user_message_chunk\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content:\n          | {\n              readonly type: \"text\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly text: string;\n            }\n          | {\n              readonly type: \"image\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n              readonly uri?: string | null;\n            }\n          | {\n              readonly type: \"audio\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n            }\n          | {\n              readonly type: \"resource_link\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly description?: string | null;\n              readonly mimeType?: string | null;\n              readonly name: string;\n              readonly size?: number | null;\n              readonly title?: string | null;\n              readonly uri: string;\n            }\n          | {\n              readonly type: \"resource\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly resource: EmbeddedResourceResource;\n            };\n        readonly messageId?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"agent_message_chunk\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content:\n          | {\n              readonly type: \"text\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly text: string;\n            }\n          | {\n              readonly type: \"image\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n              readonly uri?: string | null;\n            }\n          | {\n              readonly type: \"audio\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n            }\n          | {\n              readonly type: \"resource_link\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly description?: string | null;\n              readonly mimeType?: string | null;\n              readonly name: string;\n              readonly size?: number | null;\n              readonly title?: string | null;\n              readonly uri: string;\n            }\n          | {\n              readonly type: \"resource\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly resource: EmbeddedResourceResource;\n            };\n        readonly messageId?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"agent_thought_chunk\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content:\n          | {\n              readonly type: \"text\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly text: string;\n            }\n          | {\n              readonly type: \"image\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n              readonly uri?: string | null;\n            }\n          | {\n              readonly type: \"audio\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n            }\n          | {\n              readonly type: \"resource_link\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly description?: string | null;\n              readonly mimeType?: string | null;\n              readonly name: string;\n              readonly size?: number | null;\n              readonly title?: string | null;\n              readonly uri: string;\n            }\n          | {\n              readonly type: \"resource\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly resource: EmbeddedResourceResource;\n            };\n        readonly messageId?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"tool_call\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content?: ReadonlyArray<ToolCallContent>;\n        readonly kind?:\n          | \"read\"\n          | \"edit\"\n          | \"delete\"\n          | \"move\"\n          | \"search\"\n          | \"execute\"\n          | \"think\"\n          | \"fetch\"\n          | \"switch_mode\"\n          | \"other\";\n        readonly locations?: ReadonlyArray<ToolCallLocation>;\n        readonly rawInput?: unknown;\n        readonly rawOutput?: unknown;\n        readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n        readonly title: string;\n        readonly toolCallId: string;\n      }\n    | {\n        readonly sessionUpdate: \"tool_call_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content?: ReadonlyArray<ToolCallContent> | null;\n        readonly kind?: ToolKind | null;\n        readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n        readonly rawInput?: unknown;\n        readonly rawOutput?: unknown;\n        readonly status?: ToolCallStatus | null;\n        readonly title?: string | null;\n        readonly toolCallId: string;\n      }\n    | {\n        readonly sessionUpdate: \"plan\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly entries: ReadonlyArray<PlanEntry>;\n      }\n    | {\n        readonly sessionUpdate: \"available_commands_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly availableCommands: ReadonlyArray<AvailableCommand>;\n      }\n    | {\n        readonly sessionUpdate: \"current_mode_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly currentModeId: string;\n      }\n    | {\n        readonly sessionUpdate: \"config_option_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly configOptions: ReadonlyArray<SessionConfigOption>;\n      }\n    | {\n        readonly sessionUpdate: \"session_info_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly title?: string | null;\n        readonly updatedAt?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"usage_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cost?: Cost | null;\n        readonly size: number;\n        readonly used: number;\n      };\n};\nexport const SessionNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  update: Schema.Union(\n    [\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"user_message_chunk\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.Union(\n          [\n            Schema.Struct({\n              type: Schema.Literal(\"text\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              text: Schema.String,\n            }).annotate({ description: \"Text provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"image\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n              uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            }).annotate({ description: \"An image provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"audio\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n            }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource_link\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              name: Schema.String,\n              size: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              uri: Schema.String,\n            }).annotate({\n              description:\n                \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n            }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              resource: EmbeddedResourceResource,\n            }).annotate({\n              description:\n                \"The contents of a resource, embedded into a prompt or tool call result.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n        }),\n        messageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ description: \"A streamed item of content\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"agent_message_chunk\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.Union(\n          [\n            Schema.Struct({\n              type: Schema.Literal(\"text\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              text: Schema.String,\n            }).annotate({ description: \"Text provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"image\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n              uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            }).annotate({ description: \"An image provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"audio\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n            }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource_link\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              name: Schema.String,\n              size: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              uri: Schema.String,\n            }).annotate({\n              description:\n                \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n            }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              resource: EmbeddedResourceResource,\n            }).annotate({\n              description:\n                \"The contents of a resource, embedded into a prompt or tool call result.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n        }),\n        messageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ description: \"A streamed item of content\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"agent_thought_chunk\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.Union(\n          [\n            Schema.Struct({\n              type: Schema.Literal(\"text\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              text: Schema.String,\n            }).annotate({ description: \"Text provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"image\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n              uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            }).annotate({ description: \"An image provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"audio\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n            }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource_link\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              name: Schema.String,\n              size: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              uri: Schema.String,\n            }).annotate({\n              description:\n                \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n            }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              resource: EmbeddedResourceResource,\n            }).annotate({\n              description:\n                \"The contents of a resource, embedded into a prompt or tool call result.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n        }),\n        messageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ description: \"A streamed item of content\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"tool_call\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.optionalKey(\n          Schema.Array(ToolCallContent).annotate({\n            description: \"Content produced by the tool call.\",\n          }),\n        ),\n        kind: Schema.optionalKey(\n          Schema.Literals([\n            \"read\",\n            \"edit\",\n            \"delete\",\n            \"move\",\n            \"search\",\n            \"execute\",\n            \"think\",\n            \"fetch\",\n            \"switch_mode\",\n            \"other\",\n          ]).annotate({\n            description:\n              \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n          }),\n        ),\n        locations: Schema.optionalKey(\n          Schema.Array(ToolCallLocation).annotate({\n            description:\n              'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n          }),\n        ),\n        rawInput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Raw input parameters sent to the tool.\" }),\n        ),\n        rawOutput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n        ),\n        status: Schema.optionalKey(\n          Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n            description:\n              \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n          }),\n        ),\n        title: Schema.String.annotate({\n          description: \"Human-readable title describing what the tool is doing.\",\n        }),\n        toolCallId: Schema.String.annotate({\n          description: \"Unique identifier for a tool call within a session.\",\n        }),\n      }).annotate({\n        description:\n          \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"tool_call_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(ToolCallContent).annotate({\n              description: \"Replace the content collection.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        kind: Schema.optionalKey(\n          Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n        ),\n        locations: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(ToolCallLocation).annotate({\n              description: \"Replace the locations collection.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        rawInput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n        ),\n        rawOutput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n        ),\n        status: Schema.optionalKey(\n          Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n            description: \"Update the execution status.\",\n          }),\n        ),\n        title: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n            Schema.Null,\n          ]),\n        ),\n        toolCallId: Schema.String.annotate({\n          description: \"Unique identifier for a tool call within a session.\",\n        }),\n      }).annotate({\n        description:\n          \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"plan\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        entries: Schema.Array(PlanEntry).annotate({\n          description:\n            \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n        }),\n      }).annotate({\n        description:\n          \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"available_commands_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        availableCommands: Schema.Array(AvailableCommand).annotate({\n          description: \"Commands the agent can execute\",\n        }),\n      }).annotate({ description: \"Available commands are ready or have changed\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"current_mode_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        currentModeId: Schema.String.annotate({\n          description: \"Unique identifier for a Session Mode.\",\n        }),\n      }).annotate({\n        description:\n          \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"config_option_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.Array(SessionConfigOption).annotate({\n          description: \"The full set of configuration options and their current values.\",\n        }),\n      }).annotate({ description: \"Session configuration options have been updated.\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"session_info_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        title: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description: \"Human-readable title for the session. Set to null to clear.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        updatedAt: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        description:\n          \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"usage_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        cost: Schema.optionalKey(\n          Schema.Union([Cost, Schema.Null]).annotate({\n            description: \"Cumulative session cost (optional).\",\n          }),\n        ),\n        size: Schema.Number.annotate({\n          description: \"Total context window size in tokens.\",\n          format: \"uint64\",\n        })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        used: Schema.Number.annotate({\n          description: \"Tokens currently in context.\",\n          format: \"uint64\",\n        })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      }).annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Different types of updates that can be sent during session processing.\\n\\nThese updates provide real-time feedback about the agent's progress.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n  }),\n}).annotate({\n  description:\n    \"Notification containing a session update from the agent.\\n\\nUsed to stream real-time progress and results during prompt processing.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n});\n\nexport type SessionUpdate =\n  | {\n      readonly sessionUpdate: \"user_message_chunk\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n      readonly messageId?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"agent_message_chunk\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n      readonly messageId?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"agent_thought_chunk\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n      readonly messageId?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"tool_call\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content?: ReadonlyArray<ToolCallContent>;\n      readonly kind?:\n        | \"read\"\n        | \"edit\"\n        | \"delete\"\n        | \"move\"\n        | \"search\"\n        | \"execute\"\n        | \"think\"\n        | \"fetch\"\n        | \"switch_mode\"\n        | \"other\";\n      readonly locations?: ReadonlyArray<ToolCallLocation>;\n      readonly rawInput?: unknown;\n      readonly rawOutput?: unknown;\n      readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n      readonly title: string;\n      readonly toolCallId: string;\n    }\n  | {\n      readonly sessionUpdate: \"tool_call_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content?: ReadonlyArray<ToolCallContent> | null;\n      readonly kind?: ToolKind | null;\n      readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n      readonly rawInput?: unknown;\n      readonly rawOutput?: unknown;\n      readonly status?: ToolCallStatus | null;\n      readonly title?: string | null;\n      readonly toolCallId: string;\n    }\n  | {\n      readonly sessionUpdate: \"plan\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly entries: ReadonlyArray<PlanEntry>;\n    }\n  | {\n      readonly sessionUpdate: \"available_commands_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly availableCommands: ReadonlyArray<AvailableCommand>;\n    }\n  | {\n      readonly sessionUpdate: \"current_mode_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly currentModeId: string;\n    }\n  | {\n      readonly sessionUpdate: \"config_option_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly configOptions: ReadonlyArray<SessionConfigOption>;\n    }\n  | {\n      readonly sessionUpdate: \"session_info_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly title?: string | null;\n      readonly updatedAt?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"usage_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly cost?: Cost | null;\n      readonly size: number;\n      readonly used: number;\n    };\nexport const SessionUpdate = Schema.Union(\n  [\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"user_message_chunk\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n      messageId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"A streamed item of content\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"agent_message_chunk\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n      messageId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"A streamed item of content\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"agent_thought_chunk\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n      messageId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"A streamed item of content\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"tool_call\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.optionalKey(\n        Schema.Array(ToolCallContent).annotate({\n          description: \"Content produced by the tool call.\",\n        }),\n      ),\n      kind: Schema.optionalKey(\n        Schema.Literals([\n          \"read\",\n          \"edit\",\n          \"delete\",\n          \"move\",\n          \"search\",\n          \"execute\",\n          \"think\",\n          \"fetch\",\n          \"switch_mode\",\n          \"other\",\n        ]).annotate({\n          description:\n            \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n        }),\n      ),\n      locations: Schema.optionalKey(\n        Schema.Array(ToolCallLocation).annotate({\n          description:\n            'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n        }),\n      ),\n      rawInput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Raw input parameters sent to the tool.\" }),\n      ),\n      rawOutput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n      ),\n      status: Schema.optionalKey(\n        Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n          description:\n            \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n        }),\n      ),\n      title: Schema.String.annotate({\n        description: \"Human-readable title describing what the tool is doing.\",\n      }),\n      toolCallId: Schema.String.annotate({\n        description: \"Unique identifier for a tool call within a session.\",\n      }),\n    }).annotate({\n      description:\n        \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"tool_call_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(ToolCallContent).annotate({\n            description: \"Replace the content collection.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      kind: Schema.optionalKey(\n        Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n      ),\n      locations: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(ToolCallLocation).annotate({\n            description: \"Replace the locations collection.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      rawInput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n      ),\n      rawOutput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n      ),\n      status: Schema.optionalKey(\n        Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n          description: \"Update the execution status.\",\n        }),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n          Schema.Null,\n        ]),\n      ),\n      toolCallId: Schema.String.annotate({\n        description: \"Unique identifier for a tool call within a session.\",\n      }),\n    }).annotate({\n      description:\n        \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"plan\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      entries: Schema.Array(PlanEntry).annotate({\n        description:\n          \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n      }),\n    }).annotate({\n      description:\n        \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"available_commands_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      availableCommands: Schema.Array(AvailableCommand).annotate({\n        description: \"Commands the agent can execute\",\n      }),\n    }).annotate({ description: \"Available commands are ready or have changed\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"current_mode_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      currentModeId: Schema.String.annotate({\n        description: \"Unique identifier for a Session Mode.\",\n      }),\n    }).annotate({\n      description:\n        \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"config_option_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      configOptions: Schema.Array(SessionConfigOption).annotate({\n        description: \"The full set of configuration options and their current values.\",\n      }),\n    }).annotate({ description: \"Session configuration options have been updated.\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"session_info_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Human-readable title for the session. Set to null to clear.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      updatedAt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description:\n        \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"usage_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      cost: Schema.optionalKey(\n        Schema.Union([Cost, Schema.Null]).annotate({\n          description: \"Cumulative session cost (optional).\",\n        }),\n      ),\n      size: Schema.Number.annotate({\n        description: \"Total context window size in tokens.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      used: Schema.Number.annotate({\n        description: \"Tokens currently in context.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Different types of updates that can be sent during session processing.\\n\\nThese updates provide real-time feedback about the agent's progress.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n});\n\nexport type SetSessionConfigOptionRequest =\n  | {\n      readonly type: \"boolean\";\n      readonly value: boolean;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly configId: string;\n      readonly sessionId: string;\n    }\n  | {\n      readonly value: string;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly configId: string;\n      readonly sessionId: string;\n    };\nexport const SetSessionConfigOptionRequest = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"boolean\"),\n    value: Schema.Boolean.annotate({ description: \"The boolean value.\" }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    configId: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({ description: \"Request parameters for setting a session configuration option.\" }),\n  Schema.Struct({\n    value: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option value.\",\n    }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    configId: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({\n    title: \"value_id\",\n    description: \"Request parameters for setting a session configuration option.\",\n  }),\n]);\n\nexport type SetSessionConfigOptionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions: ReadonlyArray<SessionConfigOption>;\n};\nexport const SetSessionConfigOptionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.Array(SessionConfigOption).annotate({\n    description: \"The full set of configuration options and their current values.\",\n  }),\n}).annotate({ description: \"Response to `session/set_config_option` method.\" });\n\nexport type SetSessionModelRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly modelId: string;\n  readonly sessionId: string;\n};\nexport const SetSessionModelRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for setting a session model.\",\n});\n\nexport type SetSessionModelResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SetSessionModelResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to `session/set_model` method.\",\n});\n\nexport type SetSessionModeRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly modeId: string;\n  readonly sessionId: string;\n};\nexport const SetSessionModeRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({ description: \"Request parameters for setting a session mode.\" });\n\nexport type SetSessionModeResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SetSessionModeResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to `session/set_mode` method.\" });\n\nexport type StopReason = \"end_turn\" | \"max_tokens\" | \"max_turn_requests\" | \"refusal\" | \"cancelled\";\nexport const StopReason = Schema.Literals([\n  \"end_turn\",\n  \"max_tokens\",\n  \"max_turn_requests\",\n  \"refusal\",\n  \"cancelled\",\n]).annotate({\n  description:\n    \"Reasons why an agent stops processing a prompt turn.\\n\\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)\",\n});\n\nexport type StringPropertySchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum?: ReadonlyArray<string> | null;\n  readonly format?: StringFormat | null;\n  readonly maxLength?: number | null;\n  readonly minLength?: number | null;\n  readonly oneOf?: ReadonlyArray<EnumOption> | null;\n  readonly pattern?: string | null;\n  readonly title?: string | null;\n};\nexport const StringPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([Schema.String.annotate({ description: \"Default value.\" }), Schema.Null]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  enum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Enum values for untitled single-select enums.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  format: Schema.optionalKey(\n    Schema.Union([StringFormat, Schema.Null]).annotate({ description: \"String format.\" }),\n  ),\n  maxLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum string length.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Minimum string length.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  oneOf: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(EnumOption).annotate({\n        description: \"Titled enum options for titled single-select enums.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  pattern: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Pattern the string must match.\" }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    'Schema for string properties in an elicitation form.\\n\\nWhen `enum` or `oneOf` is set, this represents a single-select enum\\nwith `\"type\": \"string\"`.',\n});\n\nexport type Terminal = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly terminalId: string;\n};\nexport const Terminal = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  terminalId: Schema.String,\n}).annotate({\n  description:\n    \"Embed a terminal created with `terminal/create` by its id.\\n\\nThe terminal must be added before calling `terminal/release`.\\n\\nSee protocol docs: [Terminal](https://agentclientprotocol.com/protocol/terminals)\",\n});\n\nexport type TerminalOutputRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const TerminalOutputRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to get output from.\" }),\n}).annotate({ description: \"Request to get the current output and status of a terminal.\" });\n\nexport type TerminalOutputResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly exitStatus?: TerminalExitStatus | null;\n  readonly output: string;\n  readonly truncated: boolean;\n};\nexport const TerminalOutputResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  exitStatus: Schema.optionalKey(\n    Schema.Union([TerminalExitStatus, Schema.Null]).annotate({\n      description: \"Exit status if the command has completed.\",\n    }),\n  ),\n  output: Schema.String.annotate({ description: \"The terminal output captured so far.\" }),\n  truncated: Schema.Boolean.annotate({\n    description: \"Whether the output was truncated due to byte limits.\",\n  }),\n}).annotate({ description: \"Response containing the terminal output and exit status.\" });\n\nexport type TextContent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly text: string;\n};\nexport const TextContent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  text: Schema.String,\n}).annotate({ description: \"Text provided to or from an LLM.\" });\n\nexport type TextResourceContents = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly mimeType?: string | null;\n  readonly text: string;\n  readonly uri: string;\n};\nexport const TextResourceContents = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  text: Schema.String,\n  uri: Schema.String,\n}).annotate({ description: \"Text-based resource contents.\" });\n\nexport type TitledMultiSelectItems = { readonly anyOf: ReadonlyArray<EnumOption> };\nexport const TitledMultiSelectItems = Schema.Struct({\n  anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n}).annotate({ description: \"Items definition for titled multi-select enum properties.\" });\n\nexport type ToolCall = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content?: ReadonlyArray<ToolCallContent>;\n  readonly kind?:\n    | \"read\"\n    | \"edit\"\n    | \"delete\"\n    | \"move\"\n    | \"search\"\n    | \"execute\"\n    | \"think\"\n    | \"fetch\"\n    | \"switch_mode\"\n    | \"other\";\n  readonly locations?: ReadonlyArray<ToolCallLocation>;\n  readonly rawInput?: unknown;\n  readonly rawOutput?: unknown;\n  readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n  readonly title: string;\n  readonly toolCallId: string;\n};\nexport const ToolCall = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.optionalKey(\n    Schema.Array(ToolCallContent).annotate({ description: \"Content produced by the tool call.\" }),\n  ),\n  kind: Schema.optionalKey(\n    Schema.Literals([\n      \"read\",\n      \"edit\",\n      \"delete\",\n      \"move\",\n      \"search\",\n      \"execute\",\n      \"think\",\n      \"fetch\",\n      \"switch_mode\",\n      \"other\",\n    ]).annotate({\n      description:\n        \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n    }),\n  ),\n  locations: Schema.optionalKey(\n    Schema.Array(ToolCallLocation).annotate({\n      description:\n        'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n    }),\n  ),\n  rawInput: Schema.optionalKey(\n    Schema.Unknown.annotate({ description: \"Raw input parameters sent to the tool.\" }),\n  ),\n  rawOutput: Schema.optionalKey(\n    Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n  ),\n  status: Schema.optionalKey(\n    Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n      description:\n        \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n    }),\n  ),\n  title: Schema.String.annotate({\n    description: \"Human-readable title describing what the tool is doing.\",\n  }),\n  toolCallId: Schema.String.annotate({\n    description: \"Unique identifier for a tool call within a session.\",\n  }),\n}).annotate({\n  description:\n    \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n});\n\nexport type ToolCallId = string;\nexport const ToolCallId = Schema.String.annotate({\n  description: \"Unique identifier for a tool call within a session.\",\n});\n\nexport type ToolCallUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content?: ReadonlyArray<ToolCallContent> | null;\n  readonly kind?: ToolKind | null;\n  readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n  readonly rawInput?: unknown;\n  readonly rawOutput?: unknown;\n  readonly status?: ToolCallStatus | null;\n  readonly title?: string | null;\n  readonly toolCallId: string;\n};\nexport const ToolCallUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ToolCallContent).annotate({ description: \"Replace the content collection.\" }),\n      Schema.Null,\n    ]),\n  ),\n  kind: Schema.optionalKey(\n    Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n  ),\n  locations: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ToolCallLocation).annotate({ description: \"Replace the locations collection.\" }),\n      Schema.Null,\n    ]),\n  ),\n  rawInput: Schema.optionalKey(Schema.Unknown.annotate({ description: \"Update the raw input.\" })),\n  rawOutput: Schema.optionalKey(Schema.Unknown.annotate({ description: \"Update the raw output.\" })),\n  status: Schema.optionalKey(\n    Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n      description: \"Update the execution status.\",\n    }),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  toolCallId: Schema.String.annotate({\n    description: \"Unique identifier for a tool call within a session.\",\n  }),\n}).annotate({\n  description:\n    \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n});\n\nexport type UnstructuredCommandInput = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly hint: string;\n};\nexport const UnstructuredCommandInput = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  hint: Schema.String.annotate({\n    description: \"A hint to display when the input hasn't been provided yet\",\n  }),\n}).annotate({\n  description: \"All text that was typed after the command name is provided as input.\",\n});\n\nexport type UntitledMultiSelectItems = {\n  readonly enum: ReadonlyArray<string>;\n  readonly type: \"string\";\n};\nexport const UntitledMultiSelectItems = Schema.Struct({\n  enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n  type: Schema.Literal(\"string\").annotate({\n    description: \"Items definition for untitled multi-select enum properties.\",\n  }),\n}).annotate({ description: \"Items definition for untitled multi-select enum properties.\" });\n\nexport type UsageUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cost?: Cost | null;\n  readonly size: number;\n  readonly used: number;\n};\nexport const UsageUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cost: Schema.optionalKey(\n    Schema.Union([Cost, Schema.Null]).annotate({\n      description: \"Cumulative session cost (optional).\",\n    }),\n  ),\n  size: Schema.Number.annotate({\n    description: \"Total context window size in tokens.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  used: Schema.Number.annotate({ description: \"Tokens currently in context.\", format: \"uint64\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n});\n\nexport type WaitForTerminalExitRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const WaitForTerminalExitRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to wait for.\" }),\n}).annotate({ description: \"Request to wait for a terminal command to exit.\" });\n\nexport type WaitForTerminalExitResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly exitCode?: number | null;\n  readonly signal?: string | null;\n};\nexport const WaitForTerminalExitResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  exitCode: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"The process exit code (may be null if terminated by signal).\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  signal: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"The signal that terminated the process (may be null if exited normally).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response containing the exit status of a terminal command.\" });\n\nexport type WriteTextFileRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content: string;\n  readonly path: string;\n  readonly sessionId: string;\n};\nexport const WriteTextFileRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.String.annotate({ description: \"The text content to write to the file.\" }),\n  path: Schema.String.annotate({ description: \"Absolute path to the file to write.\" }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request to write content to a text file.\\n\\nOnly available if the client supports the `fs.writeTextFile` capability.\",\n});\n\nexport type WriteTextFileResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const WriteTextFileResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to `fs/write_text_file`\" });\n","import * as Schema from \"effect/Schema\";\nimport type * as SchemaIssue from \"effect/SchemaIssue\";\n\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\n\nexport const AcpRequestOperation = Schema.Literals([\n  \"decode-extension-request-payload\",\n  \"encode-extension-response\",\n  \"handle-request\",\n  \"handle-extension-request\",\n  \"receive-response\",\n  \"receive-streaming-response\",\n]);\nexport type AcpRequestOperation = typeof AcpRequestOperation.Type;\n\nexport const AcpRequestId = Schema.Union([Schema.String, Schema.Number]);\nexport type AcpRequestId = typeof AcpRequestId.Type;\n\nexport const AcpSchemaIssueKind = Schema.Literals([\n  \"Filter\",\n  \"Encoding\",\n  \"Pointer\",\n  \"Composite\",\n  \"AnyOf\",\n  \"InvalidType\",\n  \"InvalidValue\",\n  \"MissingKey\",\n  \"UnexpectedKey\",\n  \"Forbidden\",\n  \"OneOf\",\n]);\nexport type AcpSchemaIssueKind = typeof AcpSchemaIssueKind.Type;\n\nexport interface AcpSchemaIssueDiagnostics {\n  readonly issueCount: number;\n  readonly issueKinds: ReadonlyArray<AcpSchemaIssueKind>;\n  readonly maximumPathDepth: number;\n}\n\nconst schemaIssueDiagnostics = (root: SchemaIssue.Issue): AcpSchemaIssueDiagnostics => {\n  let issueCount = 0;\n  let maximumPathDepth = 0;\n  const issueKinds = new Set<AcpSchemaIssueKind>();\n\n  const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {\n    issueCount += 1;\n    issueKinds.add(issue._tag);\n    maximumPathDepth = Math.max(maximumPathDepth, pathDepth);\n    switch (issue._tag) {\n      case \"Filter\":\n      case \"Encoding\":\n        visit(issue.issue, pathDepth);\n        break;\n      case \"Pointer\":\n        visit(issue.issue, pathDepth + issue.path.length);\n        break;\n      case \"Composite\":\n      case \"AnyOf\":\n        for (const child of issue.issues) visit(child, pathDepth);\n        break;\n    }\n  };\n\n  visit(root, 0);\n  return {\n    issueCount,\n    issueKinds: [...issueKinds],\n    maximumPathDepth,\n  };\n};\n\nexport interface AcpRequestDiagnostics {\n  readonly method?: string;\n  readonly requestId?: AcpRequestId;\n  readonly operation?: AcpRequestOperation;\n  readonly cause?: unknown;\n  readonly issueCount?: number;\n  readonly issueKinds?: ReadonlyArray<AcpSchemaIssueKind>;\n  readonly maximumPathDepth?: number;\n}\n\nexport class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()(\"AcpSpawnError\", {\n  command: Schema.optional(Schema.String),\n  cause: Schema.Defect(),\n}) {\n  override get message() {\n    return this.command\n      ? `Failed to spawn ACP process for command: ${this.command}`\n      : \"Failed to spawn ACP process\";\n  }\n}\n\nexport class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(\n  \"AcpProcessExitedError\",\n  {\n    code: Schema.optional(Schema.Number),\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return this.code === undefined\n      ? \"ACP process exited\"\n      : `ACP process exited with code ${this.code}`;\n  }\n}\n\nexport const AcpProtocolParseOperation = Schema.Literals([\n  \"encode-message\",\n  \"decode-wire-message\",\n  \"decode-notification-payload\",\n  \"decode-rpc-result\",\n]);\nexport type AcpProtocolParseOperation = typeof AcpProtocolParseOperation.Type;\n\nexport class AcpProtocolParseError extends Schema.TaggedErrorClass<AcpProtocolParseError>()(\n  \"AcpProtocolParseError\",\n  {\n    operation: AcpProtocolParseOperation,\n    method: Schema.optionalKey(Schema.String),\n    requestId: Schema.optionalKey(AcpRequestId),\n    issueCount: Schema.optionalKey(Schema.Number),\n    issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),\n    maximumPathDepth: Schema.optionalKey(Schema.Number),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    const method = this.method === undefined ? \"\" : ` for method '${this.method}'`;\n    return `ACP protocol operation '${this.operation}' failed${method}.`;\n  }\n\n  static fromSchemaError(\n    operation: AcpProtocolParseOperation,\n    method: string,\n    cause: Schema.SchemaError,\n  ) {\n    return new AcpProtocolParseError({\n      operation,\n      method,\n      ...schemaIssueDiagnostics(cause.issue),\n      cause,\n    });\n  }\n\n  static fromEncodingError(\n    method: string | undefined,\n    requestId: AcpRequestId | undefined,\n    cause: unknown,\n  ) {\n    return new AcpProtocolParseError({\n      operation: \"encode-message\",\n      ...(method === undefined ? {} : { method }),\n      ...(requestId === undefined ? {} : { requestId }),\n      cause,\n    });\n  }\n}\n\nexport class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError>()(\n  \"AcpTransportError\",\n  {\n    operation: Schema.optional(\n      Schema.Literals([\"call-rpc\", \"read-input-stream\", \"read-process-exit-status\"]),\n    ),\n    method: Schema.optional(Schema.String),\n    detail: Schema.optional(Schema.String),\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    const method = this.method ? ` for method ${this.method}` : \"\";\n    return this.operation\n      ? `ACP transport operation ${this.operation} failed${method}.`\n      : \"ACP transport operation failed.\";\n  }\n}\n\nexport class AcpInputStreamEndedError extends Schema.TaggedErrorClass<AcpInputStreamEndedError>()(\n  \"AcpInputStreamEndedError\",\n  {},\n) {\n  override get message() {\n    return \"ACP input stream ended.\";\n  }\n}\n\nexport class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(\"AcpRequestError\", {\n  code: AcpSchema.ErrorCode,\n  errorMessage: Schema.String,\n  data: Schema.optional(Schema.Unknown),\n  method: Schema.optionalKey(Schema.String),\n  requestId: Schema.optionalKey(AcpRequestId),\n  operation: Schema.optionalKey(AcpRequestOperation),\n  issueCount: Schema.optionalKey(Schema.Number),\n  issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),\n  maximumPathDepth: Schema.optionalKey(Schema.Number),\n  cause: Schema.optionalKey(Schema.Defect()),\n}) {\n  override get message() {\n    return this.errorMessage;\n  }\n\n  static fromProtocolError(\n    error: AcpSchema.Error,\n    context: {\n      readonly method: string;\n      readonly requestId?: AcpRequestId;\n      readonly cause?: unknown;\n    },\n  ) {\n    return new AcpRequestError({\n      code: error.code,\n      errorMessage: error.message,\n      ...(error.data !== undefined ? { data: error.data } : {}),\n      method: context.method,\n      ...(context.requestId === undefined ? {} : { requestId: context.requestId }),\n      operation: \"receive-response\",\n      cause: context.cause ?? error,\n    });\n  }\n\n  static fromExtensionResponseFailure(method: string, requestId: AcpRequestId, cause: unknown) {\n    return AcpRequestError.internalError(\"Extension request failed\", undefined, {\n      method,\n      requestId,\n      operation: \"receive-response\",\n      cause,\n    });\n  }\n\n  static fromExtensionResponseEncodingError(\n    method: string,\n    requestId: AcpRequestId,\n    cause: AcpProtocolParseError,\n  ) {\n    return AcpRequestError.internalError(\"Internal error\", undefined, {\n      method,\n      requestId,\n      operation: \"encode-extension-response\",\n      cause,\n    });\n  }\n\n  static unsupportedStreamingResponse(method: string, requestId: AcpRequestId) {\n    return AcpRequestError.internalError(\n      \"Streaming extension responses are not supported\",\n      undefined,\n      {\n        method,\n        requestId,\n        operation: \"receive-streaming-response\",\n      },\n    );\n  }\n\n  static fromCoreHandlerError(error: AcpError, method: string) {\n    if (error._tag === \"AcpRequestError\") {\n      return error;\n    }\n    return AcpRequestError.internalError(\n      `ACP request handler failed for method '${method}'`,\n      undefined,\n      {\n        method,\n        operation: \"handle-request\",\n        cause: error,\n      },\n    );\n  }\n\n  static fromExtensionHandlerError(error: AcpError, method: string) {\n    if (error._tag === \"AcpRequestError\") {\n      return error;\n    }\n    return AcpRequestError.internalError(\n      `ACP extension request handler failed for method '${method}'`,\n      undefined,\n      {\n        method,\n        operation: \"handle-extension-request\",\n        cause: error,\n      },\n    );\n  }\n\n  static parseError(message = \"Parse error\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32700,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static invalidRequest(message = \"Invalid request\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32600,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static methodNotFound(method: string) {\n    return new AcpRequestError({\n      code: -32601,\n      errorMessage: `Method not found: ${method}`,\n    });\n  }\n\n  static invalidParams(message = \"Invalid params\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32602,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static invalidExtensionPayload(method: string, cause: Schema.SchemaError) {\n    const diagnostics = schemaIssueDiagnostics(cause.issue);\n    return new AcpRequestError({\n      code: -32602,\n      errorMessage: `Invalid payload for ACP extension method '${method}'.`,\n      data: diagnostics,\n      method,\n      operation: \"decode-extension-request-payload\",\n      ...diagnostics,\n      cause,\n    });\n  }\n\n  static internalError(\n    message = \"Internal error\",\n    data?: unknown,\n    diagnostics: AcpRequestDiagnostics = {},\n  ) {\n    return new AcpRequestError({\n      code: -32603,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n      ...diagnostics,\n    });\n  }\n\n  static authRequired(message = \"Authentication required\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32000,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static resourceNotFound(message = \"Resource not found\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32002,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  toProtocolError() {\n    return AcpSchema.Error.make({\n      code: this.code,\n      message: this.errorMessage,\n      ...(this.data !== undefined ? { data: this.data } : {}),\n    });\n  }\n}\n\nexport const AcpError = Schema.Union([\n  AcpRequestError,\n  AcpSpawnError,\n  AcpProcessExitedError,\n  AcpProtocolParseError,\n  AcpTransportError,\n  AcpInputStreamEndedError,\n]);\n\nexport type AcpError = typeof AcpError.Type;\n","// This file is generated by the effect-acp package. Do not edit manually.\n// Current ACP schema release: v0.11.3\n\nexport const AGENT_METHODS = {\n  authenticate: \"authenticate\",\n  initialize: \"initialize\",\n  logout: \"logout\",\n  session_cancel: \"session/cancel\",\n  session_close: \"session/close\",\n  session_fork: \"session/fork\",\n  session_list: \"session/list\",\n  session_load: \"session/load\",\n  session_new: \"session/new\",\n  session_prompt: \"session/prompt\",\n  session_resume: \"session/resume\",\n  session_set_config_option: \"session/set_config_option\",\n  session_set_mode: \"session/set_mode\",\n  session_set_model: \"session/set_model\",\n} as const;\n\nexport const CLIENT_METHODS = {\n  fs_read_text_file: \"fs/read_text_file\",\n  fs_write_text_file: \"fs/write_text_file\",\n  session_elicitation: \"session/elicitation\",\n  session_elicitation_complete: \"session/elicitation/complete\",\n  session_request_permission: \"session/request_permission\",\n  session_update: \"session/update\",\n  terminal_create: \"terminal/create\",\n  terminal_kill: \"terminal/kill\",\n  terminal_output: \"terminal/output\",\n  terminal_release: \"terminal/release\",\n  terminal_wait_for_exit: \"terminal/wait_for_exit\",\n} as const;\n\nexport const PROTOCOL_VERSION = 1 as const;\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as RpcClient from \"effect/unstable/rpc/RpcClient\";\nimport * as RpcClientError from \"effect/unstable/rpc/RpcClientError\";\nimport * as RpcMessage from \"effect/unstable/rpc/RpcMessage\";\nimport * as RpcSerialization from \"effect/unstable/rpc/RpcSerialization\";\nimport * as RpcServer from \"effect/unstable/rpc/RpcServer\";\n\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\nimport { CLIENT_METHODS } from \"./_generated/meta.gen.ts\";\nimport * as AcpError from \"./errors.ts\";\nconst isAcpError = Schema.is(AcpError.AcpError);\n\nexport interface AcpProtocolLogEvent {\n  readonly direction: \"incoming\" | \"outgoing\";\n  readonly stage:\n    | \"raw\"\n    | \"decoded\"\n    | \"decode_failed\"\n    | \"terminated\"\n    | \"process_spawned\"\n    | \"process_stderr\"\n    | \"process_exited\";\n  readonly payload: unknown;\n}\n\nexport type AcpIncomingNotification =\n  | {\n      readonly _tag: \"SessionUpdate\";\n      readonly method: typeof CLIENT_METHODS.session_update;\n      readonly params: AcpSchema.SessionNotification;\n    }\n  | {\n      readonly _tag: \"ElicitationComplete\";\n      readonly method: typeof CLIENT_METHODS.session_elicitation_complete;\n      readonly params: AcpSchema.ElicitationCompleteNotification;\n    }\n  | {\n      readonly _tag: \"ExtNotification\";\n      readonly method: string;\n      readonly params: unknown;\n    };\n\nexport interface AcpPatchedProtocolOptions {\n  readonly stdio: Stdio.Stdio;\n  readonly terminationError?: Effect.Effect<AcpError.AcpError>;\n  readonly serverRequestMethods: ReadonlySet<string>;\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;\n  readonly onNotification?: (\n    notification: AcpIncomingNotification,\n  ) => Effect.Effect<void, AcpError.AcpError, never>;\n  readonly onExtRequest?: (\n    method: string,\n    params: unknown,\n  ) => Effect.Effect<unknown, AcpError.AcpError, never>;\n  readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;\n}\n\nexport interface AcpPatchedProtocol {\n  readonly clientProtocol: RpcClient.Protocol[\"Service\"];\n  readonly serverProtocol: RpcServer.Protocol[\"Service\"];\n  readonly incoming: Stream.Stream<AcpIncomingNotification>;\n  readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;\n  readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;\n}\n\ninterface AcpPendingRequest {\n  readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;\n  readonly method: string;\n}\n\nconst decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);\nconst decodeElicitationComplete = Schema.decodeUnknownEffect(\n  AcpSchema.ElicitationCompleteNotification,\n);\nconst parserFactory = RpcSerialization.ndJsonRpc();\n\nconst canonicalStopReasons = new Set([\n  \"end_turn\",\n  \"max_tokens\",\n  \"max_turn_requests\",\n  \"refusal\",\n  \"cancelled\",\n]);\n\nconst structuralName = (value: string): string =>\n  value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : \"unknown\";\n\nconst valueType = (value: unknown): string =>\n  value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value;\n\nconst boundedFieldNames = (value: Record<string, unknown>): ReadonlyArray<string> =>\n  Object.keys(value)\n    .slice(0, 16)\n    .map(structuralName);\n\nconst safeWireDiagnostics = (data: string | Uint8Array): Readonly<Record<string, unknown>> => {\n  const text = typeof data === \"string\" ? data : new TextDecoder().decode(data);\n  const lines = text\n    .split(/\\r?\\n/)\n    .map((line) => line.trim())\n    .filter(Boolean);\n  if (lines.length === 0 || lines.length > 16) {\n    return { jsonSyntaxValid: false };\n  }\n\n  let decoded: ReadonlyArray<unknown>;\n  try {\n    decoded = lines.map((line) => JSON.parse(line) as unknown);\n  } catch {\n    return { jsonSyntaxValid: false };\n  }\n\n  const candidate = decoded.at(-1);\n  if (candidate === null || typeof candidate !== \"object\" || Array.isArray(candidate)) {\n    return {\n      jsonSyntaxValid: true,\n      frameCount: decoded.length,\n      topLevelType: valueType(candidate),\n    };\n  }\n\n  const frame = candidate as Record<string, unknown>;\n  const result =\n    frame.result !== null && typeof frame.result === \"object\" && !Array.isArray(frame.result)\n      ? (frame.result as Record<string, unknown>)\n      : undefined;\n  const stopReason = result?.stopReason;\n  return {\n    jsonSyntaxValid: true,\n    frameCount: decoded.length,\n    topLevelFields: boundedFieldNames(frame),\n    ...(Object.hasOwn(frame, \"jsonrpc\") ? { jsonrpcType: valueType(frame.jsonrpc) } : {}),\n    ...(Object.hasOwn(frame, \"id\") ? { idType: valueType(frame.id) } : {}),\n    ...(typeof frame.method === \"string\" ? { method: structuralName(frame.method) } : {}),\n    ...(result ? { resultFields: boundedFieldNames(result) } : {}),\n    ...(result && Object.hasOwn(result, \"stopReason\")\n      ? {\n          stopReasonType: valueType(stopReason),\n          ...(typeof stopReason === \"string\" && canonicalStopReasons.has(stopReason)\n            ? { canonicalStopReason: stopReason }\n            : {}),\n        }\n      : {}),\n  };\n};\n\nconst safeTerminationDiagnostics = (\n  error: AcpError.AcpError,\n): Readonly<Record<string, unknown>> => {\n  const record = error as unknown as Record<string, unknown>;\n  return {\n    errorTag: error._tag,\n    ...(typeof record.operation === \"string\"\n      ? { operation: structuralName(record.operation) }\n      : {}),\n    ...(typeof record.method === \"string\" ? { method: structuralName(record.method) } : {}),\n    ...(Object.hasOwn(record, \"requestId\")\n      ? { requestIdType: valueType(record.requestId), requestId: \"redacted\" }\n      : {}),\n    ...(typeof record.issueCount === \"number\"\n      ? { issueCount: Math.min(Math.max(0, record.issueCount), 10_000) }\n      : {}),\n    ...(Array.isArray(record.issueKinds)\n      ? { issueKinds: record.issueKinds.slice(0, 16).map((kind) => structuralName(String(kind))) }\n      : {}),\n    ...(typeof record.maximumPathDepth === \"number\"\n      ? { maximumPathDepth: Math.min(Math.max(0, record.maximumPathDepth), 1_000) }\n      : {}),\n    ...(typeof record.pid === \"number\" ? { pid: record.pid } : {}),\n    ...(typeof record.code === \"number\" ? { exitCode: record.code } : {}),\n  };\n};\n\nexport const makeAcpPatchedProtocol = Effect.fn(\"makeAcpPatchedProtocol\")(function* (\n  options: AcpPatchedProtocolOptions,\n): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {\n  const parser = parserFactory.makeUnsafe();\n  const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();\n  const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();\n  const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();\n  const disconnects = yield* Queue.unbounded<number>();\n  const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();\n  const nextRequestId = yield* Ref.make(1);\n  const terminationHandled = yield* Ref.make(false);\n  const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());\n\n  const logProtocol = (event: AcpProtocolLogEvent) => {\n    if (event.direction === \"incoming\" && !options.logIncoming) {\n      return Effect.void;\n    }\n    if (event.direction === \"outgoing\" && !options.logOutgoing) {\n      return Effect.void;\n    }\n    return (\n      options.logger?.(event) ??\n      Effect.logDebug(\"ACP protocol event\").pipe(Effect.annotateLogs({ event }))\n    );\n  };\n\n  const offerOutgoing = Effect.fn(\"offerOutgoing\")(function* (\n    message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,\n  ) {\n    yield* logProtocol({\n      direction: \"outgoing\",\n      stage: \"decoded\",\n      payload: message,\n    });\n\n    const method = message._tag === \"Request\" ? message.tag : undefined;\n    const encodedRequestId =\n      message._tag === \"Request\"\n        ? message.id\n        : \"requestId\" in message\n          ? message.requestId\n          : undefined;\n    const requestId = encodedRequestId === \"\" ? undefined : encodedRequestId;\n    const encoded = yield* Effect.try({\n      try: () => parser.encode(message),\n      catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),\n    });\n\n    if (encoded) {\n      yield* logProtocol({\n        direction: \"outgoing\",\n        stage: \"raw\",\n        payload: typeof encoded === \"string\" ? encoded : new TextDecoder().decode(encoded),\n      });\n\n      yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);\n    }\n  });\n\n  const resolveExtPending = (\n    requestId: AcpError.AcpRequestId,\n    onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,\n  ) =>\n    Ref.modify(extPending, (pending) => {\n      const pendingKey = String(requestId);\n      const pendingRequest = pending.get(pendingKey);\n      if (!pendingRequest) {\n        return [Effect.void, pending] as const;\n      }\n      const next = new Map(pending);\n      next.delete(pendingKey);\n      return [onFound(pendingRequest), next] as const;\n    }).pipe(Effect.flatten);\n\n  const removeExtPending = (requestId: AcpError.AcpRequestId) =>\n    Ref.update(extPending, (pending) => {\n      const pendingKey = String(requestId);\n      if (!pending.has(pendingKey)) {\n        return pending;\n      }\n      const next = new Map(pending);\n      next.delete(pendingKey);\n      return next;\n    });\n\n  const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>\n    resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));\n\n  const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>\n    resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));\n\n  const failAllExtPending = (error: AcpError.AcpError) =>\n    Ref.getAndSet(extPending, new Map()).pipe(\n      Effect.flatMap((pending) =>\n        Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {\n          discard: true,\n        }),\n      ),\n    );\n\n  const dispatchNotification = (notification: AcpIncomingNotification) =>\n    Queue.offer(notificationQueue, notification).pipe(\n      Effect.andThen(\n        options.onNotification\n          ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))\n          : Effect.void,\n      ),\n      Effect.asVoid,\n    );\n\n  const emitClientProtocolError = (error: AcpError.AcpError) =>\n    Queue.offer(clientQueue, {\n      _tag: \"ClientProtocolError\",\n      error: new RpcClientError.RpcClientError({\n        reason: new RpcClientError.RpcClientDefect({\n          message: \"ACP protocol terminated.\",\n          cause: error,\n        }),\n      }),\n    }).pipe(Effect.asVoid);\n\n  const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>\n    Ref.modify(terminationHandled, (handled) => {\n      if (handled) {\n        return [Effect.void, true] as const;\n      }\n      return [\n        Effect.gen(function* () {\n          yield* Queue.offer(disconnects, 0);\n          const error = yield* classify();\n          if (!error) {\n            return;\n          }\n          yield* logProtocol({\n            direction: \"incoming\",\n            stage: \"terminated\",\n            payload: safeTerminationDiagnostics(error),\n          });\n          yield* failAllExtPending(error);\n          yield* emitClientProtocolError(error);\n          if (options.onTermination) {\n            yield* options.onTermination(error);\n          }\n        }),\n        true,\n      ] as const;\n    }).pipe(Effect.flatten);\n\n  const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>\n    offerOutgoing({\n      _tag: \"Exit\",\n      requestId,\n      exit: {\n        _tag: \"Success\",\n        value,\n      },\n    });\n\n  const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>\n    offerOutgoing({\n      _tag: \"Exit\",\n      requestId,\n      exit: {\n        _tag: \"Failure\",\n        cause: [\n          {\n            _tag: \"Fail\",\n            error: error.toProtocolError(),\n          },\n        ],\n      },\n    });\n\n  const handleExtRequest = (message: RpcMessage.RequestEncoded) => {\n    if (!options.onExtRequest) {\n      return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));\n    }\n    return options.onExtRequest(message.tag, message.payload).pipe(\n      Effect.matchEffect({\n        onFailure: (error) =>\n          respondWithError(\n            message.id,\n            AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),\n          ),\n        onSuccess: (value) => respondWithSuccess(message.id, value),\n      }),\n    );\n  };\n\n  const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {\n    if (message.id === \"\") {\n      if (message.tag === CLIENT_METHODS.session_update) {\n        return decodeSessionUpdate(message.payload).pipe(\n          Effect.map(\n            (params) =>\n              ({\n                _tag: \"SessionUpdate\",\n                method: CLIENT_METHODS.session_update,\n                params,\n              }) satisfies AcpIncomingNotification,\n          ),\n          Effect.mapError((cause) =>\n            AcpError.AcpProtocolParseError.fromSchemaError(\n              \"decode-notification-payload\",\n              CLIENT_METHODS.session_update,\n              cause,\n            ),\n          ),\n          Effect.flatMap(dispatchNotification),\n        );\n      }\n      if (message.tag === CLIENT_METHODS.session_elicitation_complete) {\n        return decodeElicitationComplete(message.payload).pipe(\n          Effect.map(\n            (params) =>\n              ({\n                _tag: \"ElicitationComplete\",\n                method: CLIENT_METHODS.session_elicitation_complete,\n                params,\n              }) satisfies AcpIncomingNotification,\n          ),\n          Effect.mapError((cause) =>\n            AcpError.AcpProtocolParseError.fromSchemaError(\n              \"decode-notification-payload\",\n              CLIENT_METHODS.session_elicitation_complete,\n              cause,\n            ),\n          ),\n          Effect.flatMap(dispatchNotification),\n        );\n      }\n      return dispatchNotification({\n        _tag: \"ExtNotification\",\n        method: message.tag,\n        params: message.payload,\n      });\n    }\n\n    if (!options.serverRequestMethods.has(message.tag)) {\n      return handleExtRequest(message).pipe(\n        Effect.catchTags({\n          AcpProtocolParseError: (error) =>\n            Effect.logWarning(error).pipe(\n              Effect.annotateLogs({\n                method: message.tag,\n                requestId: message.id,\n                operation: error.operation,\n              }),\n              Effect.andThen(\n                respondWithError(\n                  message.id,\n                  AcpError.AcpRequestError.fromExtensionResponseEncodingError(\n                    message.tag,\n                    message.id,\n                    error,\n                  ),\n                ),\n              ),\n            ),\n        }),\n        Effect.asVoid,\n      );\n    }\n\n    return Queue.offer(serverQueue, message).pipe(Effect.asVoid);\n  };\n\n  const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>\n    Ref.get(extPending).pipe(\n      Effect.flatMap((pending) => {\n        const pendingRequest = pending.get(String(message.requestId));\n        if (!pendingRequest) {\n          return Queue.offer(clientQueue, message).pipe(Effect.asVoid);\n        }\n        if (message.exit._tag === \"Success\") {\n          return completeExtPendingSuccess(message.requestId, message.exit.value);\n        }\n        const failure = message.exit.cause.find((entry) => entry._tag === \"Fail\");\n        if (failure && isProtocolError(failure.error)) {\n          return completeExtPendingFailure(\n            message.requestId,\n            AcpError.AcpRequestError.fromProtocolError(failure.error, {\n              method: pendingRequest.method,\n              requestId: message.requestId,\n              cause: message.exit.cause,\n            }),\n          );\n        }\n        return completeExtPendingFailure(\n          message.requestId,\n          AcpError.AcpRequestError.fromExtensionResponseFailure(\n            pendingRequest.method,\n            message.requestId,\n            message.exit.cause,\n          ),\n        );\n      }),\n    );\n\n  const routeDecodedMessage = (\n    message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,\n  ): Effect.Effect<void, AcpError.AcpError> => {\n    switch (message._tag) {\n      case \"Request\":\n        return handleRequestEncoded(message);\n      case \"Exit\":\n        return handleExitEncoded(message);\n      case \"Chunk\":\n        return Ref.get(extPending).pipe(\n          Effect.flatMap((pending) => {\n            const pendingRequest = pending.get(String(message.requestId));\n            return pendingRequest\n              ? completeExtPendingFailure(\n                  message.requestId,\n                  AcpError.AcpRequestError.unsupportedStreamingResponse(\n                    pendingRequest.method,\n                    message.requestId,\n                  ),\n                )\n              : Queue.offer(clientQueue, message).pipe(Effect.asVoid);\n          }),\n        );\n      case \"Defect\":\n      case \"ClientProtocolError\":\n      case \"Pong\":\n        return Queue.offer(clientQueue, message).pipe(Effect.asVoid);\n      case \"Ack\":\n      case \"Interrupt\":\n      case \"Ping\":\n      case \"Eof\":\n        return Queue.offer(serverQueue, message).pipe(Effect.asVoid);\n    }\n  };\n\n  yield* options.stdio.stdin.pipe(\n    Stream.runForEach((data) =>\n      logProtocol({\n        direction: \"incoming\",\n        stage: \"raw\",\n        payload: typeof data === \"string\" ? data : new TextDecoder().decode(data),\n      }).pipe(\n        Effect.flatMap(() =>\n          Effect.try({\n            try: () =>\n              parser.decode(data) as ReadonlyArray<\n                RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded\n              >,\n            catch: (cause) =>\n              new AcpError.AcpProtocolParseError({\n                operation: \"decode-wire-message\",\n                cause,\n              }),\n          }),\n        ),\n        Effect.tap((messages) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decoded\",\n            payload: messages,\n          }),\n        ),\n        Effect.flatMap((messages) =>\n          Effect.forEach(messages, routeDecodedMessage, {\n            discard: true,\n          }),\n        ),\n        Effect.tapErrorTag(\"AcpProtocolParseError\", (error) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decode_failed\",\n            payload: {\n              operation: error.operation,\n              ...(error.operation === \"decode-wire-message\" ? safeWireDiagnostics(data) : {}),\n              ...(error.method === undefined ? {} : { method: error.method }),\n              ...(error.requestId === undefined\n                ? {}\n                : { requestIdType: valueType(error.requestId), requestId: \"redacted\" }),\n              ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),\n              ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),\n              ...(error.maximumPathDepth === undefined\n                ? {}\n                : { maximumPathDepth: error.maximumPathDepth }),\n            },\n          }),\n        ),\n      ),\n    ),\n    Effect.matchEffect({\n      onFailure: (error) => {\n        const normalized: AcpError.AcpError = isAcpError(error)\n          ? error\n          : new AcpError.AcpTransportError({\n              operation: \"read-input-stream\",\n              cause: error,\n            });\n        return handleTermination(() => Effect.succeed(normalized));\n      },\n      onSuccess: () =>\n        handleTermination(\n          () =>\n            options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),\n        ),\n    }),\n    Effect.forkScoped,\n  );\n\n  yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);\n\n  const clientProtocol = RpcClient.Protocol.of({\n    run: (_clientId, f) =>\n      Stream.fromQueue(clientQueue).pipe(\n        Stream.runForEach((message) => f(message)),\n        Effect.forever,\n      ),\n    send: (_clientId, request) =>\n      offerOutgoing(request).pipe(\n        Effect.mapError(\n          (error) =>\n            new RpcClientError.RpcClientError({\n              reason: new RpcClientError.RpcClientDefect({\n                message: \"Failed to send ACP protocol message.\",\n                cause: error,\n              }),\n            }),\n        ),\n      ),\n    supportsAck: true,\n    supportsTransferables: false,\n  });\n\n  const serverProtocol = RpcServer.Protocol.of({\n    run: (f) =>\n      Stream.fromQueue(serverQueue).pipe(\n        Stream.runForEach((message) => f(0, message)),\n        Effect.forever,\n      ),\n    disconnects,\n    send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),\n    end: (_clientId) => Queue.end(outgoing),\n    clientIds: Effect.succeed(new Set([0])),\n    initialMessage: Effect.succeedNone,\n    supportsAck: true,\n    supportsTransferables: false,\n    supportsSpanPropagation: true,\n  });\n\n  const sendNotification = Effect.fn(\"sendNotification\")(function* (\n    method: string,\n    payload: unknown,\n  ) {\n    yield* offerOutgoing({\n      _tag: \"Request\",\n      id: \"\",\n      tag: method,\n      payload,\n      headers: [],\n    });\n  });\n\n  const sendRequest = Effect.fn(\"sendRequest\")(function* (method: string, payload: unknown) {\n    const requestId = yield* Ref.modify(\n      nextRequestId,\n      (current) => [current, current + 1] as const,\n    );\n    const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();\n    yield* Ref.update(extPending, (pending) =>\n      new Map(pending).set(String(requestId), { deferred, method }),\n    );\n    yield* offerOutgoing({\n      _tag: \"Request\",\n      id: requestId,\n      tag: method,\n      payload,\n      headers: [],\n    }).pipe(Effect.tapError(() => removeExtPending(requestId)));\n    return yield* Deferred.await(deferred).pipe(\n      Effect.onInterrupt(() => removeExtPending(requestId)),\n    );\n  });\n\n  return {\n    clientProtocol,\n    serverProtocol,\n    get incoming() {\n      return Stream.fromQueue(notificationQueue);\n    },\n    request: sendRequest,\n    notify: sendNotification,\n  } satisfies AcpPatchedProtocol;\n});\n\nfunction isProtocolError(\n  value: unknown,\n): value is { code: number; message: string; data?: unknown } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"code\" in value &&\n    typeof value.code === \"number\" &&\n    \"message\" in value &&\n    typeof value.message === \"string\"\n  );\n}\n","import * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Rpc from \"effect/unstable/rpc/Rpc\";\nimport * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\nimport { AGENT_METHODS, CLIENT_METHODS } from \"./_generated/meta.gen.ts\";\n\n// JoyCode 1.0.4 occasionally completes an otherwise successful, long-running\n// prompt with a malformed stopReason. Accept the provider's completion frame\n// at the wire seam and keep the public ACP result canonical. The generated ACP\n// schema remains the first union member, so every standard stop reason is\n// preserved without passing through this fallback.\nconst NonCanonicalPromptStopReasonResponse = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))),\n  stopReason: Schema.Unknown,\n  usage: Schema.optionalKey(Schema.NullOr(AcpSchema.Usage)),\n  userMessageId: Schema.optionalKey(Schema.NullOr(Schema.String)),\n});\nconst isCanonicalPromptResponse = Schema.is(AcpSchema.PromptResponse);\n\nconst PromptResponseCompat = Schema.Union([\n  AcpSchema.PromptResponse,\n  NonCanonicalPromptStopReasonResponse,\n]).pipe(\n  Schema.decodeTo(\n    Schema.toType(AcpSchema.PromptResponse),\n    SchemaTransformation.transform({\n      decode: (response) =>\n        isCanonicalPromptResponse(response)\n          ? response\n          : { ...response, stopReason: \"end_turn\" as const },\n      encode: (response) => response,\n    }),\n  ),\n);\n\nexport const InitializeRpc = Rpc.make(AGENT_METHODS.initialize, {\n  payload: AcpSchema.InitializeRequest,\n  success: AcpSchema.InitializeResponse,\n  error: AcpSchema.Error,\n});\n\nexport const AuthenticateRpc = Rpc.make(AGENT_METHODS.authenticate, {\n  payload: AcpSchema.AuthenticateRequest,\n  success: AcpSchema.AuthenticateResponse,\n  error: AcpSchema.Error,\n});\n\nexport const LogoutRpc = Rpc.make(AGENT_METHODS.logout, {\n  payload: AcpSchema.LogoutRequest,\n  success: AcpSchema.LogoutResponse,\n  error: AcpSchema.Error,\n});\n\nexport const NewSessionRpc = Rpc.make(AGENT_METHODS.session_new, {\n  payload: AcpSchema.NewSessionRequest,\n  success: AcpSchema.NewSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const LoadSessionRpc = Rpc.make(AGENT_METHODS.session_load, {\n  payload: AcpSchema.LoadSessionRequest,\n  success: AcpSchema.LoadSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ListSessionsRpc = Rpc.make(AGENT_METHODS.session_list, {\n  payload: AcpSchema.ListSessionsRequest,\n  success: AcpSchema.ListSessionsResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ForkSessionRpc = Rpc.make(AGENT_METHODS.session_fork, {\n  payload: AcpSchema.ForkSessionRequest,\n  success: AcpSchema.ForkSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ResumeSessionRpc = Rpc.make(AGENT_METHODS.session_resume, {\n  payload: AcpSchema.ResumeSessionRequest,\n  success: AcpSchema.ResumeSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const CloseSessionRpc = Rpc.make(AGENT_METHODS.session_close, {\n  payload: AcpSchema.CloseSessionRequest,\n  success: AcpSchema.CloseSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const PromptRpc = Rpc.make(AGENT_METHODS.session_prompt, {\n  payload: AcpSchema.PromptRequest,\n  success: PromptResponseCompat,\n  error: AcpSchema.Error,\n});\n\nexport const SetSessionModelRpc = Rpc.make(AGENT_METHODS.session_set_model, {\n  payload: AcpSchema.SetSessionModelRequest,\n  success: AcpSchema.SetSessionModelResponse,\n  error: AcpSchema.Error,\n});\n\nexport const SetSessionConfigOptionRpc = Rpc.make(AGENT_METHODS.session_set_config_option, {\n  payload: AcpSchema.SetSessionConfigOptionRequest,\n  success: AcpSchema.SetSessionConfigOptionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ReadTextFileRpc = Rpc.make(CLIENT_METHODS.fs_read_text_file, {\n  payload: AcpSchema.ReadTextFileRequest,\n  success: AcpSchema.ReadTextFileResponse,\n  error: AcpSchema.Error,\n});\n\nexport const WriteTextFileRpc = Rpc.make(CLIENT_METHODS.fs_write_text_file, {\n  payload: AcpSchema.WriteTextFileRequest,\n  success: AcpSchema.WriteTextFileResponse,\n  error: AcpSchema.Error,\n});\n\nexport const RequestPermissionRpc = Rpc.make(CLIENT_METHODS.session_request_permission, {\n  payload: AcpSchema.RequestPermissionRequest,\n  success: AcpSchema.RequestPermissionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ElicitationRpc = Rpc.make(CLIENT_METHODS.session_elicitation, {\n  payload: AcpSchema.ElicitationRequest,\n  success: AcpSchema.ElicitationResponse,\n  error: AcpSchema.Error,\n});\n\nexport const CreateTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_create, {\n  payload: AcpSchema.CreateTerminalRequest,\n  success: AcpSchema.CreateTerminalResponse,\n  error: AcpSchema.Error,\n});\n\nexport const TerminalOutputRpc = Rpc.make(CLIENT_METHODS.terminal_output, {\n  payload: AcpSchema.TerminalOutputRequest,\n  success: AcpSchema.TerminalOutputResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ReleaseTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_release, {\n  payload: AcpSchema.ReleaseTerminalRequest,\n  success: AcpSchema.ReleaseTerminalResponse,\n  error: AcpSchema.Error,\n});\n\nexport const WaitForTerminalExitRpc = Rpc.make(CLIENT_METHODS.terminal_wait_for_exit, {\n  payload: AcpSchema.WaitForTerminalExitRequest,\n  success: AcpSchema.WaitForTerminalExitResponse,\n  error: AcpSchema.Error,\n});\n\nexport const KillTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_kill, {\n  payload: AcpSchema.KillTerminalRequest,\n  success: AcpSchema.KillTerminalResponse,\n  error: AcpSchema.Error,\n});\n\nexport const AgentRpcs = RpcGroup.make(\n  InitializeRpc,\n  AuthenticateRpc,\n  LogoutRpc,\n  NewSessionRpc,\n  LoadSessionRpc,\n  ListSessionsRpc,\n  ForkSessionRpc,\n  ResumeSessionRpc,\n  CloseSessionRpc,\n  PromptRpc,\n  SetSessionModelRpc,\n  SetSessionConfigOptionRpc,\n);\n\nexport const ClientRpcs = RpcGroup.make(\n  ReadTextFileRpc,\n  WriteTextFileRpc,\n  RequestPermissionRpc,\n  ElicitationRpc,\n  CreateTerminalRpc,\n  TerminalOutputRpc,\n  ReleaseTerminalRpc,\n  WaitForTerminalExitRpc,\n  KillTerminalRpc,\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { RpcClientError } from \"effect/unstable/rpc\";\n\nimport * as AcpSchema from \"../_generated/schema.gen.ts\";\nimport * as AcpError from \"../errors.ts\";\nconst isError = Schema.is(AcpSchema.Error);\n\nexport const callRpc = <A>(\n  method: string,\n  effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>,\n): Effect.Effect<A, AcpError.AcpError> =>\n  effect.pipe(\n    Effect.catchDefect((defect) =>\n      Schema.isSchemaError(defect)\n        ? Effect.fail(\n            AcpError.AcpProtocolParseError.fromSchemaError(\n              \"decode-rpc-result\",\n              method,\n              defect,\n            ),\n          )\n        : Effect.die(defect),\n    ),\n    Effect.catchIf(isError, (error) =>\n      Effect.fail(AcpError.AcpRequestError.fromProtocolError(error, { method })),\n    ),\n    Effect.catchTags({\n      RpcClientError: (cause) =>\n        Effect.fail(\n          new AcpError.AcpTransportError({\n            operation: \"call-rpc\",\n            method,\n            cause,\n          }),\n        ),\n    }),\n  );\n\nexport const runHandler = Effect.fnUntraced(function* <A, B>(\n  handler: ((payload: A) => Effect.Effect<B, AcpError.AcpError>) | undefined,\n  payload: A,\n  method: string,\n) {\n  if (!handler) {\n    return yield* Effect.fail(AcpError.AcpRequestError.methodNotFound(method).toProtocolError());\n  }\n  return yield* handler(payload).pipe(\n    Effect.mapError((error) =>\n      AcpError.AcpRequestError.fromCoreHandlerError(error, method).toProtocolError(),\n    ),\n  );\n});\n\nexport function decodeExtRequestRegistration<A, I>(\n  method: string,\n  payload: Schema.Codec<A, I>,\n  handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,\n) {\n  return (params: unknown): Effect.Effect<unknown, AcpError.AcpError> =>\n    Schema.decodeUnknownEffect(payload)(params).pipe(\n      Effect.mapError((error) => AcpError.AcpRequestError.invalidExtensionPayload(method, error)),\n      Effect.flatMap((decoded) => handler(decoded)),\n    );\n}\n\nexport function decodeExtNotificationRegistration<A, I>(\n  method: string,\n  payload: Schema.Codec<A, I>,\n  handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,\n) {\n  return (params: unknown): Effect.Effect<void, AcpError.AcpError> =>\n    Schema.decodeUnknownEffect(payload)(params).pipe(\n      Effect.mapError((error) =>\n        AcpError.AcpProtocolParseError.fromSchemaError(\n          \"decode-notification-payload\",\n          method,\n          error,\n        ),\n      ),\n      Effect.flatMap((decoded) => handler(decoded)),\n    );\n}\n\nconst encoder = new TextEncoder();\n\nconst JsonRpcId = Schema.Union([Schema.Number, Schema.String]);\nconst JsonRpcHeaders = Schema.Array(Schema.Unknown);\n\nexport const jsonRpcRequest = <A, I>(method: string, params: Schema.Codec<A, I>) =>\n  Schema.Struct({\n    jsonrpc: Schema.Literal(\"2.0\"),\n    id: JsonRpcId,\n    method: Schema.Literal(method),\n    params,\n    headers: JsonRpcHeaders,\n  });\n\nexport const jsonRpcNotification = <A, I>(method: string, params: Schema.Codec<A, I>) =>\n  Schema.Struct({\n    jsonrpc: Schema.Literal(\"2.0\"),\n    method: Schema.Literal(method),\n    params,\n  });\n\nexport const jsonRpcResponse = <A, I>(result: Schema.Codec<A, I>) =>\n  Schema.Struct({\n    jsonrpc: Schema.Literal(\"2.0\"),\n    id: JsonRpcId,\n    result,\n  });\n\nexport const encodeJsonl = <A, I>(schema: Schema.Codec<A, I>, value: A) =>\n  Effect.map(Schema.encodeEffect(Schema.fromJsonString(schema))(value), (encoded) =>\n    encoder.encode(`${encoded}\\n`),\n  );\n","import * as Queue from \"effect/Queue\";\nimport * as Stream from \"effect/Stream\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as AcpError from \"../errors.ts\";\n\nconst encoder = new TextEncoder();\n\nexport const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>\n  Stdio.make({\n    args: Effect.succeed([]),\n    stdin: handle.stdout,\n    stdout: () =>\n      Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>\n        typeof chunk === \"string\" ? encoder.encode(chunk) : chunk,\n      ),\n    stderr: () => Sink.drain,\n  });\n\nexport const makeInMemoryStdio = Effect.fn(\"makeInMemoryStdio\")(function* () {\n  const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();\n  const output = yield* Queue.unbounded<string>();\n  const decoder = new TextDecoder();\n\n  return {\n    stdio: Stdio.make({\n      args: Effect.succeed([]),\n      stdin: Stream.fromQueue(input),\n      stdout: () =>\n        Sink.forEach((chunk: string | Uint8Array) =>\n          Queue.offer(\n            output,\n            typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true }),\n          ),\n        ),\n      stderr: () => Sink.drain,\n    }),\n    input,\n    output,\n  };\n});\n\ntype ChildProcessTerminationHandle = Pick<\n  ChildProcessSpawner.ChildProcessHandle,\n  \"exitCode\" | \"pid\"\n>;\n\nexport const makeTerminationError = (\n  handle: ChildProcessTerminationHandle,\n): Effect.Effect<AcpError.AcpError> =>\n  Effect.match(handle.exitCode, {\n    onFailure: (cause) =>\n      new AcpError.AcpTransportError({\n        operation: \"read-process-exit-status\",\n        pid: handle.pid,\n        cause,\n      }),\n    onSuccess: (code) => new AcpError.AcpProcessExitedError({ code, pid: handle.pid }),\n  });\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as RpcClient from \"effect/unstable/rpc/RpcClient\";\nimport * as RpcMessage from \"effect/unstable/rpc/RpcMessage\";\nimport * as RpcServer from \"effect/unstable/rpc/RpcServer\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\nimport * as AcpError from \"./errors.ts\";\nimport * as AcpProtocol from \"./protocol.ts\";\nimport * as AcpRpcs from \"./rpc.ts\";\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\nimport { AGENT_METHODS, CLIENT_METHODS } from \"./_generated/meta.gen.ts\";\nimport {\n  callRpc,\n  decodeExtNotificationRegistration,\n  decodeExtRequestRegistration,\n  runHandler,\n} from \"./_internal/shared.ts\";\nimport { makeChildStdio, makeTerminationError } from \"./_internal/stdio.ts\";\n\nexport interface AcpClientOptions {\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;\n}\n\ntype AcpClientRaw = {\n  readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;\n  readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;\n  readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;\n};\n\nexport class AcpClient extends Context.Service<\n  AcpClient,\n  {\n    readonly raw: AcpClientRaw;\n    readonly agent: {\n      /**\n       * Initializes the ACP session and negotiates capabilities.\n       * @see https://agentclientprotocol.com/protocol/schema#initialize\n       */\n      readonly initialize: (\n        payload: AcpSchema.InitializeRequest,\n      ) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;\n      /**\n       * Performs ACP authentication when the agent requires it.\n       * @see https://agentclientprotocol.com/protocol/schema#authenticate\n       */\n      readonly authenticate: (\n        payload: AcpSchema.AuthenticateRequest,\n      ) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;\n      /**\n       * Logs out the current ACP identity.\n       * @see https://agentclientprotocol.com/protocol/schema#logout\n       */\n      readonly logout: (\n        payload: AcpSchema.LogoutRequest,\n      ) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;\n      /**\n       * Starts a new ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/new\n       */\n      readonly createSession: (\n        payload: AcpSchema.NewSessionRequest,\n      ) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;\n      /**\n       * Loads a previously saved ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/load\n       */\n      readonly loadSession: (\n        payload: AcpSchema.LoadSessionRequest,\n      ) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;\n      /**\n       * Lists available ACP sessions.\n       * @see https://agentclientprotocol.com/protocol/schema#session/list\n       */\n      readonly listSessions: (\n        payload: AcpSchema.ListSessionsRequest,\n      ) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;\n      /**\n       * Forks an ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/fork\n       */\n      readonly forkSession: (\n        payload: AcpSchema.ForkSessionRequest,\n      ) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;\n      /**\n       * Resumes an ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/resume\n       */\n      readonly resumeSession: (\n        payload: AcpSchema.ResumeSessionRequest,\n      ) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;\n      /**\n       * Closes an ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/close\n       */\n      readonly closeSession: (\n        payload: AcpSchema.CloseSessionRequest,\n      ) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;\n      /**\n       * Selects the active model for a session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/set_model\n       */\n      readonly setSessionModel: (\n        payload: AcpSchema.SetSessionModelRequest,\n      ) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;\n      /**\n       * Updates a session configuration option.\n       * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n       */\n      readonly setSessionConfigOption: (\n        payload: AcpSchema.SetSessionConfigOptionRequest,\n      ) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;\n      /**\n       * Sends a prompt turn to the agent.\n       * @see https://agentclientprotocol.com/protocol/schema#session/prompt\n       */\n      readonly prompt: (\n        payload: AcpSchema.PromptRequest,\n      ) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;\n      /**\n       * Sends a real ACP `session/cancel` notification.\n       * @see https://agentclientprotocol.com/protocol/schema#session/cancel\n       */\n      readonly cancel: (\n        payload: AcpSchema.CancelNotification,\n      ) => Effect.Effect<void, AcpError.AcpError>;\n    };\n    /**\n     * Registers a handler for `session/request_permission`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/request_permission\n     */\n    readonly handleRequestPermission: (\n      handler: (\n        request: AcpSchema.RequestPermissionRequest,\n      ) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `session/elicitation`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation\n     */\n    readonly handleElicitation: (\n      handler: (\n        request: AcpSchema.ElicitationRequest,\n      ) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `fs/read_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file\n     */\n    readonly handleReadTextFile: (\n      handler: (\n        request: AcpSchema.ReadTextFileRequest,\n      ) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `fs/write_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file\n     */\n    readonly handleWriteTextFile: (\n      handler: (\n        request: AcpSchema.WriteTextFileRequest,\n      ) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/create`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/create\n     */\n    readonly handleCreateTerminal: (\n      handler: (\n        request: AcpSchema.CreateTerminalRequest,\n      ) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/output`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/output\n     */\n    readonly handleTerminalOutput: (\n      handler: (\n        request: AcpSchema.TerminalOutputRequest,\n      ) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/wait_for_exit`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit\n     */\n    readonly handleTerminalWaitForExit: (\n      handler: (\n        request: AcpSchema.WaitForTerminalExitRequest,\n      ) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/kill`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/kill\n     */\n    readonly handleTerminalKill: (\n      handler: (\n        request: AcpSchema.KillTerminalRequest,\n      ) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/release`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/release\n     */\n    readonly handleTerminalRelease: (\n      handler: (\n        request: AcpSchema.ReleaseTerminalRequest,\n      ) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `session/update`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/update\n     */\n    readonly handleSessionUpdate: (\n      handler: (\n        notification: AcpSchema.SessionNotification,\n      ) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `session/elicitation/complete`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete\n     */\n    readonly handleElicitationComplete: (\n      handler: (\n        notification: AcpSchema.ElicitationCompleteNotification,\n      ) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a fallback extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtRequest: (\n      handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a fallback extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtNotification: (\n      handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a typed extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtRequest: <A, I>(\n      method: string,\n      payload: Schema.Codec<A, I>,\n      handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a typed extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtNotification: <A, I>(\n      method: string,\n      payload: Schema.Codec<A, I>,\n      handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n  }\n>()(\"effect-acp/client/AcpClient\") {}\n\ninterface AcpCoreRequestHandlers {\n  requestPermission?: (\n    request: AcpSchema.RequestPermissionRequest,\n  ) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;\n  elicitation?: (\n    request: AcpSchema.ElicitationRequest,\n  ) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;\n  readTextFile?: (\n    request: AcpSchema.ReadTextFileRequest,\n  ) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;\n  writeTextFile?: (\n    request: AcpSchema.WriteTextFileRequest,\n  ) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>;\n  createTerminal?: (\n    request: AcpSchema.CreateTerminalRequest,\n  ) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>;\n  terminalOutput?: (\n    request: AcpSchema.TerminalOutputRequest,\n  ) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;\n  terminalWaitForExit?: (\n    request: AcpSchema.WaitForTerminalExitRequest,\n  ) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;\n  terminalKill?: (\n    request: AcpSchema.KillTerminalRequest,\n  ) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>;\n  terminalRelease?: (\n    request: AcpSchema.ReleaseTerminalRequest,\n  ) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>;\n}\n\ninterface AcpNotificationHandlers {\n  readonly sessionUpdate: BufferedNotificationHandler<AcpSchema.SessionNotification>;\n  readonly elicitationComplete: BufferedNotificationHandler<AcpSchema.ElicitationCompleteNotification>;\n}\n\ninterface BufferedNotificationHandler<A> {\n  readonly handlers: Array<(notification: A) => Effect.Effect<void, AcpError.AcpError>>;\n  readonly pending: Array<A>;\n}\n\nexport const make = Effect.fn(\"effect-acp/AcpClient.make\")(function* (\n  stdio: Stdio.Stdio,\n  options: AcpClientOptions = {},\n  terminationError?: Effect.Effect<AcpError.AcpError>,\n): Effect.fn.Return<AcpClient[\"Service\"], never, Scope.Scope> {\n  const coreHandlers: AcpCoreRequestHandlers = {};\n  const notificationHandlers: AcpNotificationHandlers = {\n    sessionUpdate: { handlers: [], pending: [] },\n    elicitationComplete: { handlers: [], pending: [] },\n  };\n  const extRequestHandlers = new Map<\n    string,\n    (params: unknown) => Effect.Effect<unknown, AcpError.AcpError>\n  >();\n  const extNotificationHandlers = new Map<\n    string,\n    (params: unknown) => Effect.Effect<void, AcpError.AcpError>\n  >();\n  let unknownExtRequestHandler:\n    | ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)\n    | undefined;\n  let unknownExtNotificationHandler:\n    | ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)\n    | undefined;\n\n  const runNotificationHandlers = <A>(\n    registration: BufferedNotificationHandler<A>,\n    notification: A,\n  ) =>\n    Effect.forEach(\n      registration.handlers,\n      (handler) => handler(notification).pipe(Effect.catch(() => Effect.void)),\n      { discard: true },\n    );\n\n  const flushBufferedNotifications = <A>(registration: BufferedNotificationHandler<A>) =>\n    Effect.suspend(() => {\n      if (registration.handlers.length === 0 || registration.pending.length === 0) {\n        return Effect.void;\n      }\n      const pending = registration.pending.splice(0, registration.pending.length);\n      return Effect.forEach(\n        pending,\n        (notification) => runNotificationHandlers(registration, notification),\n        {\n          discard: true,\n        },\n      );\n    });\n\n  const dispatchNotification = (notification: AcpProtocol.AcpIncomingNotification) => {\n    switch (notification._tag) {\n      case \"SessionUpdate\": {\n        if (notificationHandlers.sessionUpdate.handlers.length === 0) {\n          notificationHandlers.sessionUpdate.pending.push(notification.params);\n          return Effect.void;\n        }\n        return runNotificationHandlers(notificationHandlers.sessionUpdate, notification.params);\n      }\n      case \"ElicitationComplete\": {\n        if (notificationHandlers.elicitationComplete.handlers.length === 0) {\n          notificationHandlers.elicitationComplete.pending.push(notification.params);\n          return Effect.void;\n        }\n        return runNotificationHandlers(\n          notificationHandlers.elicitationComplete,\n          notification.params,\n        );\n      }\n      case \"ExtNotification\": {\n        const handler = extNotificationHandlers.get(notification.method);\n        if (handler) {\n          return handler(notification.params);\n        }\n        return unknownExtNotificationHandler\n          ? unknownExtNotificationHandler(notification.method, notification.params)\n          : Effect.void;\n      }\n    }\n  };\n\n  const dispatchExtRequest = (method: string, params: unknown) => {\n    const handler = extRequestHandlers.get(method);\n    if (handler) {\n      return handler(params);\n    }\n    return unknownExtRequestHandler\n      ? unknownExtRequestHandler(method, params)\n      : Effect.fail(AcpError.AcpRequestError.methodNotFound(method));\n  };\n\n  const transport = yield* AcpProtocol.makeAcpPatchedProtocol({\n    stdio: stdio,\n    ...(terminationError ? { terminationError } : {}),\n    serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),\n    ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),\n    ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),\n    ...(options.logger ? { logger: options.logger } : {}),\n    onNotification: dispatchNotification,\n    onExtRequest: dispatchExtRequest,\n  });\n\n  const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer(\n    AcpRpcs.ClientRpcs.of({\n      [CLIENT_METHODS.session_request_permission]: (payload) =>\n        runHandler(\n          coreHandlers.requestPermission,\n          payload,\n          CLIENT_METHODS.session_request_permission,\n        ),\n      [CLIENT_METHODS.session_elicitation]: (payload) =>\n        runHandler(coreHandlers.elicitation, payload, CLIENT_METHODS.session_elicitation),\n      [CLIENT_METHODS.fs_read_text_file]: (payload) =>\n        runHandler(coreHandlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file),\n      [CLIENT_METHODS.fs_write_text_file]: (payload) =>\n        runHandler(coreHandlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe(\n          Effect.map((result) => result ?? {}),\n        ),\n      [CLIENT_METHODS.terminal_create]: (payload) =>\n        runHandler(coreHandlers.createTerminal, payload, CLIENT_METHODS.terminal_create),\n      [CLIENT_METHODS.terminal_output]: (payload) =>\n        runHandler(coreHandlers.terminalOutput, payload, CLIENT_METHODS.terminal_output),\n      [CLIENT_METHODS.terminal_wait_for_exit]: (payload) =>\n        runHandler(\n          coreHandlers.terminalWaitForExit,\n          payload,\n          CLIENT_METHODS.terminal_wait_for_exit,\n        ),\n      [CLIENT_METHODS.terminal_kill]: (payload) =>\n        runHandler(coreHandlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe(\n          Effect.map((result) => result ?? {}),\n        ),\n      [CLIENT_METHODS.terminal_release]: (payload) =>\n        runHandler(coreHandlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe(\n          Effect.map((result) => result ?? {}),\n        ),\n    }),\n  );\n\n  yield* RpcServer.make(AcpRpcs.ClientRpcs).pipe(\n    Effect.provideService(RpcServer.Protocol, transport.serverProtocol),\n    Effect.provide(clientHandlerLayer),\n    Effect.forkScoped,\n  );\n\n  let nextRpcRequestId = 2 ** 32;\n  const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs, {\n    generateRequestId: () => RpcMessage.RequestId(nextRpcRequestId++),\n  }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));\n\n  return AcpClient.of({\n    raw: {\n      notifications: transport.incoming,\n      request: transport.request,\n      notify: transport.notify,\n    },\n    agent: {\n      initialize: (payload) =>\n        callRpc(AGENT_METHODS.initialize, rpc[AGENT_METHODS.initialize](payload)),\n      authenticate: (payload) =>\n        callRpc(AGENT_METHODS.authenticate, rpc[AGENT_METHODS.authenticate](payload)),\n      logout: (payload) => callRpc(AGENT_METHODS.logout, rpc[AGENT_METHODS.logout](payload)),\n      createSession: (payload) =>\n        callRpc(AGENT_METHODS.session_new, rpc[AGENT_METHODS.session_new](payload)),\n      loadSession: (payload) =>\n        callRpc(AGENT_METHODS.session_load, rpc[AGENT_METHODS.session_load](payload)),\n      listSessions: (payload) =>\n        callRpc(AGENT_METHODS.session_list, rpc[AGENT_METHODS.session_list](payload)),\n      forkSession: (payload) =>\n        callRpc(AGENT_METHODS.session_fork, rpc[AGENT_METHODS.session_fork](payload)),\n      resumeSession: (payload) =>\n        callRpc(AGENT_METHODS.session_resume, rpc[AGENT_METHODS.session_resume](payload)),\n      closeSession: (payload) =>\n        callRpc(AGENT_METHODS.session_close, rpc[AGENT_METHODS.session_close](payload)),\n      setSessionModel: (payload) =>\n        callRpc(AGENT_METHODS.session_set_model, rpc[AGENT_METHODS.session_set_model](payload)),\n      setSessionConfigOption: (payload) =>\n        callRpc(\n          AGENT_METHODS.session_set_config_option,\n          rpc[AGENT_METHODS.session_set_config_option](payload),\n        ),\n      prompt: (payload) =>\n        callRpc(AGENT_METHODS.session_prompt, rpc[AGENT_METHODS.session_prompt](payload)),\n      cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),\n    },\n    handleRequestPermission: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.requestPermission = handler;\n        return Effect.void;\n      }),\n    handleElicitation: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.elicitation = handler;\n        return Effect.void;\n      }),\n    handleReadTextFile: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.readTextFile = handler;\n        return Effect.void;\n      }),\n    handleWriteTextFile: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.writeTextFile = handler;\n        return Effect.void;\n      }),\n    handleCreateTerminal: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.createTerminal = handler;\n        return Effect.void;\n      }),\n    handleTerminalOutput: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalOutput = handler;\n        return Effect.void;\n      }),\n    handleTerminalWaitForExit: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalWaitForExit = handler;\n        return Effect.void;\n      }),\n    handleTerminalKill: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalKill = handler;\n        return Effect.void;\n      }),\n    handleTerminalRelease: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalRelease = handler;\n        return Effect.void;\n      }),\n    handleSessionUpdate: (handler) =>\n      Effect.suspend(() => {\n        notificationHandlers.sessionUpdate.handlers.push(handler);\n        return flushBufferedNotifications(notificationHandlers.sessionUpdate);\n      }),\n    handleElicitationComplete: (handler) =>\n      Effect.suspend(() => {\n        notificationHandlers.elicitationComplete.handlers.push(handler);\n        return flushBufferedNotifications(notificationHandlers.elicitationComplete);\n      }),\n    handleUnknownExtRequest: (handler) =>\n      Effect.suspend(() => {\n        unknownExtRequestHandler = handler;\n        return Effect.void;\n      }),\n    handleUnknownExtNotification: (handler) =>\n      Effect.suspend(() => {\n        unknownExtNotificationHandler = handler;\n        return Effect.void;\n      }),\n    handleExtRequest: (method, payload, handler) =>\n      Effect.suspend(() => {\n        extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));\n        return Effect.void;\n      }),\n    handleExtNotification: (method, payload, handler) =>\n      Effect.suspend(() => {\n        extNotificationHandlers.set(\n          method,\n          decodeExtNotificationRegistration(method, payload, handler),\n        );\n        return Effect.void;\n      }),\n  });\n});\n\nexport const layer = (stdio: Stdio.Stdio, options: AcpClientOptions = {}): Layer.Layer<AcpClient> =>\n  Layer.effect(AcpClient, make(stdio, options));\n\nexport const layerChildProcess = (\n  handle: ChildProcessSpawner.ChildProcessHandle,\n  options: AcpClientOptions = {},\n): Layer.Layer<AcpClient> => {\n  const stdio = makeChildStdio(handle);\n  const terminationError = makeTerminationError(handle);\n  return Layer.effect(AcpClient, make(stdio, options, terminationError));\n};\n","/**\n * AcpLocalToolHost — agentlink fork addition.\n *\n * Default client-side implementations of the ACP `fs/*` and `terminal/*`\n * methods. Some ACP agents (Kimi CLI, notably) do not execute their local\n * tools in-process; they delegate shell and file operations to the client\n * through `terminal/create` + `fs/read_text_file` / `fs/write_text_file`.\n * When the client doesn't advertise those capabilities every such tool call\n * fails (\"ACP terminal capability is unavailable\").\n *\n * `AcpSessionRuntime` registers these handlers and advertises the matching\n * client capabilities only when `hostLocalTools` is enabled for the agent\n * (see `AcpAgentDescriptor.hostLocalTools`). Agents that run tools in their\n * own process (Gemini/Qwen today) leave the flag off and are unaffected.\n *\n * @module provider/acp/AcpLocalToolHost\n */\nimport * as Crypto from \"effect/Crypto\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport type * as EffectAcpClient from \"effect-acp/client\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\n/**\n * Fallback cap for retained terminal output when the agent does not send\n * `outputByteLimit`. The spec only bounds output when the agent asks; an\n * unbounded buffer would let a noisy command exhaust daemon memory, so a\n * generous default (2 MB) is applied instead of retaining everything.\n */\nconst DEFAULT_OUTPUT_BYTE_LIMIT = 2_000_000;\n\ntype AcpLocalToolHandlerRegistry = Pick<\n  EffectAcpClient.AcpClient[\"Service\"],\n  | \"handleReadTextFile\"\n  | \"handleWriteTextFile\"\n  | \"handleCreateTerminal\"\n  | \"handleTerminalOutput\"\n  | \"handleTerminalWaitForExit\"\n  | \"handleTerminalKill\"\n  | \"handleTerminalRelease\"\n>;\n\ninterface TerminalState {\n  readonly handle: ChildProcessSpawner.ChildProcessHandle;\n  readonly exited: Deferred.Deferred<EffectAcpSchema.TerminalExitStatus>;\n  output: string;\n  truncated: boolean;\n  exitStatus: EffectAcpSchema.TerminalExitStatus | undefined;\n  /** Signal we deliberately sent via `terminal/kill` / `terminal/release`. */\n  killSignal: string | undefined;\n}\n\nconst internalError = (message: string) => EffectAcpErrors.AcpRequestError.internalError(message);\n\nconst unknownTerminal = (terminalId: string) =>\n  EffectAcpErrors.AcpRequestError.resourceNotFound(`Unknown ACP terminal: ${terminalId}`);\n\nconst isNotFoundCause = (cause: unknown): boolean =>\n  typeof cause === \"object\" &&\n  cause !== null &&\n  (cause as { readonly _tag?: unknown })._tag === \"SystemError\" &&\n  (cause as { readonly reason?: unknown }).reason === \"NotFound\";\n\nconst toFsError = (operation: \"read\" | \"write\", filePath: string, cause: unknown) =>\n  isNotFoundCause(cause)\n    ? EffectAcpErrors.AcpRequestError.resourceNotFound(\n        `Failed to ${operation} file (not found): ${filePath}`,\n      )\n    : internalError(`Failed to ${operation} file: ${filePath}`);\n\n/**\n * Registers local `fs/*` and `terminal/*` handlers on the ACP client.\n * Terminals are tied to the surrounding scope: when the session runtime\n * shuts down, every still-running terminal process is killed with it.\n */\nexport const registerLocalToolHandlers = (input: {\n  readonly acp: AcpLocalToolHandlerRegistry;\n  /** Session cwd; fallback for relative fs paths and `terminal/create` cwd. */\n  readonly cwd: string;\n}): Effect.Effect<\n  void,\n  never,\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | Path.Path\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const crypto = yield* Crypto.Crypto;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const scope = yield* Scope.Scope;\n    const terminals = new Map<string, TerminalState>();\n\n    const resolveFilePath = (filePath: string): string =>\n      path.isAbsolute(filePath) ? filePath : path.join(input.cwd, filePath);\n\n    yield* input.acp.handleReadTextFile((request) =>\n      Effect.gen(function* () {\n        const filePath = resolveFilePath(request.path);\n        const content = yield* fileSystem\n          .readFileString(filePath)\n          .pipe(Effect.mapError((cause) => toFsError(\"read\", filePath, cause)));\n        const lines = content.split(\"\\n\");\n        const start =\n          request.line !== undefined && request.line !== null && request.line > 1\n            ? request.line - 1\n            : 0;\n        const selected =\n          request.limit !== undefined && request.limit !== null\n            ? lines.slice(start, start + request.limit)\n            : lines.slice(start);\n        return { content: selected.join(\"\\n\") } satisfies EffectAcpSchema.ReadTextFileResponse;\n      }),\n    );\n\n    yield* input.acp.handleWriteTextFile((request) =>\n      Effect.gen(function* () {\n        const filePath = resolveFilePath(request.path);\n        // The spec requires the client to create the file when missing;\n        // creating the parent directory keeps that promise for new paths.\n        yield* fileSystem\n          .makeDirectory(path.dirname(filePath), { recursive: true })\n          .pipe(Effect.ignore);\n        yield* fileSystem\n          .writeFileString(filePath, request.content)\n          .pipe(Effect.mapError((cause) => toFsError(\"write\", filePath, cause)));\n        return {} satisfies EffectAcpSchema.WriteTextFileResponse;\n      }),\n    );\n\n    yield* input.acp.handleCreateTerminal((request) =>\n      Effect.gen(function* () {\n        const terminalId = yield* crypto.randomUUIDv4.pipe(\n          Effect.mapError(() => internalError(\"Failed to allocate an ACP terminal id.\")),\n        );\n        const env = (request.env ?? []).reduce<Record<string, string>>((acc, entry) => {\n          acc[entry.name] = entry.value;\n          return acc;\n        }, {});\n        const hasEnv = Object.keys(env).length > 0;\n        const spawnCommand = yield* resolveSpawnCommand(\n          request.command,\n          request.args ?? [],\n          hasEnv ? { env, extendEnv: true } : {},\n        );\n        const handle = yield* spawner\n          .spawn(\n            ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n              cwd: request.cwd ?? input.cwd,\n              ...(hasEnv ? { env, extendEnv: true } : {}),\n              shell: spawnCommand.shell,\n            }),\n          )\n          .pipe(\n            Effect.provideService(Scope.Scope, scope),\n            Effect.mapError(() =>\n              internalError(`Failed to spawn ACP terminal command: ${request.command}`)\n            ),\n          );\n\n        const exited = yield* Deferred.make<EffectAcpSchema.TerminalExitStatus>();\n        const state: TerminalState = {\n          handle,\n          exited,\n          output: \"\",\n          truncated: false,\n          exitStatus: undefined,\n          killSignal: undefined,\n        };\n        const byteLimit = request.outputByteLimit ?? DEFAULT_OUTPUT_BYTE_LIMIT;\n        const decoder = new TextDecoder();\n        const appendOutput = (chunk: Uint8Array) => {\n          state.output += decoder.decode(chunk, { stream: true });\n          // The spec bounds bytes; slicing the JS string stays on a character\n          // boundary by construction and retains slightly less than the limit,\n          // which the spec explicitly allows.\n          if (state.output.length > byteLimit) {\n            state.output = state.output.slice(state.output.length - byteLimit);\n            state.truncated = true;\n          }\n        };\n        yield* Stream.runForEach(handle.all, (chunk) => Effect.sync(() => appendOutput(chunk))).pipe(\n          Effect.ignore,\n          Effect.forkIn(scope),\n        );\n        yield* handle.exitCode.pipe(\n          Effect.match({\n            onFailure: (): EffectAcpSchema.TerminalExitStatus => ({\n              exitCode: null,\n              signal: state.killSignal ?? null,\n            }),\n            onSuccess: (code): EffectAcpSchema.TerminalExitStatus => ({\n              exitCode: Number(code),\n              signal: state.killSignal ?? null,\n            }),\n          }),\n          Effect.flatMap((exitStatus) => {\n            state.exitStatus = exitStatus;\n            return Deferred.succeed(exited, exitStatus);\n          }),\n          Effect.ignore,\n          Effect.forkIn(scope),\n        );\n\n        terminals.set(terminalId, state);\n        return { terminalId } satisfies EffectAcpSchema.CreateTerminalResponse;\n      }),\n    );\n\n    yield* input.acp.handleTerminalOutput((request) =>\n      Effect.sync(() => {\n        const state = terminals.get(request.terminalId);\n        if (!state) {\n          return undefined;\n        }\n        return {\n          output: state.output,\n          truncated: state.truncated,\n          ...(state.exitStatus ? { exitStatus: state.exitStatus } : {}),\n        } satisfies EffectAcpSchema.TerminalOutputResponse;\n      }).pipe(\n        Effect.flatMap((result) =>\n          result === undefined\n            ? Effect.fail(unknownTerminal(request.terminalId))\n            : Effect.succeed(result),\n        ),\n      ),\n    );\n\n    yield* input.acp.handleTerminalWaitForExit((request) =>\n      Effect.gen(function* () {\n        const state = terminals.get(request.terminalId);\n        if (!state) {\n          return yield* unknownTerminal(request.terminalId);\n        }\n        const exitStatus = yield* Deferred.await(state.exited);\n        return exitStatus satisfies EffectAcpSchema.WaitForTerminalExitResponse;\n      }),\n    );\n\n    yield* input.acp.handleTerminalKill((request) =>\n      Effect.gen(function* () {\n        const state = terminals.get(request.terminalId);\n        if (!state) {\n          return yield* unknownTerminal(request.terminalId);\n        }\n        if (state.exitStatus === undefined) {\n          state.killSignal = \"SIGTERM\";\n          yield* state.handle.kill().pipe(Effect.ignore);\n        }\n        return {} satisfies EffectAcpSchema.KillTerminalResponse;\n      }),\n    );\n\n    yield* input.acp.handleTerminalRelease((request) =>\n      Effect.gen(function* () {\n        const state = terminals.get(request.terminalId);\n        if (!state) {\n          return yield* unknownTerminal(request.terminalId);\n        }\n        terminals.delete(request.terminalId);\n        if (state.exitStatus === undefined) {\n          state.killSignal = \"SIGTERM\";\n          yield* state.handle.kill().pipe(Effect.ignore);\n        }\n        return {} satisfies EffectAcpSchema.ReleaseTerminalResponse;\n      }),\n    );\n  });\n","import type { ToolLifecycleItemType } from \"@t3tools/contracts\";\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : undefined;\n}\n\nfunction asTrimmedString(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeCommandValue(value: unknown): string | undefined {\n  const direct = asTrimmedString(value);\n  if (direct) {\n    return direct;\n  }\n  if (!Array.isArray(value)) {\n    return undefined;\n  }\n  const parts: string[] = [];\n  for (const entry of value) {\n    const part = asTrimmedString(entry);\n    if (part !== undefined) {\n      parts.push(part);\n    }\n  }\n  return parts.length > 0 ? parts.join(\" \") : undefined;\n}\n\nfunction stripTrailingExitCode(value: string | undefined): string | undefined {\n  const trimmed = value?.trim();\n  if (!trimmed) {\n    return undefined;\n  }\n  const match = /^(?<output>[\\s\\S]*?)(?:\\s*<exited with exit code \\d+>)\\s*$/iu.exec(trimmed);\n  const output = match?.groups?.output?.trim() ?? trimmed;\n  return output.length > 0 ? output : undefined;\n}\n\nfunction extractCommandFromTitle(title: string | undefined): string | undefined {\n  if (!title) {\n    return undefined;\n  }\n  const backtickMatch = /`([^`]+)`/u.exec(title);\n  return backtickMatch?.[1]?.trim() || undefined;\n}\n\nfunction extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {\n  const item = asRecord(data?.item);\n  const itemInput = asRecord(item?.input);\n  const itemResult = asRecord(item?.result);\n  const rawInput = asRecord(data?.rawInput);\n  const candidates = [\n    normalizeCommandValue(item?.command),\n    normalizeCommandValue(itemInput?.command),\n    normalizeCommandValue(itemResult?.command),\n    normalizeCommandValue(data?.command),\n    normalizeCommandValue(rawInput?.command),\n  ];\n  const direct = candidates.find((candidate) => candidate !== undefined);\n  if (direct) {\n    return direct;\n  }\n  const executable = asTrimmedString(rawInput?.executable);\n  const args = normalizeCommandValue(rawInput?.args);\n  if (executable && args) {\n    return `${executable} ${args}`;\n  }\n  if (executable) {\n    return executable;\n  }\n  return extractCommandFromTitle(title);\n}\n\nfunction maybePathLike(value: string | undefined): string | undefined {\n  if (!value) {\n    return undefined;\n  }\n  if (\n    value.includes(\"/\") ||\n    value.includes(\"\\\\\") ||\n    value.startsWith(\".\") ||\n    /\\.(?:[a-z0-9]{1,12})$/iu.test(value)\n  ) {\n    return value;\n  }\n  return undefined;\n}\n\nfunction collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {\n  if (depth > 4 || paths.length >= 8) {\n    return;\n  }\n  if (Array.isArray(value)) {\n    for (const entry of value) {\n      collectPaths(entry, paths, seen, depth + 1);\n      if (paths.length >= 8) {\n        return;\n      }\n    }\n    return;\n  }\n  const record = asRecord(value);\n  if (!record) {\n    return;\n  }\n  for (const key of [\"path\", \"filePath\", \"relativePath\", \"filename\", \"newPath\", \"oldPath\"]) {\n    const candidate = maybePathLike(asTrimmedString(record[key]));\n    if (!candidate || seen.has(candidate)) {\n      continue;\n    }\n    seen.add(candidate);\n    paths.push(candidate);\n    if (paths.length >= 8) {\n      return;\n    }\n  }\n  for (const nestedKey of [\"locations\", \"item\", \"input\", \"result\", \"rawInput\", \"data\", \"changes\"]) {\n    if (!(nestedKey in record)) {\n      continue;\n    }\n    collectPaths(record[nestedKey], paths, seen, depth + 1);\n    if (paths.length >= 8) {\n      return;\n    }\n  }\n}\n\nfunction extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {\n  const paths: string[] = [];\n  collectPaths(data, paths, new Set<string>(), 0);\n  return paths[0];\n}\n\nfunction normalizeEquivalentValue(value: string | undefined): string | undefined {\n  const trimmed = asTrimmedString(value);\n  if (!trimmed) {\n    return undefined;\n  }\n  return trimmed\n    .replace(/\\s+/gu, \" \")\n    .replace(/\\s+(?:complete|completed|started)\\s*$/iu, \"\")\n    .trim();\n}\n\nfunction isEquivalent(left: string | undefined, right: string | undefined): boolean {\n  const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();\n  const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();\n  return normalizedLeft !== undefined && normalizedLeft === normalizedRight;\n}\n\nfunction classifyToolAction(input: {\n  readonly itemType?: ToolLifecycleItemType | null | undefined;\n  readonly title?: string | undefined;\n  readonly data?: Record<string, unknown> | undefined;\n}): \"command\" | \"read\" | \"file_change\" | \"search\" | \"other\" {\n  const itemType = input.itemType ?? undefined;\n  const kind = asTrimmedString(input.data?.kind)?.toLowerCase();\n  const title = asTrimmedString(input.title)?.toLowerCase();\n  if (itemType === \"command_execution\" || kind === \"execute\" || title === \"terminal\") {\n    return \"command\";\n  }\n  if (kind === \"read\" || title === \"read file\") {\n    return \"read\";\n  }\n  if (\n    itemType === \"file_change\" ||\n    kind === \"edit\" ||\n    kind === \"move\" ||\n    kind === \"delete\" ||\n    kind === \"write\"\n  ) {\n    return \"file_change\";\n  }\n  if (itemType === \"web_search\" || kind === \"search\" || title === \"find\" || title === \"grep\") {\n    return \"search\";\n  }\n  return \"other\";\n}\n\nexport interface ToolActivityPresentationInput {\n  readonly itemType?: ToolLifecycleItemType | null | undefined;\n  readonly title?: string | null | undefined;\n  readonly detail?: string | null | undefined;\n  readonly data?: unknown;\n  readonly fallbackSummary?: string | null | undefined;\n}\n\nexport interface ToolActivityPresentation {\n  readonly summary: string;\n  readonly detail?: string | undefined;\n}\n\nexport function deriveToolActivityPresentation(\n  input: ToolActivityPresentationInput,\n): ToolActivityPresentation {\n  const title = asTrimmedString(input.title);\n  const detail = stripTrailingExitCode(asTrimmedString(input.detail));\n  const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? \"Tool\";\n  const data = asRecord(input.data);\n  const command = extractToolCommand(data, title);\n  const primaryPath = extractPrimaryPath(data);\n  const action = classifyToolAction({\n    itemType: input.itemType,\n    title,\n    data,\n  });\n\n  if (action === \"command\") {\n    return {\n      summary: \"Ran command\",\n      ...(command ? { detail: command } : {}),\n    };\n  }\n\n  if (action === \"read\") {\n    if (primaryPath) {\n      return {\n        summary: \"Read file\",\n        detail: primaryPath,\n      };\n    }\n    return {\n      summary: \"Read file\",\n    };\n  }\n\n  if (action === \"file_change\") {\n    return {\n      summary: \"Changed files\",\n      ...(primaryPath ? { detail: primaryPath } : {}),\n    };\n  }\n\n  if (action === \"search\") {\n    const query =\n      asTrimmedString(asRecord(data?.rawInput)?.query) ??\n      asTrimmedString(asRecord(data?.rawInput)?.pattern) ??\n      asTrimmedString(asRecord(data?.rawInput)?.searchTerm);\n    return {\n      summary: \"Searched files\",\n      ...(query ? { detail: query } : {}),\n    };\n  }\n\n  if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {\n    return {\n      summary: title ?? fallbackSummary,\n      detail,\n    };\n  }\n\n  return {\n    summary: title ?? fallbackSummary,\n  };\n}\n","import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { deriveToolActivityPresentation } from \"@t3tools/shared/toolActivity\";\nimport type { ToolLifecycleItemType } from \"@t3tools/contracts\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {\n  if (!isRecord(value) || typeof value.currentModelId !== \"string\") {\n    return false;\n  }\n  if (!Array.isArray(value.availableModels)) {\n    return false;\n  }\n  return value.availableModels.every(\n    (model) =>\n      isRecord(model) &&\n      typeof model.modelId === \"string\" &&\n      typeof model.name === \"string\" &&\n      (model.description === undefined ||\n        model.description === null ||\n        typeof model.description === \"string\"),\n  );\n}\n\nfunction isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {\n  if (!isRecord(value) || typeof value.currentModeId !== \"string\") {\n    return false;\n  }\n  if (!Array.isArray(value.availableModes)) {\n    return false;\n  }\n  return value.availableModes.every(\n    (mode) =>\n      isRecord(mode) &&\n      typeof mode.id === \"string\" &&\n      typeof mode.name === \"string\" &&\n      (mode.description === undefined || typeof mode.description === \"string\"),\n  );\n}\n\nexport interface AcpSessionMode {\n  readonly id: string;\n  readonly name: string;\n  readonly description?: string;\n}\n\nexport interface AcpSessionModeState {\n  readonly currentModeId: string;\n  readonly availableModes: ReadonlyArray<AcpSessionMode>;\n}\n\nexport interface AcpToolCallState {\n  readonly toolCallId: string;\n  readonly kind?: string;\n  readonly title?: string;\n  readonly status?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\";\n  readonly command?: string;\n  readonly detail?: string;\n  readonly data: Record<string, unknown>;\n}\n\nexport interface AcpPlanUpdate {\n  readonly explanation?: string | null;\n  readonly plan: ReadonlyArray<{\n    readonly step: string;\n    readonly status: \"pending\" | \"inProgress\" | \"completed\";\n  }>;\n}\n\nexport interface AcpPermissionRequest {\n  readonly kind: string | \"unknown\";\n  readonly detail?: string;\n  readonly toolCall?: AcpToolCallState;\n}\n\nexport type AcpParsedSessionEvent =\n  | {\n      readonly _tag: \"ModeChanged\";\n      readonly modeId: string;\n    }\n  | {\n      readonly _tag: \"AssistantItemStarted\";\n      readonly itemId: string;\n    }\n  | {\n      readonly _tag: \"AssistantItemCompleted\";\n      readonly itemId: string;\n    }\n  | {\n      readonly _tag: \"PlanUpdated\";\n      readonly payload: AcpPlanUpdate;\n      readonly rawPayload: unknown;\n    }\n  | {\n      readonly _tag: \"ToolCallUpdated\";\n      readonly toolCall: AcpToolCallState;\n      readonly rawPayload: unknown;\n    }\n  | {\n      readonly _tag: \"ContentDelta\";\n      readonly itemId?: string;\n      readonly text: string;\n      readonly rawPayload: unknown;\n    };\n\ntype AcpSessionSetupResponse =\n  | EffectAcpSchema.LoadSessionResponse\n  | EffectAcpSchema.NewSessionResponse\n  | EffectAcpSchema.ResumeSessionResponse;\n\ntype AcpToolCallUpdate = Extract<\n  EffectAcpSchema.SessionNotification[\"update\"],\n  { readonly sessionUpdate: \"tool_call\" | \"tool_call_update\" }\n>;\n\nexport function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {\n  const configOptions = sessionResponse.configOptions;\n  if (!configOptions) return undefined;\n  for (const opt of configOptions) {\n    if (opt.category === \"model\" && opt.id.trim().length > 0) {\n      return opt.id.trim();\n    }\n  }\n  return undefined;\n}\n\nexport function findSessionConfigOption(\n  configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,\n  configId: string,\n): EffectAcpSchema.SessionConfigOption | undefined {\n  if (!configOptions) {\n    return undefined;\n  }\n  const normalizedConfigId = configId.trim();\n  if (!normalizedConfigId) {\n    return undefined;\n  }\n  return configOptions.find((option) => option.id.trim() === normalizedConfigId);\n}\n\nexport function collectSessionConfigOptionValues(\n  configOption: EffectAcpSchema.SessionConfigOption,\n): ReadonlyArray<string> {\n  if (configOption.type !== \"select\") {\n    return [];\n  }\n  return configOption.options.flatMap((entry) =>\n    \"value\" in entry ? [entry.value] : entry.options.map((option) => option.value),\n  );\n}\n\nexport function parseSessionModeState(\n  sessionResponse: AcpSessionSetupResponse,\n): AcpSessionModeState | undefined {\n  const modes = sessionResponse.modes;\n  if (!modes) return undefined;\n  const currentModeId = modes.currentModeId.trim();\n  if (!currentModeId) {\n    return undefined;\n  }\n  const availableModes: Array<AcpSessionMode> = [];\n  for (const mode of modes.availableModes) {\n    const id = mode.id.trim();\n    const name = mode.name.trim();\n    if (!id || !name) {\n      continue;\n    }\n    const description = mode.description?.trim() || undefined;\n    availableModes.push(\n      description !== undefined\n        ? ({ id, name, description } satisfies AcpSessionMode)\n        : ({ id, name } satisfies AcpSessionMode),\n    );\n  }\n  if (availableModes.length === 0) {\n    return undefined;\n  }\n  return {\n    currentModeId,\n    availableModes,\n  };\n}\n\nfunction normalizePlanStepStatus(raw: unknown): \"pending\" | \"inProgress\" | \"completed\" {\n  switch (raw) {\n    case \"completed\":\n      return \"completed\";\n    case \"in_progress\":\n    case \"inProgress\":\n      return \"inProgress\";\n    default:\n      return \"pending\";\n  }\n}\n\nfunction normalizeToolCallStatus(\n  raw: unknown,\n  fallback?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\",\n): \"pending\" | \"inProgress\" | \"completed\" | \"failed\" | undefined {\n  switch (raw) {\n    case \"pending\":\n      return \"pending\";\n    case \"in_progress\":\n    case \"inProgress\":\n      return \"inProgress\";\n    case \"completed\":\n      return \"completed\";\n    case \"failed\":\n      return \"failed\";\n    default:\n      return fallback;\n  }\n}\n\nfunction normalizeCommandValue(value: unknown): string | undefined {\n  if (typeof value === \"string\" && value.trim().length > 0) {\n    return value.trim();\n  }\n  if (!Array.isArray(value)) {\n    return undefined;\n  }\n  const parts: Array<string> = [];\n  for (const entry of value) {\n    if (typeof entry === \"string\") {\n      const part = entry.trim();\n      if (part.length > 0) {\n        parts.push(part);\n      }\n    }\n  }\n  return parts.length > 0 ? parts.join(\" \") : undefined;\n}\n\nfunction extractCommandFromTitle(title: string | undefined): string | undefined {\n  if (!title) {\n    return undefined;\n  }\n  const match = /`([^`]+)`/.exec(title);\n  return match?.[1]?.trim() || undefined;\n}\n\nfunction extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {\n  if (isRecord(rawInput)) {\n    const directCommand = normalizeCommandValue(rawInput.command);\n    if (directCommand) {\n      return directCommand;\n    }\n    const executable = typeof rawInput.executable === \"string\" ? rawInput.executable.trim() : \"\";\n    const args = normalizeCommandValue(rawInput.args);\n    if (executable && args) {\n      return `${executable} ${args}`;\n    }\n    if (executable) {\n      return executable;\n    }\n  }\n  return extractCommandFromTitle(title);\n}\n\nfunction extractTextContentFromToolCallContent(\n  content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,\n): string | undefined {\n  if (!content) return undefined;\n  const chunks: Array<string> = [];\n  for (const entry of content) {\n    if (entry.type !== \"content\") {\n      continue;\n    }\n    const nestedContent = entry.content;\n    if (nestedContent.type !== \"text\") {\n      continue;\n    }\n    const text = nestedContent.text.trim();\n    if (text.length > 0) {\n      chunks.push(text);\n    }\n  }\n  return chunks.length > 0 ? chunks.join(\"\\n\") : undefined;\n}\n\nfunction normalizeToolKind(kind: unknown): string | undefined {\n  return typeof kind === \"string\" && kind.trim().length > 0 ? kind.trim() : undefined;\n}\n\nfunction canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {\n  switch (kind) {\n    case \"execute\":\n      return \"command_execution\";\n    case \"edit\":\n    case \"delete\":\n    case \"move\":\n      return \"file_change\";\n    case \"search\":\n    case \"fetch\":\n      return \"web_search\";\n    default:\n      return \"dynamic_tool_call\";\n  }\n}\n\nfunction makeToolCallState(\n  input: {\n    readonly toolCallId: string;\n    readonly title?: string | null | undefined;\n    readonly kind?: EffectAcpSchema.ToolKind | null | undefined;\n    readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;\n    readonly rawInput?: unknown;\n    readonly rawOutput?: unknown;\n    readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;\n    readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;\n  },\n  options?: {\n    readonly fallbackStatus?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\";\n  },\n): AcpToolCallState | undefined {\n  const toolCallId = input.toolCallId.trim();\n  if (!toolCallId) {\n    return undefined;\n  }\n  const title = input.title?.trim() || undefined;\n  const command = extractToolCallCommand(input.rawInput, title);\n  const textContent = extractTextContentFromToolCallContent(input.content);\n  const normalizedTitle =\n    title && title.toLowerCase() !== \"terminal\" && title.toLowerCase() !== \"tool call\"\n      ? title\n      : undefined;\n  const data: Record<string, unknown> = { toolCallId };\n  const kind = normalizeToolKind(input.kind);\n  if (kind) {\n    data.kind = kind;\n  }\n  if (command) {\n    data.command = command;\n  }\n  if (input.rawInput !== undefined) {\n    data.rawInput = input.rawInput;\n  }\n  if (input.rawOutput !== undefined) {\n    data.rawOutput = input.rawOutput;\n  }\n  if (input.content !== undefined) {\n    data.content = input.content;\n  }\n  if (input.locations !== undefined) {\n    data.locations = input.locations;\n  }\n  const fallbackDetail = command ?? normalizedTitle ?? textContent;\n  const hasPresentationSeed =\n    title !== undefined ||\n    kind !== undefined ||\n    command !== undefined ||\n    normalizedTitle !== undefined ||\n    textContent !== undefined;\n  const presentation = hasPresentationSeed\n    ? deriveToolActivityPresentation({\n        itemType: canonicalItemTypeFromAcpToolKind(kind),\n        title,\n        detail: fallbackDetail,\n        data,\n        fallbackSummary: title ?? \"Tool\",\n      })\n    : undefined;\n  const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);\n  return {\n    toolCallId,\n    ...(kind ? { kind } : {}),\n    ...(presentation?.summary ? { title: presentation.summary } : {}),\n    ...(status ? { status } : {}),\n    ...(command ? { command } : {}),\n    ...(presentation?.detail ? { detail: presentation.detail } : {}),\n    data,\n  };\n}\n\nfunction parseTypedToolCallState(\n  event: AcpToolCallUpdate,\n  options?: {\n    readonly fallbackStatus?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\";\n  },\n): AcpToolCallState | undefined {\n  return makeToolCallState(\n    {\n      toolCallId: event.toolCallId,\n      title: event.title,\n      kind: event.kind,\n      status: event.status,\n      rawInput: event.rawInput,\n      rawOutput: event.rawOutput,\n      content: event.content,\n      locations: event.locations,\n    },\n    options,\n  );\n}\n\nexport function mergeToolCallState(\n  previous: AcpToolCallState | undefined,\n  next: AcpToolCallState,\n): AcpToolCallState {\n  const nextKind = typeof next.data.kind === \"string\" ? next.data.kind : undefined;\n  const kind = nextKind ?? previous?.kind;\n  const title = next.title ?? previous?.title;\n  const status = next.status ?? previous?.status;\n  const command = next.command ?? previous?.command;\n  const detail = next.detail ?? previous?.detail;\n  return {\n    toolCallId: next.toolCallId,\n    ...(kind ? { kind } : {}),\n    ...(title ? { title } : {}),\n    ...(status ? { status } : {}),\n    ...(command ? { command } : {}),\n    ...(detail ? { detail } : {}),\n    data: {\n      ...previous?.data,\n      ...next.data,\n    },\n  };\n}\n\nexport function parsePermissionRequest(\n  params: EffectAcpSchema.RequestPermissionRequest,\n): AcpPermissionRequest {\n  const toolCall = makeToolCallState(\n    {\n      toolCallId: params.toolCall.toolCallId,\n      title: params.toolCall.title,\n      kind: params.toolCall.kind,\n      status: params.toolCall.status,\n      rawInput: params.toolCall.rawInput,\n      rawOutput: params.toolCall.rawOutput,\n      content: params.toolCall.content,\n      locations: params.toolCall.locations,\n    },\n    { fallbackStatus: \"pending\" },\n  );\n  const kind = normalizeToolKind(params.toolCall.kind) ?? \"unknown\";\n  const detail =\n    toolCall?.command ??\n    toolCall?.title ??\n    toolCall?.detail ??\n    (typeof params.sessionId === \"string\" ? `Session ${params.sessionId}` : undefined);\n  return {\n    kind,\n    ...(detail ? { detail } : {}),\n    ...(toolCall ? { toolCall } : {}),\n  };\n}\n\nexport function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {\n  const meta = params._meta;\n  return isRecord(meta) && meta.isReplay === true;\n}\n\nexport interface SessionLoadGate {\n  readonly active: boolean;\n  readonly lastActivityAtMillis: number | undefined;\n  readonly idleGap: Duration.Duration;\n  readonly initializeResult: EffectAcpSchema.InitializeResponse;\n}\n\nexport const waitForSessionLoadReplayIdle = (input: {\n  readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;\n}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>\n  Effect.gen(function* () {\n    const pollInterval = Duration.millis(25);\n    while (true) {\n      const gate = yield* Ref.get(input.gateRef);\n      if (\n        Option.isSome(gate) &&\n        gate.value.active &&\n        gate.value.lastActivityAtMillis !== undefined\n      ) {\n        const idleGapMillis = Duration.toMillis(gate.value.idleGap);\n        const nowMillis = yield* Clock.currentTimeMillis;\n        if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {\n          return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);\n        }\n      }\n      yield* Effect.sleep(pollInterval);\n    }\n  });\n\nexport function syntheticLoadSessionResponseFromInitialize(\n  initializeResult: EffectAcpSchema.InitializeResponse,\n): EffectAcpSchema.LoadSessionResponse {\n  const meta = initializeResult._meta;\n  const modelState = isRecord(meta) ? meta.modelState : undefined;\n  const modeState = isRecord(meta) ? meta.modeState : undefined;\n  const models = isSessionModelState(modelState) ? modelState : undefined;\n  const modes = isSessionModeState(modeState) ? modeState : undefined;\n\n  return {\n    ...(models ? { models } : {}),\n    ...(modes ? { modes } : {}),\n    _meta: {\n      t3SessionLoadReady: \"replay_idle\",\n    },\n  };\n}\n\nexport function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {\n  readonly modeId?: string;\n  readonly events: ReadonlyArray<AcpParsedSessionEvent>;\n} {\n  const upd = params.update;\n  const events: Array<AcpParsedSessionEvent> = [];\n  let modeId: string | undefined;\n\n  switch (upd.sessionUpdate) {\n    case \"current_mode_update\": {\n      modeId = upd.currentModeId.trim();\n      if (modeId) {\n        events.push({\n          _tag: \"ModeChanged\",\n          modeId,\n        });\n      }\n      break;\n    }\n    case \"plan\": {\n      const plan = upd.entries.map((entry, index) => ({\n        step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,\n        status: normalizePlanStepStatus(entry.status),\n      }));\n      if (plan.length > 0) {\n        events.push({\n          _tag: \"PlanUpdated\",\n          payload: {\n            plan,\n          },\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    case \"tool_call\": {\n      const toolCall = parseTypedToolCallState(upd, {\n        fallbackStatus: \"pending\",\n      });\n      if (toolCall) {\n        events.push({\n          _tag: \"ToolCallUpdated\",\n          toolCall,\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    case \"tool_call_update\": {\n      const toolCall = parseTypedToolCallState(upd);\n      if (toolCall) {\n        events.push({\n          _tag: \"ToolCallUpdated\",\n          toolCall,\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    case \"agent_message_chunk\": {\n      if (upd.content.type === \"text\" && upd.content.text.length > 0) {\n        events.push({\n          _tag: \"ContentDelta\",\n          text: upd.content.text,\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    default:\n      break;\n  }\n\n  return { ...(modeId !== undefined ? { modeId } : {}), events };\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as EffectAcpClient from \"effect-acp/client\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport type * as EffectAcpProtocol from \"effect-acp/protocol\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport { registerLocalToolHandlers } from \"./AcpLocalToolHost.ts\";\nimport {\n  collectSessionConfigOptionValues,\n  extractModelConfigId,\n  findSessionConfigOption,\n  mergeToolCallState,\n  parseSessionModeState,\n  parseSessionUpdateEvent,\n  sessionUpdateIsReplay,\n  waitForSessionLoadReplayIdle,\n  type SessionLoadGate,\n  type AcpParsedSessionEvent,\n  type AcpSessionModeState,\n  type AcpToolCallState,\n} from \"./AcpRuntimeModel.ts\";\n\nfunction formatConfigOptionValue(value: string | boolean): string {\n  return JSON.stringify(value);\n}\n\nfunction safeProcessCommand(command: string): string {\n  const basename = command.split(/[\\\\/]/).at(-1) ?? \"unknown\";\n  return basename.length <= 128 && /^[A-Za-z0-9._-]+$/.test(basename) ? basename : \"unknown\";\n}\n\nfunction safeArgumentKind(argument: string): \"flag\" | \"positional\" {\n  return argument.startsWith(\"-\") ? \"flag\" : \"positional\";\n}\n\nfunction safeErrorTag(error: unknown): string {\n  if (error !== null && typeof error === \"object\" && \"_tag\" in error) {\n    const tag = (error as { readonly _tag?: unknown })._tag;\n    if (typeof tag === \"string\" && /^[A-Za-z][A-Za-z0-9._-]*$/.test(tag)) return tag;\n  }\n  return \"unknown\";\n}\n\nexport interface AcpSessionEventStreamBarrier {\n  readonly _tag: \"EventStreamBarrier\";\n  readonly acknowledge: Deferred.Deferred<void>;\n}\n\nexport type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;\n\nconst defaultSessionLoadTimeout = Duration.seconds(90);\nconst defaultSessionLoadReplayIdleGap = Duration.seconds(2);\n\nexport interface AcpSpawnInput {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd?: string;\n  readonly env?: NodeJS.ProcessEnv;\n}\n\nexport interface AcpSessionRuntimeOptions {\n  readonly spawn: AcpSpawnInput;\n  readonly cwd: string;\n  readonly resumeSessionId?: string;\n  readonly sessionLoadTimeout?: Duration.Input;\n  readonly sessionLoadReplayIdleGap?: Duration.Input;\n  readonly clientCapabilities?: EffectAcpSchema.InitializeRequest[\"clientCapabilities\"];\n  readonly clientInfo: {\n    readonly name: string;\n    readonly version: string;\n  };\n  readonly authMethodId: string;\n  /**\n   * When true, the `authenticate` request is skipped entirely during startup.\n   * agentlink fork addition: ACP CLIs that are already logged in via their own\n   * config (Gemini/Qwen/Kimi) reject unknown auth method ids, which would abort\n   * startup; drivers for such agents set this flag instead of inventing an id.\n   */\n  readonly skipAuthentication?: boolean;\n  /**\n   * agentlink fork addition: when true, the runtime advertises the ACP\n   * `fs` and `terminal` client capabilities and hosts them locally (see\n   * `AcpLocalToolHost.ts`). Required for agents that delegate shell/file\n   * tools to the client instead of executing them in-process (Kimi CLI).\n   */\n  readonly hostLocalTools?: boolean;\n  readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;\n  readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;\n  readonly protocolLogging?: {\n    readonly logIncoming?: boolean;\n    readonly logOutgoing?: boolean;\n    readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;\n  };\n}\n\nexport interface AcpSessionRequestLogEvent {\n  readonly method: string;\n  readonly payload: unknown;\n  readonly status: \"started\" | \"succeeded\" | \"failed\";\n  readonly result?: unknown;\n  readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;\n}\n\nexport interface AcpSessionRuntimeStartResult {\n  readonly sessionId: string;\n  readonly initializeResult: EffectAcpSchema.InitializeResponse;\n  readonly sessionSetupResult:\n    | EffectAcpSchema.LoadSessionResponse\n    | EffectAcpSchema.NewSessionResponse\n    | EffectAcpSchema.ResumeSessionResponse;\n  readonly modelConfigId: string | undefined;\n}\n\nexport class AcpSessionRuntime extends Context.Service<\n  AcpSessionRuntime,\n  {\n    /**\n     * Registers a handler for `session/request_permission`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/request_permission\n     */\n    readonly handleRequestPermission: EffectAcpClient.AcpClient[\"Service\"][\"handleRequestPermission\"];\n    /**\n     * Registers a handler for `session/elicitation`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation\n     */\n    readonly handleElicitation: EffectAcpClient.AcpClient[\"Service\"][\"handleElicitation\"];\n    /**\n     * Registers a handler for `fs/read_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file\n     */\n    readonly handleReadTextFile: EffectAcpClient.AcpClient[\"Service\"][\"handleReadTextFile\"];\n    /**\n     * Registers a handler for `fs/write_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file\n     */\n    readonly handleWriteTextFile: EffectAcpClient.AcpClient[\"Service\"][\"handleWriteTextFile\"];\n    /**\n     * Registers a handler for `terminal/create`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/create\n     */\n    readonly handleCreateTerminal: EffectAcpClient.AcpClient[\"Service\"][\"handleCreateTerminal\"];\n    /**\n     * Registers a handler for `terminal/output`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/output\n     */\n    readonly handleTerminalOutput: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalOutput\"];\n    /**\n     * Registers a handler for `terminal/wait_for_exit`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit\n     */\n    readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalWaitForExit\"];\n    /**\n     * Registers a handler for `terminal/kill`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/kill\n     */\n    readonly handleTerminalKill: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalKill\"];\n    /**\n     * Registers a handler for `terminal/release`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/release\n     */\n    readonly handleTerminalRelease: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalRelease\"];\n    /**\n     * Registers a handler for `session/update`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/update\n     */\n    readonly handleSessionUpdate: EffectAcpClient.AcpClient[\"Service\"][\"handleSessionUpdate\"];\n    /**\n     * Registers a handler for `session/elicitation/complete`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete\n     */\n    readonly handleElicitationComplete: EffectAcpClient.AcpClient[\"Service\"][\"handleElicitationComplete\"];\n    /**\n     * Registers a fallback extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtRequest: EffectAcpClient.AcpClient[\"Service\"][\"handleUnknownExtRequest\"];\n    /**\n     * Registers a fallback extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtNotification: EffectAcpClient.AcpClient[\"Service\"][\"handleUnknownExtNotification\"];\n    /**\n     * Registers a typed extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtRequest: EffectAcpClient.AcpClient[\"Service\"][\"handleExtRequest\"];\n    /**\n     * Registers a typed extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtNotification: EffectAcpClient.AcpClient[\"Service\"][\"handleExtNotification\"];\n    /**\n     * Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.\n     * Concurrent calls share the same in-flight startup and a failed startup may be retried.\n     */\n    readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;\n    /** Stream of parsed ACP session events emitted after startup. */\n    readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;\n    /** Waits until the current event consumer has processed every queued event. */\n    readonly drainEvents: Effect.Effect<void>;\n    /** Latest mode state observed from session setup and `session/update` notifications. */\n    readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;\n    /** Latest configuration options observed from session setup and configuration writes. */\n    readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;\n    /**\n     * Sends a prompt turn to the active session.\n     * @see https://agentclientprotocol.com/protocol/schema#session/prompt\n     */\n    readonly prompt: (\n      payload: Omit<EffectAcpSchema.PromptRequest, \"sessionId\">,\n    ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Sends a real ACP `session/cancel` notification for the active session.\n     * @see https://agentclientprotocol.com/protocol/schema#session/cancel\n     */\n    readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;\n    /**\n     * Selects the active mode through the negotiated `mode` configuration option.\n     * This is a no-op when the requested mode is already active.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n     */\n    readonly setMode: (\n      modeId: string,\n    ) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Updates a session configuration option and the runtime configuration snapshot.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n     */\n    readonly setConfigOption: (\n      configId: string,\n      value: string | boolean,\n    ) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Selects the base model through the negotiated model configuration option.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n     */\n    readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;\n    /**\n     * Selects the active model through the unstable ACP `session/set_model` capability.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_model\n     */\n    readonly setSessionModel: (\n      modelId: string,\n    ) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Sends a generic ACP extension request and records it through the request logger.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly request: (\n      method: string,\n      payload: unknown,\n    ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;\n    /**\n     * Sends a generic ACP extension notification.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly notify: (\n      method: string,\n      payload: unknown,\n    ) => Effect.Effect<void, EffectAcpErrors.AcpError>;\n  }\n>()(\"t3/provider/acp/AcpSessionRuntime\") {}\n\ninterface AcpStartedState extends AcpSessionRuntimeStartResult {}\n\ntype AcpStartState =\n  | { readonly _tag: \"NotStarted\" }\n  | {\n      readonly _tag: \"Starting\";\n      readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;\n    }\n  | { readonly _tag: \"Started\"; readonly result: AcpStartedState };\n\ninterface AcpAssistantSegmentState {\n  readonly nextSegmentIndex: number;\n  readonly activeItemId?: string;\n}\n\ninterface EnsureActiveAssistantSegmentResult {\n  readonly itemId: string;\n  readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: \"AssistantItemStarted\" }>;\n}\n\nexport const make = (\n  options: AcpSessionRuntimeOptions,\n): Effect.Effect<\n  AcpSessionRuntime[\"Service\"],\n  EffectAcpErrors.AcpError,\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | Scope.Scope\n  | FileSystem.FileSystem\n  | Path.Path\n> =>\n  Effect.gen(function* () {\n    const crypto = yield* Crypto.Crypto;\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const runtimeScope = yield* Scope.Scope;\n    const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();\n    const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);\n    const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());\n    const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new EffectAcpErrors.AcpTransportError({\n            detail: \"Failed to generate an ACP assistant item runtime identifier.\",\n            cause,\n          }),\n      ),\n    );\n    const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });\n    const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));\n    const startStateRef = yield* Ref.make<AcpStartState>({ _tag: \"NotStarted\" });\n    const promptSerializationSemaphore = yield* Semaphore.make(1);\n    const activePromptFiberRef = yield* Ref.make<\n      Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>\n    >(Option.none());\n    const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());\n\n    const logRequest = (event: AcpSessionRequestLogEvent) =>\n      options.requestLogger ? options.requestLogger(event) : Effect.void;\n\n    const runLoggedRequest = <A>(\n      method: string,\n      payload: unknown,\n      effect: Effect.Effect<A, EffectAcpErrors.AcpError>,\n    ): Effect.Effect<A, EffectAcpErrors.AcpError> =>\n      logRequest({ method, payload, status: \"started\" }).pipe(\n        Effect.flatMap(() =>\n          effect.pipe(\n            Effect.tap((result) =>\n              logRequest({\n                method,\n                payload,\n                status: \"succeeded\",\n                result,\n              }),\n            ),\n            Effect.onError((cause) =>\n              logRequest({\n                method,\n                payload,\n                status: \"failed\",\n                cause,\n              }),\n            ),\n          ),\n        ),\n      );\n\n    const spawnCommand = yield* resolveSpawnCommand(\n      options.spawn.command,\n      options.spawn.args,\n      options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {},\n    );\n    const child = yield* spawner\n      .spawn(\n        ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n          ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),\n          ...(options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {}),\n          shell: spawnCommand.shell,\n        }),\n      )\n      .pipe(\n        Effect.provideService(Scope.Scope, runtimeScope),\n        Effect.mapError(\n          (cause) =>\n            new EffectAcpErrors.AcpSpawnError({\n              command: options.spawn.command,\n              cause,\n            }),\n        ),\n      );\n\n    const logProcessEvent = (\n      stage: \"process_spawned\" | \"process_stderr\" | \"process_exited\",\n      payload: Readonly<Record<string, unknown>>,\n    ) =>\n      options.protocolLogging?.logger?.({ direction: \"incoming\", stage, payload }) ?? Effect.void;\n\n    yield* logProcessEvent(\"process_spawned\", {\n      command: safeProcessCommand(spawnCommand.command),\n      argumentCount: Math.min(spawnCommand.args.length, 1_000),\n      argumentKinds: spawnCommand.args.slice(0, 32).map(safeArgumentKind),\n      pid: child.pid,\n    });\n\n    yield* child.stderr.pipe(\n      Stream.runForEach((chunk) => {\n        const text = new TextDecoder().decode(chunk);\n        return logProcessEvent(\"process_stderr\", {\n          pid: child.pid,\n          byteLength: chunk.byteLength,\n          lineBreakCount: Math.min(text.match(/\\n/g)?.length ?? 0, 10_000),\n        });\n      }),\n      Effect.catch((error) =>\n        logProcessEvent(\"process_stderr\", {\n          pid: child.pid,\n          errorTag: safeErrorTag(error),\n        }),\n      ),\n      Effect.forkIn(runtimeScope),\n    );\n\n    yield* child.exitCode.pipe(\n      Effect.matchEffect({\n        onFailure: (error) =>\n          logProcessEvent(\"process_exited\", {\n            pid: child.pid,\n            errorTag: safeErrorTag(error),\n          }),\n        onSuccess: (exitCode) =>\n          logProcessEvent(\"process_exited\", {\n            pid: child.pid,\n            exitCode,\n          }),\n      }),\n      Effect.forkIn(runtimeScope),\n    );\n\n    const acpContext = yield* Layer.build(\n      EffectAcpClient.layerChildProcess(child, {\n        ...(options.protocolLogging?.logIncoming !== undefined\n          ? { logIncoming: options.protocolLogging.logIncoming }\n          : {}),\n        ...(options.protocolLogging?.logOutgoing !== undefined\n          ? { logOutgoing: options.protocolLogging.logOutgoing }\n          : {}),\n        ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),\n      }),\n    ).pipe(Effect.provideService(Scope.Scope, runtimeScope));\n\n    const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));\n\n    yield* acp.handleSessionUpdate((notification) =>\n      Effect.gen(function* () {\n        const gate = yield* Ref.get(sessionLoadGateRef);\n        if (Option.isSome(gate) && gate.value.active) {\n          const lastActivityAtMillis = yield* Clock.currentTimeMillis;\n          yield* Ref.set(\n            sessionLoadGateRef,\n            Option.some({\n              ...gate.value,\n              lastActivityAtMillis,\n            }),\n          );\n          return;\n        }\n        if (sessionUpdateIsReplay(notification)) {\n          return;\n        }\n        const startState = yield* Ref.get(startStateRef);\n        // One runtime projects one root ACP session. Child-session updates need\n        // explicit lineage routing and must never be flattened into this stream.\n        if (\n          startState._tag !== \"Started\" ||\n          notification.sessionId !== startState.result.sessionId\n        ) {\n          return;\n        }\n        yield* handleSessionUpdate({\n          queue: eventQueue,\n          modeStateRef,\n          toolCallsRef,\n          assistantSegmentRef,\n          assistantItemRuntimeId,\n          params: notification,\n        });\n      }),\n    );\n    if (options.hostLocalTools === true) {\n      yield* registerLocalToolHandlers({ acp, cwd: options.cwd });\n    }\n    const hostLocalTools = options.hostLocalTools === true;\n    const initializeClientCapabilities = {\n      fs: {\n        readTextFile: hostLocalTools,\n        writeTextFile: hostLocalTools,\n        ...options.clientCapabilities?.fs,\n      },\n      terminal: options.clientCapabilities?.terminal ?? hostLocalTools,\n      ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),\n      ...(options.clientCapabilities?.elicitation\n        ? { elicitation: options.clientCapabilities.elicitation }\n        : {}),\n      ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),\n    } satisfies NonNullable<EffectAcpSchema.InitializeRequest[\"clientCapabilities\"]>;\n\n    const getStartedState = Effect.gen(function* () {\n      const state = yield* Ref.get(startStateRef);\n      if (state._tag === \"Started\") {\n        return state.result;\n      }\n      return yield* new EffectAcpErrors.AcpTransportError({\n        detail: \"ACP session runtime has not been started\",\n        cause: \"ACP session runtime has not been started\",\n      });\n    });\n\n    const validateConfigOptionValue = (\n      configId: string,\n      value: string | boolean,\n    ): Effect.Effect<void, EffectAcpErrors.AcpError> =>\n      Effect.gen(function* () {\n        const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);\n        if (!configOption) {\n          return;\n        }\n        if (configOption.type === \"boolean\") {\n          if (typeof value === \"boolean\") {\n            return;\n          }\n          return yield* new EffectAcpErrors.AcpRequestError({\n            code: -32602,\n            errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option \"${configOption.id}\": expected boolean`,\n            data: {\n              configId: configOption.id,\n              expectedType: \"boolean\",\n              receivedValue: value,\n            },\n          });\n        }\n        if (typeof value !== \"string\") {\n          return yield* new EffectAcpErrors.AcpRequestError({\n            code: -32602,\n            errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option \"${configOption.id}\": expected string`,\n            data: {\n              configId: configOption.id,\n              expectedType: \"string\",\n              receivedValue: value,\n            },\n          });\n        }\n        const allowedValues = collectSessionConfigOptionValues(configOption);\n        if (allowedValues.includes(value)) {\n          return;\n        }\n        return yield* new EffectAcpErrors.AcpRequestError({\n          code: -32602,\n          errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option \"${configOption.id}\": expected one of ${allowedValues.join(\", \")}`,\n          data: {\n            configId: configOption.id,\n            allowedValues,\n            receivedValue: value,\n          },\n        });\n      });\n\n    const updateConfigOptions = (\n      response:\n        | EffectAcpSchema.SetSessionConfigOptionResponse\n        | EffectAcpSchema.LoadSessionResponse\n        | EffectAcpSchema.NewSessionResponse\n        | EffectAcpSchema.ResumeSessionResponse,\n    ): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));\n\n    const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>\n      Ref.update(modeStateRef, (current) =>\n        current ? { ...current, currentModeId: modeId } : current,\n      );\n\n    const setConfigOption = (\n      configId: string,\n      value: string | boolean,\n    ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>\n      validateConfigOptionValue(configId, value).pipe(\n        Effect.flatMap(() => getStartedState),\n        Effect.flatMap((started) =>\n          Ref.get(configOptionsRef).pipe(\n            Effect.flatMap((configOptions) => {\n              const existing = findSessionConfigOption(configOptions, configId);\n              if (existing && configOptionCurrentValueMatches(existing, value)) {\n                return Effect.succeed({\n                  configOptions,\n                } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);\n              }\n              const requestPayload =\n                typeof value === \"boolean\"\n                  ? ({\n                      sessionId: started.sessionId,\n                      configId,\n                      type: \"boolean\",\n                      value,\n                    } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)\n                  : ({\n                      sessionId: started.sessionId,\n                      configId,\n                      value: String(value),\n                    } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);\n              return runLoggedRequest(\n                \"session/set_config_option\",\n                requestPayload,\n                acp.agent.setSessionConfigOption(requestPayload),\n              ).pipe(Effect.tap((response) => updateConfigOptions(response)));\n            }),\n          ),\n        ),\n      );\n\n    const startOnce = Effect.gen(function* () {\n      const initializePayload = {\n        protocolVersion: 1,\n        clientCapabilities: initializeClientCapabilities,\n        clientInfo: options.clientInfo,\n      } satisfies EffectAcpSchema.InitializeRequest;\n\n      const initializeResult = yield* runLoggedRequest(\n        \"initialize\",\n        initializePayload,\n        acp.agent.initialize(initializePayload),\n      );\n\n      if (!options.skipAuthentication) {\n        const authenticatePayload = {\n          methodId: options.authMethodId,\n        } satisfies EffectAcpSchema.AuthenticateRequest;\n\n        yield* runLoggedRequest(\n          \"authenticate\",\n          authenticatePayload,\n          acp.agent.authenticate(authenticatePayload),\n        );\n      }\n\n      let sessionId: string;\n      let sessionSetupResult:\n        | EffectAcpSchema.LoadSessionResponse\n        | EffectAcpSchema.NewSessionResponse\n        | EffectAcpSchema.ResumeSessionResponse;\n      if (options.resumeSessionId) {\n        const loadPayload = {\n          sessionId: options.resumeSessionId,\n          cwd: options.cwd,\n          mcpServers: options.mcpServers ?? [],\n        } satisfies EffectAcpSchema.LoadSessionRequest;\n        const sessionLoadTimeout = Duration.fromInputUnsafe(\n          options.sessionLoadTimeout ?? defaultSessionLoadTimeout,\n        );\n        const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(\n          options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,\n        );\n\n        yield* Ref.set(\n          sessionLoadGateRef,\n          Option.some({\n            active: true,\n            lastActivityAtMillis: undefined,\n            idleGap: sessionLoadReplayIdleGap,\n            initializeResult,\n          }),\n        );\n\n        sessionId = options.resumeSessionId;\n        sessionSetupResult = yield* Effect.gen(function* () {\n          yield* logRequest({\n            method: \"session/load\",\n            payload: loadPayload,\n            status: \"started\",\n          });\n\n          const idleFiber = yield* waitForSessionLoadReplayIdle({\n            gateRef: sessionLoadGateRef,\n          }).pipe(Effect.forkIn(runtimeScope));\n          const loaded = yield* Effect.raceFirst(\n            acp.agent.loadSession(loadPayload),\n            Fiber.join(idleFiber),\n          ).pipe(\n            Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),\n            Effect.timeoutOption(sessionLoadTimeout),\n            Effect.flatMap((result) =>\n              Option.match(result, {\n                onNone: () =>\n                  Effect.fail(\n                    new EffectAcpErrors.AcpTransportError({\n                      operation: \"call-rpc\",\n                      method: \"session/load\",\n                      detail: \"session/load timed out waiting for RPC response or replay idle gap\",\n                      cause: undefined,\n                    }),\n                  ),\n                onSome: Effect.succeed,\n              }),\n            ),\n            Effect.tap((result) =>\n              logRequest({\n                method: \"session/load\",\n                payload: loadPayload,\n                status: \"succeeded\",\n                result,\n              }),\n            ),\n            Effect.onError((cause) =>\n              logRequest({\n                method: \"session/load\",\n                payload: loadPayload,\n                status: \"failed\",\n                cause,\n              }),\n            ),\n          );\n\n          return loaded;\n        }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));\n      } else {\n        const createPayload = {\n          cwd: options.cwd,\n          mcpServers: options.mcpServers ?? [],\n        } satisfies EffectAcpSchema.NewSessionRequest;\n        const created = yield* runLoggedRequest(\n          \"session/new\",\n          createPayload,\n          acp.agent.createSession(createPayload),\n        );\n        sessionId = created.sessionId;\n        sessionSetupResult = created;\n      }\n\n      yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));\n      yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));\n\n      const nextState = {\n        sessionId,\n        initializeResult,\n        sessionSetupResult,\n        modelConfigId: extractModelConfigId(sessionSetupResult),\n      } satisfies AcpStartedState;\n      return nextState;\n    });\n\n    const start = Effect.gen(function* () {\n      const deferred = yield* Deferred.make<\n        AcpSessionRuntimeStartResult,\n        EffectAcpErrors.AcpError\n      >();\n      const effect = yield* Ref.modify(startStateRef, (state) => {\n        switch (state._tag) {\n          case \"Started\":\n            return [Effect.succeed(state.result), state] as const;\n          case \"Starting\":\n            return [Deferred.await(state.deferred), state] as const;\n          case \"NotStarted\":\n            return [\n              startOnce.pipe(\n                Effect.tap((result) =>\n                  Ref.set(startStateRef, { _tag: \"Started\", result }).pipe(\n                    Effect.andThen(Deferred.succeed(deferred, result)),\n                  ),\n                ),\n                Effect.onError((cause) =>\n                  Deferred.failCause(deferred, cause).pipe(\n                    Effect.andThen(Ref.set(startStateRef, { _tag: \"NotStarted\" })),\n                  ),\n                ),\n              ),\n              { _tag: \"Starting\", deferred } satisfies AcpStartState,\n            ] as const;\n        }\n      });\n      return yield* effect;\n    });\n\n    return {\n      handleRequestPermission: acp.handleRequestPermission,\n      handleElicitation: acp.handleElicitation,\n      handleReadTextFile: acp.handleReadTextFile,\n      handleWriteTextFile: acp.handleWriteTextFile,\n      handleCreateTerminal: acp.handleCreateTerminal,\n      handleTerminalOutput: acp.handleTerminalOutput,\n      handleTerminalWaitForExit: acp.handleTerminalWaitForExit,\n      handleTerminalKill: acp.handleTerminalKill,\n      handleTerminalRelease: acp.handleTerminalRelease,\n      handleSessionUpdate: acp.handleSessionUpdate,\n      handleElicitationComplete: acp.handleElicitationComplete,\n      handleUnknownExtRequest: acp.handleUnknownExtRequest,\n      handleUnknownExtNotification: acp.handleUnknownExtNotification,\n      handleExtRequest: acp.handleExtRequest,\n      handleExtNotification: acp.handleExtNotification,\n      start: () => start,\n      getEvents: () => Stream.fromQueue(eventQueue),\n      drainEvents: Effect.gen(function* () {\n        const acknowledge = yield* Deferred.make<void>();\n        yield* Queue.offer(eventQueue, {\n          _tag: \"EventStreamBarrier\",\n          acknowledge,\n        });\n        yield* Deferred.await(acknowledge);\n      }),\n      getModeState: Ref.get(modeStateRef),\n      getConfigOptions: Ref.get(configOptionsRef),\n      prompt: (payload) =>\n        promptSerializationSemaphore.withPermit(\n          Effect.gen(function* () {\n            const started = yield* getStartedState;\n            yield* closeActiveAssistantSegment({\n              queue: eventQueue,\n              assistantSegmentRef,\n            });\n            const requestPayload = {\n              sessionId: started.sessionId,\n              ...payload,\n            } satisfies EffectAcpSchema.PromptRequest;\n            const cancelledResponse = {\n              stopReason: \"cancelled\",\n            } satisfies EffectAcpSchema.PromptResponse;\n            const promptRpcFiber = yield* runLoggedRequest(\n              \"session/prompt\",\n              requestPayload,\n              acp.agent.prompt(requestPayload),\n            ).pipe(Effect.forkIn(runtimeScope));\n            yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));\n            return yield* Fiber.join(promptRpcFiber).pipe(\n              Effect.catchCause((cause) =>\n                Cause.hasInterruptsOnly(cause)\n                  ? Effect.succeed(cancelledResponse)\n                  : Effect.failCause(cause),\n              ),\n              Effect.ensuring(\n                Effect.gen(function* () {\n                  yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);\n                  yield* Ref.set(activePromptFiberRef, Option.none());\n                }),\n              ),\n              Effect.tap(() =>\n                closeActiveAssistantSegment({\n                  queue: eventQueue,\n                  assistantSegmentRef,\n                }),\n              ),\n            );\n          }),\n        ),\n      cancel: getStartedState.pipe(\n        Effect.flatMap((started) =>\n          Effect.gen(function* () {\n            const activePromptFiber = yield* Ref.get(activePromptFiberRef);\n            if (Option.isSome(activePromptFiber)) {\n              yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);\n            }\n            yield* acp.agent\n              .cancel({ sessionId: started.sessionId })\n              .pipe(Effect.ignore, Effect.forkIn(runtimeScope));\n          }),\n        ),\n      ),\n      setMode: (modeId) =>\n        Ref.get(modeStateRef).pipe(\n          Effect.flatMap((modeState) => {\n            if (modeState?.currentModeId === modeId) {\n              return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);\n            }\n            return setConfigOption(\"mode\", modeId).pipe(\n              Effect.tap(() => updateCurrentModeId(modeId)),\n              Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),\n            );\n          }),\n        ),\n      setConfigOption,\n      setModel: (model) =>\n        getStartedState.pipe(\n          Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? \"model\", model)),\n          Effect.asVoid,\n        ),\n      setSessionModel: (modelId) =>\n        getStartedState.pipe(\n          Effect.flatMap((started) => {\n            const requestPayload = {\n              sessionId: started.sessionId,\n              modelId,\n            } satisfies EffectAcpSchema.SetSessionModelRequest;\n            return runLoggedRequest(\n              \"session/set_model\",\n              requestPayload,\n              acp.agent.setSessionModel(requestPayload),\n            );\n          }),\n        ),\n      request: (method, payload) =>\n        runLoggedRequest(method, payload, acp.raw.request(method, payload)),\n      notify: acp.raw.notify,\n    } satisfies AcpSessionRuntime[\"Service\"];\n  });\n\nexport const layer = (\n  options: AcpSessionRuntimeOptions,\n): Layer.Layer<\n  AcpSessionRuntime,\n  EffectAcpErrors.AcpError,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path\n> => Layer.effect(AcpSessionRuntime, make(options));\n\nfunction sessionConfigOptionsFromSetup(\n  response:\n    | {\n        readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;\n      }\n    | undefined,\n): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {\n  return response?.configOptions ?? [];\n}\n\nfunction configOptionCurrentValueMatches(\n  configOption: EffectAcpSchema.SessionConfigOption,\n  value: string | boolean,\n): boolean {\n  const currentValue = configOption.currentValue;\n  if (configOption.type === \"boolean\") {\n    return currentValue === value;\n  }\n  if (typeof currentValue !== \"string\") {\n    return false;\n  }\n  return currentValue.trim() === String(value).trim();\n}\n\nconst handleSessionUpdate = ({\n  queue,\n  modeStateRef,\n  toolCallsRef,\n  assistantSegmentRef,\n  assistantItemRuntimeId,\n  params,\n}: {\n  readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;\n  readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;\n  readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;\n  readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;\n  readonly assistantItemRuntimeId: string;\n  readonly params: EffectAcpSchema.SessionNotification;\n}): Effect.Effect<void> =>\n  Effect.gen(function* () {\n    const parsed = parseSessionUpdateEvent(params);\n    if (parsed.modeId) {\n      yield* Ref.update(modeStateRef, (current) =>\n        current === undefined ? current : updateModeState(current, parsed.modeId!),\n      );\n    }\n    for (const event of parsed.events) {\n      if (event._tag === \"ToolCallUpdated\") {\n        yield* closeActiveAssistantSegment({\n          queue,\n          assistantSegmentRef,\n        });\n        const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {\n          const previous = current.get(event.toolCall.toolCallId);\n          const nextToolCall = mergeToolCallState(previous, event.toolCall);\n          const next = new Map(current);\n          if (nextToolCall.status === \"completed\" || nextToolCall.status === \"failed\") {\n            next.delete(nextToolCall.toolCallId);\n          } else {\n            next.set(nextToolCall.toolCallId, nextToolCall);\n          }\n          return [{ previous, merged: nextToolCall }, next] as const;\n        });\n        if (!shouldEmitToolCallUpdate(previous, merged)) {\n          continue;\n        }\n        yield* Queue.offer(queue, {\n          _tag: \"ToolCallUpdated\",\n          toolCall: merged,\n          rawPayload: event.rawPayload,\n        });\n        continue;\n      }\n      if (event._tag === \"ContentDelta\") {\n        if (event.text.trim().length === 0) {\n          const assistantSegmentState = yield* Ref.get(assistantSegmentRef);\n          if (!assistantSegmentState.activeItemId) {\n            continue;\n          }\n        }\n        const itemId = yield* ensureActiveAssistantSegment({\n          queue,\n          assistantSegmentRef,\n          sessionId: params.sessionId,\n          assistantItemRuntimeId,\n        });\n        yield* Queue.offer(queue, {\n          ...event,\n          itemId,\n        });\n        continue;\n      }\n      yield* Queue.offer(queue, event);\n    }\n  });\n\nfunction updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {\n  const normalized = nextModeId.trim();\n  if (!normalized) {\n    return modeState;\n  }\n  return modeState.availableModes.some((mode) => mode.id === normalized)\n    ? {\n        ...modeState,\n        currentModeId: normalized,\n      }\n    : modeState;\n}\n\nfunction shouldEmitToolCallUpdate(\n  previous: AcpToolCallState | undefined,\n  next: AcpToolCallState,\n): boolean {\n  if (next.status === \"completed\" || next.status === \"failed\") {\n    return true;\n  }\n  if (!next.detail) {\n    return false;\n  }\n  return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;\n}\n\nconst assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>\n  `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;\n\nconst ensureActiveAssistantSegment = ({\n  queue,\n  assistantSegmentRef,\n  sessionId,\n  assistantItemRuntimeId,\n}: {\n  readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;\n  readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;\n  readonly sessionId: string;\n  readonly assistantItemRuntimeId: string;\n}) =>\n  Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(\n    assistantSegmentRef,\n    (current) => {\n      if (current.activeItemId) {\n        return [{ itemId: current.activeItemId }, current] as const;\n      }\n      const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);\n      return [\n        {\n          itemId,\n          startedEvent: {\n            _tag: \"AssistantItemStarted\",\n            itemId,\n          } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: \"AssistantItemStarted\" }>,\n        },\n        {\n          nextSegmentIndex: current.nextSegmentIndex + 1,\n          activeItemId: itemId,\n        } satisfies AcpAssistantSegmentState,\n      ] as const;\n    },\n  ).pipe(\n    Effect.flatMap((result) =>\n      result.startedEvent\n        ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))\n        : Effect.succeed(result.itemId),\n    ),\n  );\n\nconst closeActiveAssistantSegment = ({\n  queue,\n  assistantSegmentRef,\n}: {\n  readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;\n  readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;\n}) =>\n  Ref.modify(assistantSegmentRef, (current) => {\n    if (!current.activeItemId) {\n      return [undefined, current] as const;\n    }\n    return [\n      {\n        _tag: \"AssistantItemCompleted\",\n        itemId: current.activeItemId,\n      } satisfies AcpParsedSessionEvent,\n      {\n        nextSegmentIndex: current.nextSegmentIndex,\n      } satisfies AcpAssistantSegmentState,\n    ] as const;\n  }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));\n","/**\n * AcpAgentSupport — shared plumbing for the fork's first-party ACP drivers\n * (Gemini CLI, Qwen Code, Kimi CLI, JoyCode).\n *\n * Upstream t3code ships one `XxxAcpSupport.ts` per ACP driver (Cursor, Grok,\n * OpenCode); the three CLIs this fork targets differ only in\n * bin/args/auth/model defaults, so their support layer is one generic\n * builder plus a static descriptor per agent (see `GeminiAcpAgent.ts`,\n * `QwenAcpAgent.ts`, `KimiAcpAgent.ts`, `JoyCodeAcpAgent.ts`).\n *\n * Two protocol notes worth keeping:\n *\n *   - Authentication: `AcpSessionRuntime.start()` normally performs\n *     `initialize` -> `authenticate` -> `session/new|load`. The three CLIs\n *     here are already logged in via their own config, so their descriptors\n *     set `skipAuthentication: true` (a fork addition on the runtime\n *     options) and no `authenticate` request is sent.\n *\n *   - Resume: agents that advertise `loadSession` (Qwen Code does; see the\n *     fork's previous CLI adapter notes) get the persisted ACP session id\n *     passed back through `resumeSessionId`, which makes\n *     `AcpSessionRuntime` issue `session/load`. Agents without that\n *     capability (Gemini CLI, and Kimi CLI until proven otherwise) always\n *     start a fresh `session/new`; their resume cursors are ignored.\n *\n * @module provider/acp/AcpAgentSupport\n */\nimport { ProviderDriverKind } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Scope from \"effect/Scope\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport type * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\n\nimport * as AcpSessionRuntime from \"./AcpSessionRuntime.ts\";\n\n/** Schema version stamped onto every ACP-agent resume cursor we persist. */\nexport const ACP_AGENT_RESUME_VERSION = 1 as const;\n\n/**\n * Static description of one ACP-speaking CLI. Everything the generic\n * adapter/provider/text-generation code needs to know about the agent lives\n * here.\n */\nexport interface AcpAgentDescriptor {\n  /** ProviderDriverKind slug, e.g. \"gemini\". */\n  readonly provider: ProviderDriverKind;\n  /** Human-readable CLI name used in logs/messages, e.g. \"Gemini CLI\". */\n  readonly displayName: string;\n  /** Default binary resolved on PATH when settings.binaryPath is blank. */\n  readonly defaultBinary: string;\n  /** argv that starts the CLI in ACP mode (after the binary). */\n  readonly acpArgs: ReadonlyArray<string>;\n  /** Default model slug applied when the caller doesn't pick one. */\n  readonly defaultModel: string;\n  /** Built-in model slugs offered before discovery/custom models. */\n  readonly builtInModels: ReadonlyArray<string>;\n  /** Optional provider-specific guidance shown when the binary cannot be resolved. */\n  readonly missingBinaryMessage?: string;\n  /** Whether the agent advertises `loadSession` (resume-by-id). */\n  readonly supportsSessionLoad: boolean;\n  /**\n   * agentlink fork addition: when true, the session runtime advertises and\n   * locally hosts the ACP `fs`/`terminal` client capabilities. Enable for\n   * agents that delegate shell/file tools to the client (Kimi CLI); leave\n   * off for agents that execute tools in their own process.\n   */\n  readonly hostLocalTools?: boolean;\n}\n\n/** Minimal settings payload the support layer reads (all three schemas match). */\nexport type AcpAgentSettings = {\n  readonly binaryPath: string;\n  readonly customModels: ReadonlyArray<string>;\n};\n\nexport function buildAcpAgentSpawnInput(\n  descriptor: AcpAgentDescriptor,\n  settings: Pick<AcpAgentSettings, \"binaryPath\"> | null | undefined,\n  cwd: string,\n  environment?: NodeJS.ProcessEnv,\n): AcpSessionRuntime.AcpSpawnInput {\n  return {\n    command: settings?.binaryPath.trim() || descriptor.defaultBinary,\n    args: [...descriptor.acpArgs],\n    cwd,\n    ...(environment ? { env: environment } : {}),\n  };\n}\n\nexport interface AcpAgentRuntimeInput extends Omit<\n  AcpSessionRuntime.AcpSessionRuntimeOptions,\n  \"authMethodId\" | \"clientCapabilities\" | \"skipAuthentication\" | \"hostLocalTools\" | \"spawn\"\n> {\n  readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"];\n  readonly settings: Pick<AcpAgentSettings, \"binaryPath\"> | null | undefined;\n  readonly environment?: NodeJS.ProcessEnv;\n}\n\n/**\n * Build an `AcpSessionRuntime` for one of the fork's ACP agents. The agent\n * CLIs authenticate out of band (their own `login` command), so the runtime\n * is created with `skipAuthentication` and a placeholder method id that is\n * never sent.\n */\nexport const makeAcpAgentRuntime = (\n  descriptor: AcpAgentDescriptor,\n  input: AcpAgentRuntimeInput,\n): Effect.Effect<\n  AcpSessionRuntime.AcpSessionRuntime[\"Service\"],\n  EffectAcpErrors.AcpError,\n  Crypto.Crypto | Scope.Scope | FileSystem.FileSystem | Path.Path\n> =>\n  Effect.gen(function* () {\n    const acpContext = yield* Layer.build(\n      AcpSessionRuntime.layer({\n        ...input,\n        spawn: buildAcpAgentSpawnInput(descriptor, input.settings, input.cwd, input.environment),\n        authMethodId: \"none\",\n        skipAuthentication: true,\n        hostLocalTools: descriptor.hostLocalTools === true,\n      }).pipe(\n        Layer.provide(\n          Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),\n        ),\n      ),\n    );\n    return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(\n      Effect.provide(acpContext),\n    );\n  });\n\nexport function resolveAcpAgentModelId(\n  descriptor: AcpAgentDescriptor,\n  model: string | null | undefined,\n): string {\n  const trimmed = model?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : descriptor.defaultModel;\n}\n\nexport function currentAcpAgentModelIdFromSessionSetup(\n  sessionSetupResult:\n    | EffectAcpSchema.LoadSessionResponse\n    | EffectAcpSchema.NewSessionResponse\n    | EffectAcpSchema.ResumeSessionResponse,\n): string | undefined {\n  return sessionSetupResult.models?.currentModelId?.trim() || undefined;\n}\n\n/**\n * Apply a requested model selection to a live ACP runtime. No-op when the\n * requested model is already active or none was requested. Uses the config\n * option path (`setModel`), which the three ACP CLIs negotiate through\n * `session/new` config options; `session/set_model` is an unstable extension\n * they don't all implement.\n */\nexport function applyAcpAgentModelSelection<E>(input: {\n  readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime[\"Service\"], \"setModel\">;\n  readonly currentModelId: string | undefined;\n  readonly requestedModelId: string | undefined;\n  readonly mapError: (cause: EffectAcpErrors.AcpError) => E;\n}): Effect.Effect<string | undefined, E> {\n  const shouldSwitchModel =\n    input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;\n  if (!shouldSwitchModel) {\n    return Effect.succeed(input.currentModelId);\n  }\n  return input.runtime\n    .setModel(input.requestedModelId)\n    .pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Extract a resumable ACP session id from an opaque resume cursor. Returns\n * `undefined` for foreign, malformed, or stale cursors — callers then start\n * a fresh session.\n */\nexport function parseAcpAgentResumeCursor(raw: unknown): { sessionId: string } | undefined {\n  if (!isRecord(raw)) return undefined;\n  if (raw.schemaVersion !== ACP_AGENT_RESUME_VERSION) return undefined;\n  if (typeof raw.sessionId !== \"string\" || !raw.sessionId.trim()) return undefined;\n  return { sessionId: raw.sessionId.trim() };\n}\n\nexport function makeAcpAgentResumeCursor(sessionId: string): {\n  schemaVersion: typeof ACP_AGENT_RESUME_VERSION;\n  sessionId: string;\n} {\n  return { schemaVersion: ACP_AGENT_RESUME_VERSION, sessionId };\n}\n\n/**\n * Decide the effective resume target for a `startSession` call. Qwen Code\n * advertises `loadSession`, so its cursors are honored; the other agents\n * silently drop them and always start fresh (mirrors the fork's previous\n * CLI adapter semantics for `gemini`, which lacks `loadSession`).\n */\nexport function resolveResumeSessionId(\n  descriptor: AcpAgentDescriptor,\n  resumeCursor: unknown,\n): string | undefined {\n  if (!descriptor.supportsSessionLoad) {\n    return undefined;\n  }\n  return parseAcpAgentResumeCursor(resumeCursor)?.sessionId;\n}\n","/**\n * AcpAgentTextGeneration — generic text generation over `AcpSessionRuntime`\n * for the fork's ACP CLIs (Gemini / Qwen / Kimi).\n *\n * Ported from the upstream `GrokTextGeneration`: spin up a short-lived ACP\n * session, stream `agent_message_chunk` text into a buffer, prompt for a\n * structured JSON blob, decode it against the per-operation schema. Used for\n * thread-title generation (the only text-generation consumer left in the\n * fork after the git/source-control trim).\n *\n * @module textGeneration/AcpAgentTextGeneration\n */\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\nimport type * as EffectAcpErrors from \"effect-acp/errors\";\n\nimport { type ModelSelection } from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { extractJsonObject } from \"@t3tools/shared/schemaJson\";\n\nimport { TextGenerationError } from \"@t3tools/contracts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n} from \"./TextGenerationUtils.ts\";\nimport {\n  applyAcpAgentModelSelection,\n  currentAcpAgentModelIdFromSessionSetup,\n  makeAcpAgentRuntime,\n  resolveAcpAgentModelId,\n  type AcpAgentDescriptor,\n  type AcpAgentSettings,\n} from \"../provider/acp/AcpAgentSupport.ts\";\n\nconst ACP_AGENT_TIMEOUT_MS = 180_000;\n\nconst isTextGenerationError = Schema.is(TextGenerationError);\n\nexport const makeAcpAgentTextGeneration = (\n  descriptor: AcpAgentDescriptor,\n  settings: AcpAgentSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n) =>\n  Effect.gen(function* () {\n    const crypto = yield* Crypto.Crypto;\n    const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n\n    const runAcpAgentJson = <S extends Schema.Top>({\n      operation,\n      cwd,\n      prompt,\n      outputSchemaJson,\n      modelSelection,\n    }: {\n      operation:\n        | \"generateCommitMessage\"\n        | \"generatePrContent\"\n        | \"generateBranchName\"\n        | \"generateThreadTitle\";\n      cwd: string;\n      prompt: string;\n      outputSchemaJson: S;\n      modelSelection: ModelSelection;\n    }): Effect.Effect<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> =>\n      Effect.gen(function* () {\n        const resolvedModel = resolveAcpAgentModelId(descriptor, modelSelection.model);\n        const outputRef = yield* Ref.make(\"\");\n        const runtime = yield* makeAcpAgentRuntime(descriptor, {\n          settings,\n          environment,\n          childProcessSpawner: commandSpawner,\n          cwd,\n          clientInfo: { name: \"agentlink-text-generation\", version: \"0.0.0\" },\n        }).pipe(\n          Effect.provideService(Crypto.Crypto, crypto),\n          Effect.provideService(FileSystem.FileSystem, fileSystem),\n          Effect.provideService(Path.Path, path),\n        );\n\n        yield* runtime.handleSessionUpdate((notification) => {\n          const update = notification.update;\n          if (update.sessionUpdate !== \"agent_message_chunk\") {\n            return Effect.void;\n          }\n          const content = update.content;\n          if (content.type !== \"text\") {\n            return Effect.void;\n          }\n          return Ref.update(outputRef, (current) => current + content.text);\n        });\n\n        const promptResult = yield* Effect.gen(function* () {\n          const started = yield* runtime.start();\n          yield* applyAcpAgentModelSelection({\n            runtime,\n            currentModelId: currentAcpAgentModelIdFromSessionSetup(started.sessionSetupResult),\n            requestedModelId: resolvedModel,\n            mapError: (cause) =>\n              new TextGenerationError({\n                operation,\n                detail: `Failed to set ${descriptor.displayName} ACP base model for text generation.`,\n                cause,\n              }),\n          });\n\n          return yield* runtime.prompt({\n            prompt: [{ type: \"text\", text: prompt }],\n          });\n        }).pipe(\n          Effect.timeoutOption(ACP_AGENT_TIMEOUT_MS),\n          Effect.flatMap(\n            Option.match({\n              onNone: () =>\n                Effect.fail(\n                  new TextGenerationError({\n                    operation,\n                    detail: `${descriptor.displayName} ACP request timed out.`,\n                  }),\n                ),\n              onSome: (value) => Effect.succeed(value),\n            }),\n          ),\n          Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>\n            isTextGenerationError(cause)\n              ? cause\n              : new TextGenerationError({\n                  operation,\n                  detail: `${descriptor.displayName} ACP request failed.`,\n                  cause,\n                }),\n          ),\n        );\n\n        const trimmed = (yield* Ref.get(outputRef)).trim();\n        if (!trimmed) {\n          return yield* new TextGenerationError({\n            operation,\n            detail:\n              promptResult.stopReason === \"cancelled\"\n                ? `${descriptor.displayName} ACP request was cancelled.`\n                : `${descriptor.displayName} returned empty output.`,\n          });\n        }\n\n        const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));\n        return yield* decodeOutput(extractJsonObject(trimmed)).pipe(\n          Effect.catchTags({\n            SchemaError: (cause) =>\n              Effect.fail(\n                new TextGenerationError({\n                  operation,\n                  detail: `${descriptor.displayName} returned invalid structured output.`,\n                  cause,\n                }),\n              ),\n          }),\n        );\n      }).pipe(\n        Effect.mapError((cause) =>\n          isTextGenerationError(cause)\n            ? cause\n            : new TextGenerationError({\n                operation,\n                detail: `${descriptor.displayName} ACP text generation failed.`,\n                cause,\n              }),\n        ),\n        Effect.scoped,\n      );\n\n    const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n      Effect.fn(\"AcpAgentTextGeneration.generateCommitMessage\")(function* (input) {\n        const { prompt, outputSchema } = buildCommitMessagePrompt({\n          branch: input.branch,\n          stagedSummary: input.stagedSummary,\n          stagedPatch: input.stagedPatch,\n          includeBranch: input.includeBranch === true,\n          policy: input.policy,\n        });\n\n        const generated = yield* runAcpAgentJson({\n          operation: \"generateCommitMessage\",\n          cwd: input.cwd,\n          prompt,\n          outputSchemaJson: outputSchema,\n          modelSelection: input.modelSelection,\n        });\n\n        return {\n          subject: sanitizeCommitSubject(generated.subject),\n          body: generated.body.trim(),\n          ...(\"branch\" in generated && typeof generated.branch === \"string\"\n            ? { branch: sanitizeFeatureBranchName(generated.branch) }\n            : {}),\n        };\n      });\n\n    const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n      Effect.fn(\"AcpAgentTextGeneration.generatePrContent\")(function* (input) {\n        const { prompt, outputSchema } = buildPrContentPrompt({\n          baseBranch: input.baseBranch,\n          headBranch: input.headBranch,\n          commitSummary: input.commitSummary,\n          diffSummary: input.diffSummary,\n          diffPatch: input.diffPatch,\n          policy: input.policy,\n          changeRequestTemplate: input.changeRequestTemplate,\n        });\n\n        const generated = yield* runAcpAgentJson({\n          operation: \"generatePrContent\",\n          cwd: input.cwd,\n          prompt,\n          outputSchemaJson: outputSchema,\n          modelSelection: input.modelSelection,\n        });\n\n        return {\n          title: sanitizePrTitle(generated.title),\n          body: generated.body.trim(),\n        };\n      });\n\n    const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n      Effect.fn(\"AcpAgentTextGeneration.generateBranchName\")(function* (input) {\n        const { prompt, outputSchema } = buildBranchNamePrompt({\n          message: input.message,\n          attachments: input.attachments,\n        });\n\n        const generated = yield* runAcpAgentJson({\n          operation: \"generateBranchName\",\n          cwd: input.cwd,\n          prompt,\n          outputSchemaJson: outputSchema,\n          modelSelection: input.modelSelection,\n        });\n\n        return {\n          branch: sanitizeBranchFragment(generated.branch),\n        };\n      });\n\n    const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n      Effect.fn(\"AcpAgentTextGeneration.generateThreadTitle\")(function* (input) {\n        const { prompt, outputSchema } = buildThreadTitlePrompt({\n          message: input.message,\n          previousTitle: input.previousTitle,\n          attachments: input.attachments,\n        });\n\n        const generated = yield* runAcpAgentJson({\n          operation: \"generateThreadTitle\",\n          cwd: input.cwd,\n          prompt,\n          outputSchemaJson: outputSchema,\n          modelSelection: input.modelSelection,\n        });\n\n        return {\n          title: sanitizeThreadTitle(generated.title),\n        } satisfies TextGeneration.ThreadTitleGenerationResult;\n      });\n\n    return {\n      generateCommitMessage,\n      generatePrContent,\n      generateBranchName,\n      generateThreadTitle,\n    } satisfies TextGeneration.TextGeneration[\"Service\"];\n  });\n","import {\n  type ProviderApprovalDecision,\n  type ProviderDriverKind,\n  type ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\n\nimport {\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionClosedError,\n  type ProviderAdapterError,\n} from \"../Errors.ts\";\nconst isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);\nconst isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);\n\nexport function mapAcpToAdapterError(\n  provider: ProviderDriverKind,\n  threadId: ThreadId,\n  method: string,\n  error: EffectAcpErrors.AcpError,\n): ProviderAdapterError {\n  if (isAcpProcessExitedError(error)) {\n    return new ProviderAdapterSessionClosedError({\n      provider,\n      threadId,\n      cause: error,\n    });\n  }\n  if (isAcpRequestError(error)) {\n    return new ProviderAdapterRequestError({\n      provider,\n      method,\n      detail: error.message,\n      cause: error,\n    });\n  }\n  return new ProviderAdapterRequestError({\n    provider,\n    method,\n    detail: error.message,\n    cause: error,\n  });\n}\n\nexport function acpPermissionOutcome(decision: ProviderApprovalDecision): string {\n  switch (decision) {\n    case \"acceptForSession\":\n      return \"allow-always\";\n    case \"accept\":\n      return \"allow-once\";\n    case \"decline\":\n    default:\n      return \"reject-once\";\n  }\n}\n","import {\n  type RuntimeEventRawSource,\n  RuntimeItemId,\n  type CanonicalRequestType,\n  type EventId,\n  type ProviderApprovalDecision,\n  type ProviderDriverKind,\n  type ProviderRuntimeEvent,\n  type RuntimeRequestId,\n  type ThreadId,\n  type ToolLifecycleItemType,\n  type TurnId,\n} from \"@t3tools/contracts\";\n\nimport type { AcpPermissionRequest, AcpPlanUpdate, AcpToolCallState } from \"./AcpRuntimeModel.ts\";\n\ntype AcpAdapterRawSource = Extract<\n  RuntimeEventRawSource,\n  \"acp.jsonrpc\" | `acp.${string}.extension`\n>;\n\ninterface AcpEventStamp {\n  readonly eventId: EventId;\n  readonly createdAt: string;\n}\n\ntype AcpCanonicalRequestType = Extract<\n  CanonicalRequestType,\n  \"exec_command_approval\" | \"file_read_approval\" | \"file_change_approval\" | \"unknown\"\n>;\n\nfunction canonicalRequestTypeFromAcpKind(kind: string | \"unknown\"): AcpCanonicalRequestType {\n  switch (kind) {\n    case \"execute\":\n      return \"exec_command_approval\";\n    case \"read\":\n      return \"file_read_approval\";\n    case \"edit\":\n    case \"delete\":\n    case \"move\":\n      return \"file_change_approval\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {\n  switch (kind) {\n    case \"execute\":\n      return \"command_execution\";\n    case \"edit\":\n    case \"delete\":\n    case \"move\":\n      return \"file_change\";\n    case \"search\":\n    case \"fetch\":\n      return \"web_search\";\n    default:\n      return \"dynamic_tool_call\";\n  }\n}\n\nfunction runtimeItemStatusFromAcpToolStatus(\n  status: AcpToolCallState[\"status\"],\n): \"inProgress\" | \"completed\" | \"failed\" | undefined {\n  switch (status) {\n    case \"pending\":\n    case \"inProgress\":\n      return \"inProgress\";\n    case \"completed\":\n      return \"completed\";\n    case \"failed\":\n      return \"failed\";\n    default:\n      return undefined;\n  }\n}\n\nexport function makeAcpRequestOpenedEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly requestId: RuntimeRequestId;\n  readonly permissionRequest: AcpPermissionRequest;\n  readonly detail: string;\n  readonly args: unknown;\n  readonly source: AcpAdapterRawSource;\n  readonly method: string;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"request.opened\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    requestId: input.requestId,\n    payload: {\n      requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),\n      detail: input.detail,\n      args: input.args,\n    },\n    raw: {\n      source: input.source,\n      method: input.method,\n      payload: input.rawPayload,\n    },\n  };\n}\n\nexport function makeAcpRequestResolvedEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly requestId: RuntimeRequestId;\n  readonly permissionRequest: AcpPermissionRequest;\n  readonly decision: ProviderApprovalDecision;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"request.resolved\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    requestId: input.requestId,\n    payload: {\n      requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),\n      decision: input.decision,\n    },\n  };\n}\n\nexport function makeAcpPlanUpdatedEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly payload: AcpPlanUpdate;\n  readonly source: AcpAdapterRawSource;\n  readonly method: string;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"turn.plan.updated\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    payload: input.payload,\n    raw: {\n      source: input.source,\n      method: input.method,\n      payload: input.rawPayload,\n    },\n  };\n}\n\nexport function makeAcpToolCallEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly toolCall: AcpToolCallState;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  const runtimeStatus = runtimeItemStatusFromAcpToolStatus(input.toolCall.status);\n  return {\n    type:\n      input.toolCall.status === \"completed\" || input.toolCall.status === \"failed\"\n        ? \"item.completed\"\n        : \"item.updated\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    itemId: RuntimeItemId.make(input.toolCall.toolCallId),\n    payload: {\n      itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),\n      ...(runtimeStatus ? { status: runtimeStatus } : {}),\n      ...(input.toolCall.title ? { title: input.toolCall.title } : {}),\n      ...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),\n      ...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),\n    },\n    raw: {\n      source: \"acp.jsonrpc\",\n      method: \"session/update\",\n      payload: input.rawPayload,\n    },\n  };\n}\n\nexport function makeAcpAssistantItemEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: string;\n  readonly lifecycle: \"item.started\" | \"item.completed\";\n}): ProviderRuntimeEvent {\n  return {\n    type: input.lifecycle,\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    itemId: RuntimeItemId.make(input.itemId),\n    payload: {\n      itemType: \"assistant_message\",\n      status: input.lifecycle === \"item.completed\" ? \"completed\" : \"inProgress\",\n    },\n  };\n}\n\nexport function makeAcpContentDeltaEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly itemId?: string;\n  readonly text: string;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"content.delta\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),\n    payload: {\n      streamKind: \"assistant_text\",\n      delta: input.text,\n    },\n    raw: {\n      source: \"acp.jsonrpc\",\n      method: \"session/update\",\n      payload: input.rawPayload,\n    },\n  };\n}\n","import type { ProviderDriverKind, ThreadId } from \"@t3tools/contracts\";\nimport { causeErrorTag, errorTag } from \"@t3tools/shared/observability\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport type * as SchemaIssue from \"effect/SchemaIssue\";\nimport type * as EffectAcpProtocol from \"effect-acp/protocol\";\n\nimport type { EventNdjsonLogger } from \"../Layers/EventNdjsonLogger.ts\";\nimport type * as AcpSessionRuntime from \"./AcpSessionRuntime.ts\";\n\nconst canonicalStopReasons = new Set([\n  \"end_turn\",\n  \"max_tokens\",\n  \"max_turn_requests\",\n  \"refusal\",\n  \"cancelled\",\n]);\n\nfunction structuralMethod(value: string): string {\n  return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : \"unknown\";\n}\n\nfunction summarizePayload(payload: unknown): Readonly<Record<string, unknown>> {\n  if (payload === null) return { valueType: \"null\" };\n  if (typeof payload === \"string\") {\n    return { valueType: \"string\", byteLength: new TextEncoder().encode(payload).byteLength };\n  }\n  if (payload instanceof Uint8Array) {\n    return { valueType: \"bytes\", byteLength: payload.byteLength };\n  }\n  if (Array.isArray(payload)) {\n    return { valueType: \"array\", itemCount: payload.length };\n  }\n  if (typeof payload !== \"object\") {\n    return { valueType: typeof payload };\n  }\n\n  try {\n    const record = payload as Record<string, unknown>;\n    return {\n      valueType: \"object\",\n      fieldCount: Object.keys(record).length,\n      ...(typeof record._tag === \"string\" ? { messageTag: errorTag(record) } : {}),\n      ...(typeof record.tag === \"string\" ? { method: structuralMethod(record.tag) } : {}),\n    };\n  } catch {\n    return { valueType: \"object\" };\n  }\n}\n\nfunction boundedNumber(value: unknown, maximum: number): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value)\n    ? Math.min(Math.max(0, value), maximum)\n    : undefined;\n}\n\nfunction structuralNames(value: unknown): ReadonlyArray<string> | undefined {\n  return Array.isArray(value)\n    ? value.slice(0, 16).map((item) =>\n        typeof item === \"string\" ? structuralMethod(item) : \"unknown\",\n      )\n    : undefined;\n}\n\nfunction schemaIssueDiagnostics(root: SchemaIssue.Issue): Readonly<Record<string, unknown>> {\n  let issueCount = 0;\n  let maximumPathDepth = 0;\n  const issueKinds = new Set<string>();\n\n  const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {\n    if (issueCount >= 10_000) return;\n    issueCount += 1;\n    issueKinds.add(structuralMethod(issue._tag));\n    maximumPathDepth = Math.max(maximumPathDepth, pathDepth);\n    switch (issue._tag) {\n      case \"Filter\":\n      case \"Encoding\":\n        visit(issue.issue, pathDepth);\n        break;\n      case \"Pointer\":\n        visit(issue.issue, Math.min(pathDepth + issue.path.length, 1_000));\n        break;\n      case \"Composite\":\n      case \"AnyOf\":\n        for (const child of issue.issues.slice(0, 1_000)) visit(child, pathDepth);\n        break;\n    }\n  };\n\n  visit(root, 0);\n  return {\n    issueCount,\n    issueKinds: [...issueKinds].slice(0, 16),\n    maximumPathDepth,\n  };\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : undefined;\n}\n\nfunction summarizeRequestCause(\n  cause: Cause.Cause<unknown>,\n): Readonly<Record<string, unknown>> | undefined {\n  for (const reason of cause.reasons) {\n    if (reason._tag !== \"Fail\") continue;\n    const failure = asRecord(reason.error);\n    if (failure?._tag === \"AcpProtocolParseError\" && failure.operation === \"decode-rpc-result\") {\n      const issueCount = boundedNumber(failure.issueCount, 10_000);\n      const issueKinds = structuralNames(failure.issueKinds);\n      const maximumPathDepth = boundedNumber(failure.maximumPathDepth, 1_000);\n      return {\n        failureKind: \"rpc-result-decode\",\n        causeTags: [\"AcpProtocolParseError\", \"SchemaError\"],\n        ...(issueCount === undefined ? {} : { issueCount }),\n        ...(issueKinds ? { issueKinds } : {}),\n        ...(maximumPathDepth === undefined ? {} : { maximumPathDepth }),\n      };\n    }\n\n    const transport = failure;\n    if (transport?._tag !== \"AcpTransportError\" || transport.operation !== \"call-rpc\") continue;\n    const rpcClient = asRecord(transport.cause);\n    if (rpcClient?._tag !== \"RpcClientError\") continue;\n    const rpcDefect = asRecord(rpcClient.reason);\n    if (rpcDefect?._tag !== \"RpcClientDefect\" || !Schema.isSchemaError(rpcDefect.cause)) continue;\n\n    return {\n      failureKind: \"rpc-result-decode\",\n      causeTags: [\n        \"AcpTransportError\",\n        \"RpcClientError\",\n        \"RpcClientDefect\",\n        \"SchemaError\",\n      ],\n      ...schemaIssueDiagnostics(rpcDefect.cause.issue),\n    };\n  }\n  return undefined;\n}\n\nfunction summarizeProtocolDiagnostics(payload: unknown): Readonly<Record<string, unknown>> {\n  if (payload === null || typeof payload !== \"object\" || Array.isArray(payload)) {\n    return summarizePayload(payload);\n  }\n\n  const record = payload as Record<string, unknown>;\n  const requestIdType =\n    typeof record.requestIdType === \"string\"\n      ? structuralMethod(record.requestIdType)\n      : Object.hasOwn(record, \"requestId\")\n        ? record.requestId === null\n          ? \"null\"\n          : Array.isArray(record.requestId)\n            ? \"array\"\n            : typeof record.requestId\n        : undefined;\n  const issueCount = boundedNumber(record.issueCount, 10_000);\n  const maximumPathDepth = boundedNumber(record.maximumPathDepth, 1_000);\n  const frameCount = boundedNumber(record.frameCount, 16);\n  const pid = boundedNumber(record.pid, Number.MAX_SAFE_INTEGER);\n  const exitCode = boundedNumber(record.exitCode, 255);\n  const byteLength = boundedNumber(record.byteLength, Number.MAX_SAFE_INTEGER);\n  const lineBreakCount = boundedNumber(record.lineBreakCount, 10_000);\n  const argumentCount = boundedNumber(record.argumentCount, 1_000);\n  const argumentKinds = structuralNames(record.argumentKinds);\n  const issueKinds = structuralNames(record.issueKinds);\n  const topLevelFields = structuralNames(record.topLevelFields);\n  const resultFields = structuralNames(record.resultFields);\n\n  return {\n    valueType: \"object\",\n    ...(typeof record.errorTag === \"string\"\n      ? { errorTag: structuralMethod(record.errorTag) }\n      : {}),\n    ...(typeof record.command === \"string\" ? { command: structuralMethod(record.command) } : {}),\n    ...(argumentCount === undefined ? {} : { argumentCount }),\n    ...(argumentKinds ? { argumentKinds } : {}),\n    ...(typeof record.operation === \"string\"\n      ? { operation: structuralMethod(record.operation) }\n      : {}),\n    ...(typeof record.method === \"string\" ? { method: structuralMethod(record.method) } : {}),\n    ...(requestIdType ? { requestIdType, requestId: \"redacted\" } : {}),\n    ...(issueCount === undefined ? {} : { issueCount }),\n    ...(issueKinds ? { issueKinds } : {}),\n    ...(maximumPathDepth === undefined ? {} : { maximumPathDepth }),\n    ...(typeof record.jsonSyntaxValid === \"boolean\"\n      ? { jsonSyntaxValid: record.jsonSyntaxValid }\n      : {}),\n    ...(frameCount === undefined ? {} : { frameCount }),\n    ...(typeof record.topLevelType === \"string\"\n      ? { topLevelType: structuralMethod(record.topLevelType) }\n      : {}),\n    ...(topLevelFields ? { topLevelFields } : {}),\n    ...(typeof record.jsonrpcType === \"string\"\n      ? { jsonrpcType: structuralMethod(record.jsonrpcType) }\n      : {}),\n    ...(typeof record.idType === \"string\" ? { idType: structuralMethod(record.idType) } : {}),\n    ...(resultFields ? { resultFields } : {}),\n    ...(typeof record.stopReasonType === \"string\"\n      ? { stopReasonType: structuralMethod(record.stopReasonType) }\n      : {}),\n    ...(typeof record.canonicalStopReason === \"string\" &&\n    canonicalStopReasons.has(record.canonicalStopReason)\n      ? { canonicalStopReason: record.canonicalStopReason }\n      : {}),\n    ...(pid === undefined ? {} : { pid }),\n    ...(exitCode === undefined ? {} : { exitCode }),\n    ...(byteLength === undefined ? {} : { byteLength }),\n    ...(lineBreakCount === undefined ? {} : { lineBreakCount }),\n  };\n}\n\nfunction formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) {\n  const causeDiagnostics = event.cause ? summarizeRequestCause(event.cause) : undefined;\n  return {\n    method: structuralMethod(event.method),\n    status: event.status,\n    request: summarizePayload(event.payload),\n    ...(event.result !== undefined ? { result: summarizePayload(event.result) } : {}),\n    ...(event.cause !== undefined\n      ? {\n          errorTag: causeErrorTag(event.cause),\n          reasonCount: event.cause.reasons.length,\n          ...(causeDiagnostics ?? {}),\n        }\n      : {}),\n  };\n}\n\nfunction formatProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) {\n  return {\n    direction: event.direction,\n    stage: event.stage,\n    payload:\n      event.stage === \"decode_failed\" ||\n      event.stage === \"terminated\" ||\n      event.stage === \"process_spawned\" ||\n      event.stage === \"process_stderr\" ||\n      event.stage === \"process_exited\"\n        ? summarizeProtocolDiagnostics(event.payload)\n        : summarizePayload(event.payload),\n  };\n}\n\nexport const makeAcpNativeLoggerFactory = Effect.fn(\"makeAcpNativeLoggerFactory\")(function* () {\n  const crypto = yield* Crypto.Crypto;\n  return (input: {\n    readonly nativeEventLogger: EventNdjsonLogger | undefined;\n    readonly provider: ProviderDriverKind;\n    readonly threadId: ThreadId;\n  }): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, \"requestLogger\" | \"protocolLogging\"> => {\n    const writeNativeAcpLog = (logInput: {\n      readonly kind: \"request\" | \"protocol\";\n      readonly payload: unknown;\n    }) =>\n      Effect.gen(function* () {\n        if (!input.nativeEventLogger) return;\n        const observedAt = DateTime.formatIso(yield* DateTime.now);\n        yield* input.nativeEventLogger.write(\n          {\n            observedAt,\n            event: {\n              id: yield* crypto.randomUUIDv4,\n              kind: logInput.kind,\n              provider: input.provider,\n              createdAt: observedAt,\n              threadId: input.threadId,\n              payload: logInput.payload,\n            },\n          },\n          input.threadId,\n        );\n      }).pipe(\n        Effect.catchCause((cause) =>\n          Cause.hasInterrupts(cause)\n            ? Effect.interrupt\n            : Effect.logWarning(\"Failed to write native ACP event log.\", {\n                errorTag: causeErrorTag(cause),\n                reasonCount: cause.reasons.length,\n                provider: input.provider,\n                threadId: input.threadId,\n              }),\n        ),\n      );\n\n    return {\n      requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>\n        writeNativeAcpLog({\n          kind: \"request\",\n          payload: formatRequestLogPayload(event),\n        }),\n      ...(input.nativeEventLogger\n        ? {\n            protocolLogging: {\n              logIncoming: true,\n              logOutgoing: true,\n              logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>\n                writeNativeAcpLog({\n                  kind: \"protocol\",\n                  payload: formatProtocolLogPayload(event),\n                }),\n            } satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions[\"protocolLogging\"]>,\n          }\n        : {}),\n    };\n  };\n});\n","/**\n * AcpAgentAdapter — generic `ProviderAdapter` over `AcpSessionRuntime` for\n * the fork's ACP CLIs (Gemini / Qwen / Kimi / JoyCode).\n *\n * Ported from the upstream `GrokAdapter`, minus the Grok-specific pieces the\n * fork doesn't need: the MCP provider-session bridge (the `mcp/` subsystem\n * was trimmed) and the `x.ai/ask_user_question` extension (xAI-only). What\n * remains is the ACP-core loop: session start (fresh or `session/load`),\n * permission routing into the approval pipeline, plan/tool-call/content\n * event projection, steer-aware prompt settlement, interrupt, and resume\n * cursors.\n *\n * One instance of this adapter is created per provider instance by the\n * driver (`Drivers/<X>Driver.ts`); behavior differences between the\n * CLIs live entirely in their `AcpAgentDescriptor`.\n *\n * @module provider/Layers/AcpAgentAdapter\n */\nimport {\n  ApprovalRequestId,\n  EventId,\n  type ProviderApprovalDecision,\n  type ProviderRuntimeEvent,\n  type ProviderSession,\n  type ProviderUserInputAnswers,\n  ProviderInstanceId,\n  RuntimeRequestId,\n  type ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\n\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport {\n  ProviderAdapterProcessError,\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n} from \"../Errors.ts\";\nimport { mapAcpToAdapterError } from \"../acp/AcpAdapterSupport.ts\";\nimport type * as AcpSessionRuntime from \"../acp/AcpSessionRuntime.ts\";\nimport {\n  makeAcpAssistantItemEvent,\n  makeAcpContentDeltaEvent,\n  makeAcpPlanUpdatedEvent,\n  makeAcpRequestOpenedEvent,\n  makeAcpRequestResolvedEvent,\n  makeAcpToolCallEvent,\n} from \"../acp/AcpCoreRuntimeEvents.ts\";\nimport { parsePermissionRequest } from \"../acp/AcpRuntimeModel.ts\";\nimport { makeAcpNativeLoggerFactory } from \"../acp/AcpNativeLogging.ts\";\nimport {\n  applyAcpAgentModelSelection,\n  currentAcpAgentModelIdFromSessionSetup,\n  makeAcpAgentResumeCursor,\n  makeAcpAgentRuntime,\n  resolveAcpAgentModelId,\n  resolveResumeSessionId,\n  type AcpAgentDescriptor,\n  type AcpAgentSettings,\n} from \"../acp/AcpAgentSupport.ts\";\nimport type { ProviderAdapterError } from \"../Errors.ts\";\nimport type { ProviderAdapterShape } from \"../Services/ProviderAdapter.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\n\nconst encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\n\nfunction encodeJsonStringForDiagnostics(input: unknown): string | undefined {\n  const result = encodeUnknownJsonStringExit(input);\n  return Exit.isSuccess(result) ? result.value : undefined;\n}\n\nexport interface AcpAgentAdapterOptions {\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n  readonly instanceId?: ProviderInstanceId;\n}\n\ninterface PendingApproval {\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n}\n\ninterface AcpAgentSessionContext {\n  readonly threadId: ThreadId;\n  readonly acpSessionId: string;\n  session: ProviderSession;\n  readonly scope: Scope.Closeable;\n  readonly acp: AcpSessionRuntime.AcpSessionRuntime[\"Service\"];\n  notificationFiber: Fiber.Fiber<void, never> | undefined;\n  readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;\n  turns: Array<{ id: TurnId; items: Array<unknown> }>;\n  lastPlanFingerprint: string | undefined;\n  activeTurnId: TurnId | undefined;\n  /** Turns already interrupted; late prompt RPCs must not resurrect them. */\n  interruptedTurnIds: Set<TurnId>;\n  /** Number of sendTurn prompts currently in flight or being prepared.\n   * >0 means a turn is actively running, so a new sendTurn is a steer that\n   * continues it, and only the last remaining prompt settles the turn. */\n  promptsInFlight: number;\n  currentModelId: string | undefined;\n  stopped: boolean;\n}\n\nfunction settlePendingApprovalsAsCancelled(\n  pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,\n): Effect.Effect<void> {\n  return Effect.forEach(\n    Array.from(pendingApprovals.values()),\n    (pending) => Deferred.succeed(pending.decision, \"cancel\").pipe(Effect.ignore),\n    { discard: true },\n  );\n}\n\nfunction appendPromptResultToTurn(\n  ctx: AcpAgentSessionContext,\n  turnId: TurnId,\n  promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,\n  result: EffectAcpSchema.PromptResponse,\n): void {\n  const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);\n  ctx.turns = existingTurnRecord\n    ? ctx.turns.map((turn) =>\n        turn.id === turnId\n          ? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }\n          : turn,\n      )\n    : [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];\n}\n\nconst resolveNotificationTurnId = (ctx: AcpAgentSessionContext): TurnId | undefined =>\n  ctx.activeTurnId;\n\nconst resolveCallbackTurnId = (ctx: AcpAgentSessionContext): TurnId | undefined => ctx.activeTurnId;\n\nconst resolveSessionCallbackTurnId = (\n  sessions: ReadonlyMap<ThreadId, AcpAgentSessionContext>,\n  threadId: ThreadId,\n): TurnId | undefined => {\n  const ctx = sessions.get(threadId);\n  return ctx ? resolveCallbackTurnId(ctx) : undefined;\n};\n\nfunction selectPermissionOptionId(\n  request: EffectAcpSchema.RequestPermissionRequest,\n  decision: Exclude<ProviderApprovalDecision, \"cancel\">,\n): string | undefined {\n  const kind =\n    decision === \"acceptForSession\"\n      ? \"allow_always\"\n      : decision === \"accept\"\n        ? \"allow_once\"\n        : \"reject_once\";\n  const option = request.options.find((entry) => entry.kind === kind);\n  return option?.optionId.trim() || undefined;\n}\n\nfunction selectAutoApprovedPermissionOption(\n  request: EffectAcpSchema.RequestPermissionRequest,\n): string | undefined {\n  return (\n    selectPermissionOptionId(request, \"acceptForSession\") ??\n    selectPermissionOptionId(request, \"accept\")\n  );\n}\n\nexport function acpAgentPromptSettlementBelongsToContext(input: {\n  readonly liveAcpSessionId: string;\n  readonly expectedAcpSessionId: string;\n  readonly liveActiveTurnId: TurnId | undefined;\n  readonly liveSessionActiveTurnId: TurnId | undefined;\n  readonly turnId: TurnId;\n}): boolean {\n  return (\n    input.liveAcpSessionId === input.expectedAcpSessionId &&\n    (input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)\n  );\n}\n\nexport function makeAcpAgentAdapter(\n  descriptor: AcpAgentDescriptor,\n  settings: AcpAgentSettings,\n  options?: AcpAgentAdapterOptions,\n) {\n  return Effect.gen(function* () {\n    const PROVIDER = descriptor.provider;\n    const boundInstanceId =\n      options?.instanceId ?? ProviderInstanceId.make(descriptor.provider as string);\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const serverConfig = yield* Effect.service(ServerConfig);\n    const crypto = yield* Crypto.Crypto;\n    const nativeEventLogger =\n      options?.nativeEventLogger ??\n      (options?.nativeEventLogPath !== undefined\n        ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: \"native\" })\n        : undefined);\n    const managedNativeEventLogger =\n      options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n    const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();\n\n    const sessions = new Map<ThreadId, AcpAgentSessionContext>();\n    const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());\n    const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();\n\n    const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n    const randomUUIDv4 = crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"crypto/randomUUIDv4\",\n            detail: `Failed to generate ${descriptor.displayName} runtime identifier.`,\n            cause,\n          }),\n      ),\n    );\n    const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));\n    const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });\n    const mapAcpCallbackFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n      effect.pipe(\n        Effect.mapError(\n          (cause) =>\n            new EffectAcpErrors.AcpTransportError({\n              detail: `Failed to process ${descriptor.displayName} ACP callback.`,\n              cause,\n            }),\n        ),\n      );\n\n    const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>\n      PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);\n\n    const getThreadSemaphore = (threadId: string) =>\n      SynchronizedRef.modifyEffect(threadLocksRef, (current) => {\n        const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(\n          current.get(threadId),\n        );\n        return Option.match(existing, {\n          onNone: () =>\n            Semaphore.make(1).pipe(\n              Effect.map((semaphore) => {\n                const next = new Map(current);\n                next.set(threadId, semaphore);\n                return [semaphore, next] as const;\n              }),\n            ),\n          onSome: (semaphore) => Effect.succeed([semaphore, current] as const),\n        });\n      });\n\n    const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>\n      Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));\n\n    const settlePromptInFlight = (\n      threadId: ThreadId,\n      turnId: TurnId,\n      expectedAcpSessionId: string,\n      options?: {\n        readonly errorMessage?: string;\n        readonly completedStopReason?: EffectAcpSchema.StopReason | null;\n        readonly emitTurnCompletion?: boolean;\n        /** Interrupt/cancel: drop every outstanding prompt slot and settle once. */\n        readonly settleAllPrompts?: boolean;\n      },\n    ) =>\n      Effect.gen(function* () {\n        const liveCtx = sessions.get(threadId);\n        if (!liveCtx) {\n          return;\n        }\n        const settlementBelongsToLiveContext = acpAgentPromptSettlementBelongsToContext({\n          liveAcpSessionId: liveCtx.acpSessionId,\n          expectedAcpSessionId,\n          liveActiveTurnId: liveCtx.activeTurnId,\n          liveSessionActiveTurnId: liveCtx.session.activeTurnId,\n          turnId,\n        });\n        if (!settlementBelongsToLiveContext) {\n          // interruptTurn already consumed every prompt slot for this turn. A\n          // late prompt result must neither emit a second terminal event nor\n          // consume a slot belonging to a newer turn on the same ACP session.\n          if (\n            liveCtx.acpSessionId !== expectedAcpSessionId ||\n            liveCtx.interruptedTurnIds.has(turnId)\n          ) {\n            return;\n          }\n          if (options?.emitTurnCompletion !== false) {\n            if (options?.errorMessage !== undefined) {\n              yield* offerRuntimeEvent({\n                type: \"turn.completed\",\n                ...(yield* makeEventStamp()),\n                provider: PROVIDER,\n                threadId,\n                turnId,\n                payload: {\n                  state: \"failed\",\n                  errorMessage: options.errorMessage,\n                },\n              });\n            } else if (options?.completedStopReason !== undefined) {\n              yield* offerRuntimeEvent({\n                type: \"turn.completed\",\n                ...(yield* makeEventStamp()),\n                provider: PROVIDER,\n                threadId,\n                turnId,\n                payload: {\n                  state: options.completedStopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n                  stopReason: options.completedStopReason ?? null,\n                },\n              });\n            }\n          }\n          return;\n        }\n        let settleTurnId = turnId;\n        if (options?.settleAllPrompts) {\n          liveCtx.promptsInFlight = 0;\n          if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {\n            const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;\n            if (!fallbackTurnId) {\n              if (liveCtx.session.status === \"running\" || liveCtx.session.status === \"connecting\") {\n                const updatedAt = yield* nowIso;\n                const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;\n                liveCtx.activeTurnId = undefined;\n                liveCtx.session = {\n                  ...readySession,\n                  status: \"ready\",\n                  updatedAt,\n                };\n              }\n              return;\n            }\n            settleTurnId = fallbackTurnId;\n          }\n        } else {\n          const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);\n          if (\n            remainingPrompts > 0 ||\n            liveCtx.activeTurnId !== settleTurnId ||\n            liveCtx.session.activeTurnId !== settleTurnId\n          ) {\n            liveCtx.promptsInFlight = remainingPrompts;\n            return;\n          }\n          liveCtx.promptsInFlight = remainingPrompts;\n        }\n        const updatedAt = yield* nowIso;\n        const canEmitTurnCompletion =\n          liveCtx.session.status === \"running\" || liveCtx.session.status === \"connecting\";\n        const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;\n        const shouldEmitCompletedTurn =\n          options?.completedStopReason !== undefined && canEmitTurnCompletion;\n        const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;\n        liveCtx.activeTurnId = undefined;\n        liveCtx.session = {\n          ...readySession,\n          status: \"ready\",\n          updatedAt,\n        };\n        if (options?.emitTurnCompletion === false) {\n          return;\n        }\n        if (shouldEmitFailedTurn) {\n          yield* offerRuntimeEvent({\n            type: \"turn.completed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId,\n            turnId: settleTurnId,\n            payload: {\n              state: \"failed\",\n              errorMessage: options.errorMessage,\n            },\n          });\n        } else if (shouldEmitCompletedTurn) {\n          yield* offerRuntimeEvent({\n            type: \"turn.completed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId,\n            turnId: settleTurnId,\n            payload: {\n              state: options.completedStopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n              stopReason: options.completedStopReason ?? null,\n            },\n          });\n        }\n      });\n\n    const logNative = (threadId: ThreadId, method: string, payload: unknown) =>\n      Effect.gen(function* () {\n        if (!nativeEventLogger) return;\n        const observedAt = yield* nowIso;\n        yield* nativeEventLogger.write(\n          {\n            observedAt,\n            event: {\n              id: yield* randomUUIDv4,\n              kind: \"notification\",\n              provider: PROVIDER,\n              createdAt: observedAt,\n              method,\n              threadId,\n              payload,\n            },\n          },\n          threadId,\n        );\n      }).pipe(\n        Effect.catchCause((cause) =>\n          Effect.logWarning(`Failed to write native ${descriptor.displayName} notification log.`, {\n            cause,\n            threadId,\n            method,\n          }),\n        ),\n      );\n\n    const emitPlanUpdate = (\n      ctx: AcpAgentSessionContext,\n      turnId: TurnId | undefined,\n      stamp: { readonly eventId: EventId; readonly createdAt: string },\n      payload: {\n        readonly explanation?: string | null;\n        readonly plan: ReadonlyArray<{\n          readonly step: string;\n          readonly status: \"pending\" | \"inProgress\" | \"completed\";\n        }>;\n      },\n      rawPayload: unknown,\n      method: string,\n    ) =>\n      Effect.gen(function* () {\n        const fingerprint = `${turnId ?? \"no-turn\"}:${encodeJsonStringForDiagnostics(payload) ?? \"[unserializable payload]\"}`;\n        if (ctx.lastPlanFingerprint === fingerprint) {\n          return;\n        }\n        ctx.lastPlanFingerprint = fingerprint;\n        yield* offerRuntimeEvent(\n          makeAcpPlanUpdatedEvent({\n            stamp,\n            provider: PROVIDER,\n            threadId: ctx.threadId,\n            turnId,\n            payload,\n            source: \"acp.jsonrpc\",\n            method,\n            rawPayload,\n          }),\n        );\n      });\n\n    const requireSession = (\n      threadId: ThreadId,\n    ): Effect.Effect<AcpAgentSessionContext, ProviderAdapterSessionNotFoundError> => {\n      const ctx = sessions.get(threadId);\n      if (!ctx || ctx.stopped) {\n        return Effect.fail(\n          new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),\n        );\n      }\n      return Effect.succeed(ctx);\n    };\n\n    const stopSessionInternal = (ctx: AcpAgentSessionContext) =>\n      Effect.gen(function* () {\n        if (ctx.stopped) return;\n        ctx.stopped = true;\n        yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);\n        if (ctx.notificationFiber) {\n          yield* Fiber.interrupt(ctx.notificationFiber);\n        }\n        yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));\n        sessions.delete(ctx.threadId);\n        yield* offerRuntimeEvent({\n          type: \"session.exited\",\n          ...(yield* makeEventStamp()),\n          provider: PROVIDER,\n          threadId: ctx.threadId,\n          payload: { exitKind: \"graceful\" },\n        });\n      });\n\n    const startSession: ProviderAdapterShape<ProviderAdapterError>[\"startSession\"] = (input) =>\n      withThreadLock(\n        input.threadId,\n        Effect.gen(function* () {\n          if (input.provider !== undefined && input.provider !== PROVIDER) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"startSession\",\n              issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n            });\n          }\n          if (!input.cwd?.trim()) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"startSession\",\n              issue: \"cwd is required and must be non-empty.\",\n            });\n          }\n\n          const cwd = path.resolve(input.cwd.trim());\n          const modelSelection =\n            input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n          const existing = sessions.get(input.threadId);\n          if (existing && !existing.stopped) {\n            yield* stopSessionInternal(existing);\n          }\n\n          const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();\n          const sessionScope = yield* Scope.make(\"sequential\");\n          let sessionScopeTransferred = false;\n          yield* Effect.addFinalizer(() =>\n            sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),\n          );\n\n          const resumeSessionId = resolveResumeSessionId(descriptor, input.resumeCursor);\n          const acpNativeLoggers = makeAcpNativeLoggers({\n            nativeEventLogger,\n            provider: PROVIDER,\n            threadId: input.threadId,\n          });\n\n          const acp = yield* makeAcpAgentRuntime(descriptor, {\n            settings,\n            ...(options?.environment ? { environment: options.environment } : {}),\n            childProcessSpawner,\n            cwd,\n            ...(resumeSessionId ? { resumeSessionId } : {}),\n            clientInfo: { name: \"agentlink\", version: \"0.0.0\" },\n            ...acpNativeLoggers,\n          }).pipe(\n            Effect.provideService(Crypto.Crypto, crypto),\n            Effect.provideService(FileSystem.FileSystem, fileSystem),\n            Effect.provideService(Path.Path, path),\n            Effect.provideService(Scope.Scope, sessionScope),\n            Effect.mapError(\n              (cause) =>\n                new ProviderAdapterProcessError({\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  detail: cause.message,\n                  cause,\n                }),\n            ),\n          );\n          const started = yield* Effect.gen(function* () {\n            yield* acp.handleRequestPermission((params) =>\n              mapAcpCallbackFailure(\n                Effect.gen(function* () {\n                  yield* logNative(input.threadId, \"session/request_permission\", params);\n                  if (input.runtimeMode === \"full-access\") {\n                    const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);\n                    if (autoApprovedOptionId !== undefined) {\n                      return {\n                        outcome: {\n                          outcome: \"selected\" as const,\n                          optionId: autoApprovedOptionId,\n                        },\n                      };\n                    }\n                  }\n                  const permissionRequest = parsePermissionRequest(params);\n                  const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n                  const runtimeRequestId = RuntimeRequestId.make(requestId);\n                  const decision = yield* Deferred.make<ProviderApprovalDecision>();\n                  const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);\n                  pendingApprovals.set(requestId, { decision });\n                  yield* offerRuntimeEvent(\n                    makeAcpRequestOpenedEvent({\n                      stamp: yield* makeEventStamp(),\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      turnId,\n                      requestId: runtimeRequestId,\n                      permissionRequest,\n                      detail:\n                        permissionRequest.detail ??\n                        encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??\n                        \"[unserializable params]\",\n                      args: params,\n                      source: \"acp.jsonrpc\",\n                      method: \"session/request_permission\",\n                      rawPayload: params,\n                    }),\n                  );\n                  const resolved = yield* Deferred.await(decision);\n                  pendingApprovals.delete(requestId);\n                  yield* offerRuntimeEvent(\n                    makeAcpRequestResolvedEvent({\n                      stamp: yield* makeEventStamp(),\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      turnId,\n                      requestId: runtimeRequestId,\n                      permissionRequest,\n                      decision: resolved,\n                    }),\n                  );\n                  const selectedOptionId =\n                    resolved === \"cancel\" ? undefined : selectPermissionOptionId(params, resolved);\n                  return {\n                    outcome: selectedOptionId\n                      ? {\n                          outcome: \"selected\" as const,\n                          optionId: selectedOptionId,\n                        }\n                      : ({ outcome: \"cancelled\" } as const),\n                  };\n                }),\n              ),\n            );\n            return yield* acp.start();\n          }).pipe(\n            Effect.mapError((error) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, \"session/start\", error),\n            ),\n          );\n\n          const requestedStartModelId = modelSelection?.model\n            ? resolveAcpAgentModelId(descriptor, modelSelection.model)\n            : undefined;\n          const boundModelId = yield* applyAcpAgentModelSelection({\n            runtime: acp,\n            currentModelId: currentAcpAgentModelIdFromSessionSetup(started.sessionSetupResult),\n            requestedModelId: requestedStartModelId,\n            mapError: (cause) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, \"session/set_model\", cause),\n          });\n\n          const now = yield* nowIso;\n          const session: ProviderSession = {\n            provider: PROVIDER,\n            providerInstanceId: boundInstanceId,\n            status: \"ready\",\n            runtimeMode: input.runtimeMode,\n            cwd,\n            ...(boundModelId ? { model: resolveAcpAgentModelId(descriptor, boundModelId) } : {}),\n            threadId: input.threadId,\n            resumeCursor: makeAcpAgentResumeCursor(started.sessionId),\n            createdAt: now,\n            updatedAt: now,\n          };\n\n          const ctx: AcpAgentSessionContext = {\n            threadId: input.threadId,\n            acpSessionId: started.sessionId,\n            session,\n            scope: sessionScope,\n            acp,\n            notificationFiber: undefined,\n            pendingApprovals,\n            turns: [],\n            lastPlanFingerprint: undefined,\n            activeTurnId: undefined,\n            interruptedTurnIds: new Set(),\n            promptsInFlight: 0,\n            currentModelId: boundModelId,\n            stopped: false,\n          };\n\n          const nf = yield* Stream.runDrain(\n            Stream.mapEffect(acp.getEvents(), (event) =>\n              Effect.gen(function* () {\n                if (event._tag === \"EventStreamBarrier\") {\n                  yield* Deferred.succeed(event.acknowledge, undefined);\n                  return;\n                }\n                if (\n                  event._tag === \"PlanUpdated\" ||\n                  event._tag === \"ToolCallUpdated\" ||\n                  event._tag === \"ContentDelta\"\n                ) {\n                  yield* logNative(ctx.threadId, \"session/update\", event.rawPayload);\n                }\n\n                if (event._tag === \"ModeChanged\") {\n                  return;\n                }\n\n                const notificationTurnId = resolveNotificationTurnId(ctx);\n                if (\n                  notificationTurnId === undefined ||\n                  ctx.interruptedTurnIds.has(notificationTurnId)\n                ) {\n                  return;\n                }\n                const stamp = yield* makeEventStamp();\n\n                switch (event._tag) {\n                  case \"AssistantItemStarted\":\n                    yield* offerRuntimeEvent(\n                      makeAcpAssistantItemEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        itemId: event.itemId,\n                        lifecycle: \"item.started\",\n                      }),\n                    );\n                    return;\n                  case \"AssistantItemCompleted\":\n                    yield* offerRuntimeEvent(\n                      makeAcpAssistantItemEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        itemId: event.itemId,\n                        lifecycle: \"item.completed\",\n                      }),\n                    );\n                    return;\n                  case \"PlanUpdated\":\n                    yield* emitPlanUpdate(\n                      ctx,\n                      notificationTurnId,\n                      stamp,\n                      event.payload,\n                      event.rawPayload,\n                      \"session/update\",\n                    );\n                    return;\n                  case \"ToolCallUpdated\":\n                    yield* offerRuntimeEvent(\n                      makeAcpToolCallEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        toolCall: event.toolCall,\n                        rawPayload: event.rawPayload,\n                      }),\n                    );\n                    return;\n                  case \"ContentDelta\":\n                    yield* offerRuntimeEvent(\n                      makeAcpContentDeltaEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        ...(event.itemId ? { itemId: event.itemId } : {}),\n                        text: event.text,\n                        rawPayload: event.rawPayload,\n                      }),\n                    );\n                    return;\n                }\n              }),\n            ),\n          ).pipe(\n            Effect.catch((cause) =>\n              Effect.logError(\n                `Failed to process ${descriptor.displayName} runtime notification.`,\n                { cause },\n              ),\n            ),\n            Effect.forkChild,\n          );\n\n          ctx.notificationFiber = nf;\n          sessions.set(input.threadId, ctx);\n          sessionScopeTransferred = true;\n\n          yield* offerRuntimeEvent({\n            type: \"session.started\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { resume: started.initializeResult },\n          });\n          yield* offerRuntimeEvent({\n            type: \"session.state.changed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { state: \"ready\", reason: `${descriptor.displayName} ACP session ready` },\n          });\n          yield* offerRuntimeEvent({\n            type: \"thread.started\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { providerThreadId: started.sessionId },\n          });\n\n          return session;\n        }).pipe(Effect.scoped),\n      );\n\n    const sendTurn: ProviderAdapterShape<ProviderAdapterError>[\"sendTurn\"] = (input) =>\n      Effect.gen(function* () {\n        const prepared = yield* withThreadLock(\n          input.threadId,\n          Effect.gen(function* () {\n            const ctx = yield* requireSession(input.threadId);\n            // A sendTurn while a prompt is in flight is a steer: the agent\n            // folds the new prompt into the ongoing work, so the active turn\n            // id is reused instead of opening a new turn.\n            const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;\n            const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);\n            // Count this prompt immediately so a superseded in-flight prompt\n            // resolving from here on does not settle the turn; decremented on\n            // preparation failure here, and after the prompt below otherwise.\n            ctx.promptsInFlight += 1;\n            // Bind the turn id before cooperative yields so interruptTurn can\n            // settle this prompt even if stop arrives during preparation.\n            ctx.activeTurnId = turnId;\n            ctx.session = {\n              ...ctx.session,\n              status: steeringTurnId === undefined ? \"connecting\" : \"running\",\n              activeTurnId: turnId,\n              updatedAt: yield* nowIso,\n            };\n\n            return yield* Effect.gen(function* () {\n              const turnModelSelection =\n                input.modelSelection?.instanceId === boundInstanceId\n                  ? input.modelSelection\n                  : undefined;\n              const requestedTurnModelId = turnModelSelection?.model\n                ? resolveAcpAgentModelId(descriptor, turnModelSelection.model)\n                : undefined;\n              const currentModelId = yield* applyAcpAgentModelSelection({\n                runtime: ctx.acp,\n                currentModelId: ctx.currentModelId,\n                requestedModelId: requestedTurnModelId,\n                mapError: (cause) =>\n                  mapAcpToAdapterError(PROVIDER, input.threadId, \"session/set_model\", cause),\n              });\n\n              const text = input.input?.trim();\n              const imagePromptParts = yield* Effect.forEach(\n                input.attachments ?? [],\n                (attachment) =>\n                  Effect.gen(function* () {\n                    const attachmentPath = resolveAttachmentPath({\n                      attachmentsDir: serverConfig.attachmentsDir,\n                      attachment,\n                    });\n                    if (!attachmentPath) {\n                      return yield* new ProviderAdapterRequestError({\n                        provider: PROVIDER,\n                        method: \"session/prompt\",\n                        detail: `Invalid attachment id '${attachment.id}'.`,\n                      });\n                    }\n                    const bytes = yield* fileSystem.readFile(attachmentPath).pipe(\n                      Effect.mapError(\n                        (cause) =>\n                          new ProviderAdapterRequestError({\n                            provider: PROVIDER,\n                            method: \"session/prompt\",\n                            detail: cause.message,\n                            cause,\n                          }),\n                      ),\n                    );\n                    return {\n                      type: \"image\",\n                      data: Buffer.from(bytes).toString(\"base64\"),\n                      mimeType: attachment.mimeType,\n                    } satisfies EffectAcpSchema.ContentBlock;\n                  }),\n              );\n              const promptParts: Array<EffectAcpSchema.ContentBlock> = [\n                ...(text ? [{ type: \"text\" as const, text }] : []),\n                ...imagePromptParts,\n              ];\n\n              if (promptParts.length === 0) {\n                return yield* new ProviderAdapterValidationError({\n                  provider: PROVIDER,\n                  operation: \"sendTurn\",\n                  issue: \"Turn requires non-empty text or attachments.\",\n                });\n              }\n\n              ctx.currentModelId = currentModelId;\n              const displayModel = currentModelId\n                ? resolveAcpAgentModelId(descriptor, currentModelId)\n                : undefined;\n              for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {\n                yield* Effect.yieldNow;\n              }\n              if (ctx.interruptedTurnIds.has(turnId)) {\n                yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {\n                  completedStopReason: \"cancelled\",\n                  emitTurnCompletion: false,\n                  settleAllPrompts: true,\n                });\n                return yield* new ProviderAdapterRequestError({\n                  provider: PROVIDER,\n                  method: \"session/prompt\",\n                  detail: `${descriptor.displayName} prompt was interrupted during preparation.`,\n                });\n              }\n              if (steeringTurnId === undefined) {\n                ctx.lastPlanFingerprint = undefined;\n              }\n              ctx.session = {\n                ...ctx.session,\n                status: \"running\",\n                activeTurnId: turnId,\n                updatedAt: yield* nowIso,\n                ...(displayModel ? { model: displayModel } : {}),\n              };\n\n              if (steeringTurnId === undefined) {\n                yield* offerRuntimeEvent({\n                  type: \"turn.started\",\n                  ...(yield* makeEventStamp()),\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  turnId,\n                  payload: displayModel ? { model: displayModel } : {},\n                });\n              }\n\n              return {\n                acp: ctx.acp,\n                acpSessionId: ctx.acpSessionId,\n                displayModel,\n                promptParts,\n                turnId,\n              };\n            }).pipe(\n              Effect.tapCause(() =>\n                Effect.gen(function* () {\n                  const liveCtx = sessions.get(input.threadId);\n                  if (!liveCtx) {\n                    return;\n                  }\n                  yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {\n                    errorMessage: `${descriptor.displayName} prompt preparation failed.`,\n                    emitTurnCompletion: false,\n                  });\n                }),\n              ),\n            );\n          }),\n        );\n        const promptSettled = yield* Ref.make(false);\n        const promptRpcSucceeded = yield* Ref.make(false);\n        const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(\n          undefined,\n        );\n\n        const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);\n\n        return yield* Effect.gen(function* () {\n          const result = yield* prepared.acp\n            .prompt({\n              prompt: prepared.promptParts,\n            })\n            .pipe(\n              Effect.tap((promptResult) =>\n                Effect.all([\n                  Ref.set(promptRpcSucceeded, true),\n                  Ref.set(promptResultRef, promptResult),\n                ]),\n              ),\n              Effect.tapError((error) =>\n                Ref.set(\n                  promptFailureMessageRef,\n                  mapAcpToAdapterError(PROVIDER, input.threadId, \"session/prompt\", error).message,\n                ).pipe(Effect.andThen(prepared.acp.drainEvents)),\n              ),\n              Effect.mapError((error) =>\n                mapAcpToAdapterError(PROVIDER, input.threadId, \"session/prompt\", error),\n              ),\n            );\n\n          return yield* withThreadLock(\n            input.threadId,\n            Effect.gen(function* () {\n              const ctx = yield* requireSession(input.threadId);\n              if (ctx.acpSessionId !== prepared.acpSessionId) {\n                yield* settlePromptInFlight(\n                  input.threadId,\n                  prepared.turnId,\n                  prepared.acpSessionId,\n                  {\n                    errorMessage: `${descriptor.displayName} session changed before the turn completed.`,\n                    settleAllPrompts: true,\n                  },\n                );\n                yield* Ref.set(promptSettled, true);\n                return yield* new ProviderAdapterRequestError({\n                  provider: PROVIDER,\n                  method: \"session/prompt\",\n                  detail: `${descriptor.displayName} session changed before the turn completed.`,\n                });\n              }\n              // Keep prompt settlement atomic with respect to Stop and steering.\n              // interruptTurn marks its target before waiting for this lock, so\n              // cancellation can still win while queued ACP events are drained.\n              for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {\n                yield* Effect.yieldNow;\n              }\n              yield* prepared.acp.drainEvents;\n              if (ctx.interruptedTurnIds.has(prepared.turnId)) {\n                yield* Ref.set(promptSettled, true);\n                return {\n                  threadId: input.threadId,\n                  turnId: prepared.turnId,\n                  resumeCursor: ctx.session.resumeCursor,\n                };\n              }\n\n              if (\n                ctx.promptsInFlight <= 0 ||\n                ctx.activeTurnId !== prepared.turnId ||\n                ctx.session.activeTurnId !== prepared.turnId\n              ) {\n                yield* Ref.set(promptSettled, true);\n                return {\n                  threadId: input.threadId,\n                  turnId: prepared.turnId,\n                  resumeCursor: ctx.session.resumeCursor,\n                };\n              }\n\n              appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);\n              ctx.session = {\n                ...ctx.session,\n                status: \"running\",\n                activeTurnId: prepared.turnId,\n                updatedAt: yield* nowIso,\n                ...(prepared.displayModel ? { model: prepared.displayModel } : {}),\n              };\n              const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);\n              ctx.promptsInFlight = remainingPrompts;\n\n              // Only the last remaining prompt settles the turn. A steer-\n              // superseded prompt resolving while another is in flight or\n              // pending must leave the merged turn running.\n              if (\n                remainingPrompts === 0 &&\n                ctx.activeTurnId === prepared.turnId &&\n                ctx.session.activeTurnId === prepared.turnId\n              ) {\n                if (ctx.interruptedTurnIds.has(prepared.turnId)) {\n                  yield* Ref.set(promptSettled, true);\n                  return {\n                    threadId: input.threadId,\n                    turnId: prepared.turnId,\n                    resumeCursor: ctx.session.resumeCursor,\n                  };\n                }\n                const completedAt = yield* nowIso;\n                const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;\n                ctx.activeTurnId = undefined;\n                ctx.session = {\n                  ...readySession,\n                  status: \"ready\",\n                  updatedAt: completedAt,\n                  ...(prepared.displayModel ? { model: prepared.displayModel } : {}),\n                };\n                yield* offerRuntimeEvent({\n                  type: \"turn.completed\",\n                  ...(yield* makeEventStamp()),\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  turnId: prepared.turnId,\n                  payload: {\n                    state: result.stopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n                    stopReason: result.stopReason,\n                  },\n                });\n                ctx.interruptedTurnIds.delete(prepared.turnId);\n                yield* Ref.set(promptSettled, true);\n              } else if (remainingPrompts > 0) {\n                yield* Ref.set(promptSettled, true);\n              }\n\n              return {\n                threadId: input.threadId,\n                turnId: prepared.turnId,\n                resumeCursor: ctx.session.resumeCursor,\n              };\n            }),\n          );\n        }).pipe(\n          Effect.ensuring(\n            Effect.gen(function* () {\n              if (yield* Ref.get(promptSettled)) {\n                return;\n              }\n\n              if (yield* Ref.get(promptRpcSucceeded)) {\n                const promptResult = yield* Ref.get(promptResultRef);\n                if (promptResult === undefined) {\n                  return;\n                }\n                yield* withThreadLock(\n                  input.threadId,\n                  Effect.gen(function* () {\n                    const ctx = yield* requireSession(input.threadId);\n                    if (ctx.acpSessionId !== prepared.acpSessionId) {\n                      yield* settlePromptInFlight(\n                        input.threadId,\n                        prepared.turnId,\n                        prepared.acpSessionId,\n                        {\n                          errorMessage: `${descriptor.displayName} session changed before the turn completed.`,\n                          settleAllPrompts: true,\n                        },\n                      );\n                      return;\n                    }\n                    if (ctx.interruptedTurnIds.has(prepared.turnId)) {\n                      return;\n                    }\n                    if (\n                      ctx.promptsInFlight <= 0 ||\n                      ctx.activeTurnId !== prepared.turnId ||\n                      ctx.session.activeTurnId !== prepared.turnId\n                    ) {\n                      return;\n                    }\n                    appendPromptResultToTurn(\n                      ctx,\n                      prepared.turnId,\n                      prepared.promptParts,\n                      promptResult,\n                    );\n                    yield* settlePromptInFlight(\n                      input.threadId,\n                      prepared.turnId,\n                      prepared.acpSessionId,\n                      {\n                        completedStopReason: promptResult.stopReason,\n                      },\n                    );\n                  }),\n                );\n                return;\n              }\n\n              const errorMessage = yield* Ref.get(promptFailureMessageRef);\n              yield* withThreadLock(\n                input.threadId,\n                settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {\n                  errorMessage: errorMessage ?? `${descriptor.displayName} prompt request failed.`,\n                }),\n              );\n            }).pipe(Effect.catch(() => Effect.void)),\n          ),\n        );\n      });\n\n    const interruptTurn: ProviderAdapterShape<ProviderAdapterError>[\"interruptTurn\"] = (\n      threadId,\n      turnId,\n    ) =>\n      Effect.gen(function* () {\n        const observed = yield* Effect.sync(() => {\n          const ctx = sessions.get(threadId);\n          if (!ctx || ctx.stopped) {\n            return {\n              _tag: \"Proceed\" as const,\n              acpSessionId: undefined,\n              interruptedTurnId: turnId,\n            };\n          }\n          const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;\n          if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {\n            return { _tag: \"Ignore\" as const };\n          }\n          const interruptedTurnId = turnId ?? activeTurnId;\n          if (interruptedTurnId !== undefined) {\n            ctx.interruptedTurnIds.add(interruptedTurnId);\n          }\n          return {\n            _tag: \"Proceed\" as const,\n            acpSessionId: ctx.acpSessionId,\n            interruptedTurnId,\n          };\n        });\n        if (observed._tag === \"Ignore\") {\n          return;\n        }\n\n        yield* withThreadLock(\n          threadId,\n          Effect.gen(function* () {\n            const ctx = yield* requireSession(threadId);\n            if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {\n              return;\n            }\n            const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;\n            if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {\n              return;\n            }\n            if (\n              observed.interruptedTurnId !== undefined &&\n              activeTurnId !== undefined &&\n              activeTurnId !== observed.interruptedTurnId\n            ) {\n              return;\n            }\n            const interruptedTurnId =\n              observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;\n            yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);\n            yield* Effect.ignore(\n              ctx.acp.cancel.pipe(\n                Effect.mapError((error) =>\n                  mapAcpToAdapterError(PROVIDER, threadId, \"session/cancel\", error),\n                ),\n              ),\n            );\n            if (interruptedTurnId) {\n              ctx.interruptedTurnIds.add(interruptedTurnId);\n              yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {\n                completedStopReason: \"cancelled\",\n                settleAllPrompts: true,\n              });\n            } else if (\n              ctx.promptsInFlight > 0 ||\n              ctx.session.status === \"running\" ||\n              ctx.session.status === \"connecting\"\n            ) {\n              const updatedAt = yield* nowIso;\n              ctx.promptsInFlight = 0;\n              ctx.activeTurnId = undefined;\n              const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;\n              ctx.session = {\n                ...readySession,\n                status: \"ready\",\n                updatedAt,\n              };\n            }\n          }),\n        );\n      });\n\n    const respondToRequest: ProviderAdapterShape<ProviderAdapterError>[\"respondToRequest\"] = (\n      threadId,\n      requestId,\n      decision,\n    ) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        const pending = ctx.pendingApprovals.get(requestId);\n        if (!pending) {\n          return yield* new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"session/request_permission\",\n            detail: `Unknown pending approval request: ${requestId}`,\n          });\n        }\n        yield* Deferred.succeed(pending.decision, decision);\n      });\n\n    const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>[\"respondToUserInput\"] = (\n      threadId,\n      requestId,\n      _answers,\n    ) =>\n      Effect.gen(function* () {\n        yield* requireSession(threadId);\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"session/elicitation\",\n          detail: `${descriptor.displayName} ACP sessions do not emit structured user-input requests (request ${requestId}).`,\n        });\n      });\n\n    const readThread: ProviderAdapterShape<ProviderAdapterError>[\"readThread\"] = (input) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(input.threadId);\n        return { threadId: input.threadId, turns: ctx.turns };\n      });\n\n    const rollbackThread: ProviderAdapterShape<ProviderAdapterError>[\"rollbackThread\"] = (\n      threadId,\n      numTurns,\n    ) =>\n      Effect.gen(function* () {\n        yield* requireSession(threadId);\n        if (!Number.isInteger(numTurns) || numTurns < 1) {\n          return yield* new ProviderAdapterValidationError({\n            provider: PROVIDER,\n            operation: \"rollbackThread\",\n            issue: \"numTurns must be an integer >= 1.\",\n          });\n        }\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"thread/rollback\",\n          detail: `${descriptor.displayName} ACP sessions do not support provider-side rollback yet.`,\n        });\n      });\n\n    const stopSession: ProviderAdapterShape<ProviderAdapterError>[\"stopSession\"] = (threadId) =>\n      withThreadLock(\n        threadId,\n        Effect.gen(function* () {\n          const ctx = yield* requireSession(threadId);\n          yield* stopSessionInternal(ctx);\n        }),\n      );\n\n    const listSessions: ProviderAdapterShape<ProviderAdapterError>[\"listSessions\"] = () =>\n      Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));\n\n    const hasSession: ProviderAdapterShape<ProviderAdapterError>[\"hasSession\"] = (threadId) =>\n      Effect.sync(() => {\n        const c = sessions.get(threadId);\n        return c !== undefined && !c.stopped;\n      });\n\n    const stopAll: ProviderAdapterShape<ProviderAdapterError>[\"stopAll\"] = () =>\n      Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true });\n\n    yield* Effect.addFinalizer(() =>\n      Effect.ignore(stopAll()).pipe(\n        Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),\n        Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),\n      ),\n    );\n\n    const streamEvents = Stream.fromPubSub(runtimeEventPubSub);\n\n    return {\n      provider: PROVIDER,\n      capabilities: { sessionModelSwitch: \"in-session\" },\n      startSession,\n      sendTurn,\n      interruptTurn,\n      readThread,\n      rollbackThread,\n      respondToRequest,\n      respondToUserInput,\n      stopSession,\n      listSessions,\n      hasSession,\n      stopAll,\n      streamEvents,\n    } satisfies ProviderAdapterShape<ProviderAdapterError>;\n  });\n}\n","/**\n * AcpAgentProvider — generic snapshot/probe layer for the fork's ACP CLIs\n * (Gemini / Qwen / Kimi / JoyCode), ported from the upstream `GrokProvider` and\n * parameterized by `AcpAgentDescriptor`.\n *\n * The probe sequence is:\n *   1. `<bin> --version` with a short timeout — detects \"not installed\"\n *      (command resolution failure) vs \"installed but broken\" (non-zero\n *      exit) vs \"hangs\" (timeout).\n *   2. ACP model discovery: boot the runtime (`makeAcpAgentRuntime`),\n *      `initialize` + `session/new`, read `models.availableModels` from the\n *      setup result. Failure/timeout here degrades the snapshot to `error`\n *      with the fallback model list rather than failing the check.\n *\n * @module provider/Layers/AcpAgentProvider\n */\nimport {\n  type ModelCapabilities,\n  type ServerProvider,\n  type ServerProviderModel,\n} from \"@t3tools/contracts\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { createModelCapabilities } from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport {\n  buildServerProvider,\n  isCommandMissingCause,\n  parseGenericCliVersion,\n  providerModelsFromSettings,\n  spawnAndCollect,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  type ProviderMaintenanceCapabilities,\n} from \"../providerMaintenance.ts\";\nimport {\n  makeAcpAgentRuntime,\n  resolveAcpAgentModelId,\n  type AcpAgentDescriptor,\n  type AcpAgentSettings,\n} from \"../acp/AcpAgentSupport.ts\";\n\nconst EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n  optionDescriptors: [],\n});\n\nconst VERSION_PROBE_TIMEOUT_MS = 4_000;\nconst ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;\n\nexport function buildInitialAcpAgentProviderSnapshot(\n  descriptor: AcpAgentDescriptor,\n  settings: AcpAgentSettings & { readonly enabled: boolean },\n): Effect.Effect<ServerProviderDraft> {\n  return Effect.gen(function* () {\n    const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);\n    const models = acpAgentModelsFromSettings(descriptor, settings.customModels);\n\n    if (!settings.enabled) {\n      return buildServerProvider({\n        presentation: descriptorPresentation(descriptor),\n        enabled: false,\n        checkedAt,\n        models,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: `${descriptor.displayName} is disabled in settings.`,\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: descriptorPresentation(descriptor),\n      enabled: true,\n      checkedAt,\n      models,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: `Checking ${descriptor.displayName} availability...`,\n      },\n    });\n  });\n}\n\nconst descriptorPresentation = (descriptor: AcpAgentDescriptor) =>\n  ({\n    displayName: descriptor.displayName,\n    showInteractionModeToggle: false,\n    requiresNewThreadForModelChange: true,\n  }) as const;\n\nfunction acpAgentModelsFromSettings(\n  descriptor: AcpAgentDescriptor,\n  customModels: ReadonlyArray<string> | undefined,\n  builtInModels?: ReadonlyArray<ServerProviderModel>,\n): ReadonlyArray<ServerProviderModel> {\n  const builtIns =\n    builtInModels ??\n    descriptor.builtInModels.map(\n      (slug): ServerProviderModel => ({\n        slug,\n        name: slug,\n        isCustom: false,\n        capabilities: EMPTY_CAPABILITIES,\n      }),\n    );\n  return providerModelsFromSettings(builtIns, customModels ?? [], EMPTY_CAPABILITIES);\n}\n\nfunction buildDiscoveredModelsFromSessionModelState(\n  descriptor: AcpAgentDescriptor,\n  modelState: EffectAcpSchema.SessionModelState | null | undefined,\n): ReadonlyArray<ServerProviderModel> {\n  if (!modelState || modelState.availableModels.length === 0) {\n    return [];\n  }\n  const seen = new Set<string>();\n  return modelState.availableModels\n    .map((model): ServerProviderModel | undefined => {\n      const slug = resolveAcpAgentModelId(descriptor, model.modelId);\n      if (!slug || seen.has(slug)) {\n        return undefined;\n      }\n      seen.add(slug);\n      return {\n        slug,\n        name: model.name.trim() || slug,\n        isCustom: false,\n        capabilities: EMPTY_CAPABILITIES,\n      };\n    })\n    .filter((model): model is ServerProviderModel => model !== undefined);\n}\n\nexport function buildDiscoveredAcpAgentModels(\n  descriptor: AcpAgentDescriptor,\n  sessionSetupResult:\n    | EffectAcpSchema.LoadSessionResponse\n    | EffectAcpSchema.NewSessionResponse\n    | EffectAcpSchema.ResumeSessionResponse,\n): ReadonlyArray<ServerProviderModel> {\n  const models = buildDiscoveredModelsFromSessionModelState(\n    descriptor,\n    sessionSetupResult.models,\n  );\n  if (models.length > 0) {\n    return models;\n  }\n\n  const modelConfig = sessionSetupResult.configOptions?.find(\n    (option) => option.category === \"model\" && option.type === \"select\",\n  );\n  if (!modelConfig || modelConfig.type !== \"select\") {\n    return [];\n  }\n\n  const options = modelConfig.options.flatMap((entry) =>\n    \"value\" in entry ? [entry] : entry.options,\n  );\n  const seen = new Set<string>();\n  return options\n    .map((option): ServerProviderModel | undefined => {\n      const slug = resolveAcpAgentModelId(descriptor, option.value);\n      if (!slug || seen.has(slug)) {\n        return undefined;\n      }\n      seen.add(slug);\n      return {\n        slug,\n        name: option.name.trim() || slug,\n        isCustom: false,\n        capabilities: EMPTY_CAPABILITIES,\n      };\n    })\n    .filter((model): model is ServerProviderModel => model !== undefined);\n}\n\nconst discoverModelsViaAcp = (\n  descriptor: AcpAgentDescriptor,\n  settings: AcpAgentSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n) =>\n  Effect.gen(function* () {\n    const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const acp = yield* makeAcpAgentRuntime(descriptor, {\n      settings,\n      environment,\n      childProcessSpawner,\n      cwd: process.cwd(),\n      clientInfo: { name: \"agentlink-provider-probe\", version: \"0.0.0\" },\n    });\n    const started = yield* acp.start();\n    return buildDiscoveredAcpAgentModels(descriptor, started.sessionSetupResult);\n  }).pipe(Effect.scoped);\n\nconst runVersionCommand = (\n  descriptor: AcpAgentDescriptor,\n  settings: AcpAgentSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n) =>\n  Effect.gen(function* () {\n    const command = settings.binaryPath.trim() || descriptor.defaultBinary;\n    const spawnCommand = yield* resolveSpawnCommand(command, [\"--version\"], {\n      env: environment,\n    });\n    return yield* spawnAndCollect(\n      command,\n      ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        env: environment,\n        shell: spawnCommand.shell,\n      }),\n    );\n  });\n\nexport const checkAcpAgentProviderStatus = (\n  descriptor: AcpAgentDescriptor,\n  settings: AcpAgentSettings & { readonly enabled: boolean },\n  environment: NodeJS.ProcessEnv = process.env,\n): Effect.Effect<\n  ServerProviderDraft,\n  never,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path\n> =>\n  Effect.gen(function* () {\n    const checkedAt = DateTime.formatIso(yield* DateTime.now);\n    const fallbackModels = acpAgentModelsFromSettings(descriptor, settings.customModels);\n    const presentation = descriptorPresentation(descriptor);\n\n    if (!settings.enabled) {\n      return buildServerProvider({\n        presentation,\n        enabled: false,\n        checkedAt,\n        models: fallbackModels,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: `${descriptor.displayName} is disabled in settings.`,\n        },\n      });\n    }\n\n    const versionResult = yield* runVersionCommand(descriptor, settings, environment).pipe(\n      Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),\n      Effect.result,\n    );\n\n    if (Result.isFailure(versionResult)) {\n      const error = versionResult.failure;\n      yield* Effect.logWarning(`${descriptor.displayName} health check failed.`, {\n        errorTag: error._tag,\n      });\n      return buildServerProvider({\n        presentation,\n        enabled: settings.enabled,\n        checkedAt,\n        models: fallbackModels,\n        probe: {\n          installed: !isCommandMissingCause(error),\n          version: null,\n          status: \"error\",\n          auth: { status: \"unknown\" },\n          message: isCommandMissingCause(error)\n            ? descriptor.missingBinaryMessage ??\n              `${descriptor.displayName} (\\`${descriptor.defaultBinary}\\`) is not installed or not on PATH.`\n            : `Failed to execute ${descriptor.displayName} health check.`,\n        },\n      });\n    }\n\n    if (Option.isNone(versionResult.success)) {\n      return buildServerProvider({\n        presentation,\n        enabled: settings.enabled,\n        checkedAt,\n        models: fallbackModels,\n        probe: {\n          installed: true,\n          version: null,\n          status: \"error\",\n          auth: { status: \"unknown\" },\n          message: `${descriptor.displayName} is installed but timed out while running \\`${descriptor.defaultBinary} --version\\`.`,\n        },\n      });\n    }\n\n    const versionOutput = versionResult.success.value;\n    const version = parseGenericCliVersion(`${versionOutput.stdout}\\n${versionOutput.stderr}`);\n    if (versionOutput.code !== 0) {\n      yield* Effect.logWarning(\n        `${descriptor.displayName} version probe exited with a non-zero status.`,\n        {\n          exitCode: versionOutput.code,\n          stdoutLength: versionOutput.stdout.length,\n          stderrLength: versionOutput.stderr.length,\n        },\n      );\n      return buildServerProvider({\n        presentation,\n        enabled: settings.enabled,\n        checkedAt,\n        models: fallbackModels,\n        probe: {\n          installed: true,\n          version,\n          status: \"error\",\n          auth: { status: \"unknown\" },\n          message: `${descriptor.displayName} is installed but failed to run.`,\n        },\n      });\n    }\n\n    const discoveryExit = yield* discoverModelsViaAcp(descriptor, settings, environment).pipe(\n      Effect.timeoutOption(ACP_MODEL_DISCOVERY_TIMEOUT_MS),\n      Effect.exit,\n    );\n    if (Exit.isFailure(discoveryExit)) {\n      yield* Effect.logWarning(`${descriptor.displayName} ACP model discovery failed`, {\n        errorTag: causeErrorTag(discoveryExit.cause),\n      });\n      return buildServerProvider({\n        presentation,\n        enabled: settings.enabled,\n        checkedAt,\n        models: fallbackModels,\n        probe: {\n          installed: true,\n          version,\n          status: \"error\",\n          auth: { status: \"unknown\" },\n          message: `${descriptor.displayName} is installed but ACP startup failed. Check server logs for details.`,\n        },\n      });\n    }\n    if (Option.isNone(discoveryExit.value)) {\n      yield* Effect.logWarning(\n        `${descriptor.displayName} ACP model discovery timed out after ${ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,\n      );\n      return buildServerProvider({\n        presentation,\n        enabled: settings.enabled,\n        checkedAt,\n        models: fallbackModels,\n        probe: {\n          installed: true,\n          version,\n          status: \"error\",\n          auth: { status: \"unknown\" },\n          message: `${descriptor.displayName} is installed but ACP startup timed out after ${ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,\n        },\n      });\n    }\n    const discoveredModels = discoveryExit.value.value;\n    const models =\n      discoveredModels.length > 0\n        ? acpAgentModelsFromSettings(descriptor, settings.customModels, discoveredModels)\n        : fallbackModels;\n\n    return buildServerProvider({\n      presentation,\n      enabled: settings.enabled,\n      checkedAt,\n      models,\n      probe: {\n        installed: true,\n        version,\n        status: \"ready\",\n        auth: { status: \"unknown\" },\n      },\n    });\n  });\n\nexport const enrichAcpAgentSnapshot = (\n  descriptor: AcpAgentDescriptor,\n  input: {\n    readonly snapshot: ServerProvider;\n    readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;\n    readonly enableProviderUpdateChecks?: boolean;\n    readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;\n    readonly httpClient: HttpClient.HttpClient;\n  },\n): Effect.Effect<void> =>\n  enrichProviderSnapshotWithVersionAdvisory(input.snapshot, input.maintenanceCapabilities, {\n    enableProviderUpdateChecks: input.enableProviderUpdateChecks,\n  }).pipe(\n    Effect.provideService(HttpClient.HttpClient, input.httpClient),\n    Effect.flatMap((enrichedSnapshot) => input.publishSnapshot(enrichedSnapshot)),\n    Effect.catchCause((cause) =>\n      Effect.logWarning(`${descriptor.displayName} version advisory enrichment failed`, {\n        errorTag: causeErrorTag(cause),\n      }),\n    ),\n    Effect.asVoid,\n  );\n","/**\n * makeAcpAgentDriver — factory for the fork's ACP `ProviderDriver`s\n * (Gemini / Qwen / Kimi / JoyCode).\n *\n * Mirrors the upstream `GrokDriver` shape: a plain value whose `create()`\n * returns one `ProviderInstance` bundling `snapshot` / `adapter` /\n * `textGeneration` closures captured over the per-instance settings. The\n * per-agent behavior lives in the `AcpAgentDescriptor`; this module wires\n * the generic `AcpAgentAdapter` / `AcpAgentProvider` /\n * `AcpAgentTextGeneration` into the driver SPI.\n *\n * The npm package advisory is resolved through\n * `makePackageManagedProviderMaintenanceResolver`, which falls back to\n * manual-only maintenance when the package lookup can't run.\n *\n * @module provider/Drivers/makeAcpAgentDriver\n */\nimport { ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { makeAcpAgentTextGeneration } from \"../../textGeneration/AcpAgentTextGeneration.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeAcpAgentAdapter } from \"../Layers/AcpAgentAdapter.ts\";\nimport {\n  buildInitialAcpAgentProviderSnapshot,\n  checkAcpAgentProviderStatus,\n  enrichAcpAgentSnapshot,\n} from \"../Layers/AcpAgentProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport {\n  defaultProviderContinuationIdentity,\n  type ProviderDriver,\n  type ProviderInstance,\n} from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  makePackageManagedProviderMaintenanceResolver,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nimport type { AcpAgentDescriptor, AcpAgentSettings } from \"../acp/AcpAgentSupport.ts\";\n\nexport type AcpAgentDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\nexport interface AcpAgentDriverInput {\n  readonly descriptor: AcpAgentDescriptor;\n  /** npm package the CLI is distributed as; used for update advisories. */\n  readonly npmPackageName: string;\n  /**\n   * Display name for the driver itself (registry metadata). Defaults to the\n   * descriptor's display name.\n   */\n  readonly driverDisplayName?: string;\n}\n\ntype AcpAgentDriverSettings = AcpAgentSettings & { readonly enabled: boolean };\n\nconst withInstanceIdentity =\n  (\n    driverKind: ProviderDriverKind,\n    input: {\n      readonly instanceId: ProviderInstance[\"instanceId\"];\n      readonly displayName: string | undefined;\n      readonly accentColor: string | undefined;\n      readonly continuationGroupKey: string;\n    },\n  ) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: driverKind,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport function makeAcpAgentDriver<S extends AcpAgentDriverSettings>(input: {\n  readonly driver: AcpAgentDriverInput;\n  readonly configSchema: Schema.Codec<S, unknown>;\n  readonly defaultConfig: () => S;\n}): ProviderDriver<S, AcpAgentDriverEnv> {\n  const { descriptor, npmPackageName } = input.driver;\n  const DRIVER_KIND = descriptor.provider;\n  const UPDATE = makePackageManagedProviderMaintenanceResolver({\n    provider: DRIVER_KIND,\n    npmPackageName,\n    homebrewFormula: null,\n    nativeUpdate: null,\n  });\n\n  return {\n    driverKind: DRIVER_KIND,\n    metadata: {\n      displayName: input.driver.driverDisplayName ?? descriptor.displayName,\n      supportsMultipleInstances: true,\n    },\n    configSchema: input.configSchema,\n    defaultConfig: input.defaultConfig,\n    create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n      Effect.gen(function* () {\n        const crypto = yield* Crypto.Crypto;\n        const fileSystem = yield* FileSystem.FileSystem;\n        const path = yield* Path.Path;\n        const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n        const httpClient = yield* HttpClient.HttpClient;\n        const serverSettings = yield* ServerSettingsService;\n        const eventLoggers = yield* ProviderEventLoggers;\n        const processEnv = mergeProviderInstanceEnvironment(environment);\n        const continuationIdentity = defaultProviderContinuationIdentity({\n          driverKind: DRIVER_KIND,\n          instanceId,\n        });\n        const stampIdentity = withInstanceIdentity(DRIVER_KIND, {\n          instanceId,\n          displayName,\n          accentColor,\n          continuationGroupKey: continuationIdentity.continuationKey,\n        });\n        const effectiveConfig = { ...config, enabled } satisfies S;\n        const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(\n          UPDATE,\n          {\n            binaryPath: effectiveConfig.binaryPath,\n            env: processEnv,\n          },\n        );\n\n        const adapter = yield* makeAcpAgentAdapter(descriptor, effectiveConfig, {\n          environment: processEnv,\n          ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n          instanceId,\n        });\n        const textGeneration = yield* makeAcpAgentTextGeneration(\n          descriptor,\n          effectiveConfig,\n          processEnv,\n        );\n\n        const checkProvider = checkAcpAgentProviderStatus(\n          descriptor,\n          effectiveConfig,\n          processEnv,\n        ).pipe(\n          Effect.map(stampIdentity),\n          Effect.provideService(Crypto.Crypto, crypto),\n          Effect.provideService(FileSystem.FileSystem, fileSystem),\n          Effect.provideService(Path.Path, path),\n          Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n        );\n\n        const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n        const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<S>>({\n          maintenanceCapabilities,\n          getSettings: snapshotSettings.getSettings,\n          streamSettings: snapshotSettings.streamSettings,\n          haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n          initialSnapshot: (settings) =>\n            buildInitialAcpAgentProviderSnapshot(descriptor, settings.provider).pipe(\n              Effect.map(stampIdentity),\n            ),\n          checkProvider,\n          // Model catalog and capabilities come exclusively from the ACP\n          // session model state observed during provider checks.\n          enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>\n            enrichAcpAgentSnapshot(descriptor, {\n              snapshot: currentSnapshot,\n              maintenanceCapabilities,\n              enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n              publishSnapshot,\n              httpClient,\n            }),\n        }).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderDriverError({\n                driver: DRIVER_KIND,\n                instanceId,\n                detail: `Failed to build ${descriptor.displayName} snapshot: ${cause.message ?? String(cause)}`,\n                cause,\n              }),\n          ),\n        );\n\n        return {\n          instanceId,\n          driverKind: DRIVER_KIND,\n          continuationIdentity,\n          displayName,\n          accentColor,\n          enabled,\n          snapshot,\n          adapter,\n          textGeneration,\n        } satisfies ProviderInstance;\n      }),\n  };\n}\n","/**\n * GeminiDriver — `ProviderDriver` for Google's Gemini CLI\n * (`gemini --experimental-acp`), built on the generic ACP agent machinery.\n *\n * @module provider/Drivers/GeminiDriver\n */\nimport { GeminiSettings } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nimport { GeminiAcpAgent } from \"../acp/GeminiAcpAgent.ts\";\nimport { makeAcpAgentDriver, type AcpAgentDriverEnv } from \"./makeAcpAgentDriver.ts\";\n\nconst decodeGeminiSettings = Schema.decodeSync(GeminiSettings);\n\nexport type GeminiDriverEnv = AcpAgentDriverEnv;\n\nexport const GeminiDriver = makeAcpAgentDriver({\n  driver: {\n    descriptor: GeminiAcpAgent,\n    npmPackageName: \"@google/gemini-cli\",\n  },\n  configSchema: GeminiSettings,\n  defaultConfig: (): GeminiSettings => decodeGeminiSettings({}),\n});\n","/**\n * JoyCodeAcpAgent — descriptor for JoyCode CLI. `joycode app-server` starts\n * its ACP server over stdio.\n *\n * JoyCode 1.0.1 advertises both `loadSession` and `session/resume`, but its\n * `session/load` response is currently JSON-RPC `null`. daemon-t3 decodes\n * that response as an ACP LoadSessionResponse object, so the probe driver\n * deliberately starts fresh until that compatibility boundary is resolved.\n *\n * @module provider/acp/JoyCodeAcpAgent\n */\nimport { ProviderDriverKind } from \"@t3tools/contracts\";\n\nimport type { AcpAgentDescriptor } from \"./AcpAgentSupport.ts\";\n\nexport const JoyCodeAcpAgent: AcpAgentDescriptor = {\n  provider: ProviderDriverKind.make(\"joycode\"),\n  displayName: \"JoyCode\",\n  defaultBinary: \"joycode\",\n  acpArgs: [\"app-server\"],\n  defaultModel: \"default\",\n  builtInModels: [\"default\"],\n  missingBinaryMessage: \"请安装 joycode-cli，参考内部文档。\",\n  supportsSessionLoad: false,\n};\n","/** JoyCodeDriver — JoyCode CLI (`joycode app-server`) via generic ACP. */\nimport { JoyCodeSettings } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nimport { JoyCodeAcpAgent } from \"../acp/JoyCodeAcpAgent.ts\";\nimport { makeAcpAgentDriver, type AcpAgentDriverEnv } from \"./makeAcpAgentDriver.ts\";\n\nconst decodeJoyCodeSettings = Schema.decodeSync(JoyCodeSettings);\n\nexport type JoyCodeDriverEnv = AcpAgentDriverEnv;\n\nexport const JoyCodeDriver = makeAcpAgentDriver({\n  driver: {\n    descriptor: JoyCodeAcpAgent,\n    npmPackageName: \"@joycode/joycode-cli\",\n  },\n  configSchema: JoyCodeSettings,\n  defaultConfig: (): JoyCodeSettings => decodeJoyCodeSettings({}),\n});\n","/**\n * KimiAcpAgent — descriptor for the Kimi CLI (Kimi Code CLI, Moonshot),\n * backed by the Kimi K2 model line. `kimi acp` starts the agent in Agent\n * Client Protocol mode over stdio. Kimi CLI is not known to advertise ACP\n * `loadSession`, so resume cursors are ignored and every session starts\n * fresh.\n *\n * @module provider/acp/KimiAcpAgent\n */\nimport { ProviderDriverKind } from \"@t3tools/contracts\";\n\nimport type { AcpAgentDescriptor } from \"./AcpAgentSupport.ts\";\n\nexport const KimiAcpAgent: AcpAgentDescriptor = {\n  provider: ProviderDriverKind.make(\"kimi\"),\n  displayName: \"Kimi CLI\",\n  defaultBinary: \"kimi\",\n  acpArgs: [\"acp\"],\n  defaultModel: \"kimi-k2\",\n  builtInModels: [\"kimi-k2\", \"kimi-for-coding\"],\n  supportsSessionLoad: false,\n  // Kimi CLI delegates its local tools (Bash/Read/Write/Grep/Glob) to the\n  // ACP client; without the fs/terminal capabilities every such call fails\n  // with \"ACP terminal capability is unavailable\".\n  hostLocalTools: true,\n};\n","/**\n * KimiDriver — `ProviderDriver` for the Kimi CLI (`kimi acp`), built on the\n * generic ACP agent machinery.\n *\n * @module provider/Drivers/KimiDriver\n */\nimport { KimiSettings } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nimport { KimiAcpAgent } from \"../acp/KimiAcpAgent.ts\";\nimport { makeAcpAgentDriver, type AcpAgentDriverEnv } from \"./makeAcpAgentDriver.ts\";\n\nconst decodeKimiSettings = Schema.decodeSync(KimiSettings);\n\nexport type KimiDriverEnv = AcpAgentDriverEnv;\n\nexport const KimiDriver = makeAcpAgentDriver({\n  driver: {\n    descriptor: KimiAcpAgent,\n    npmPackageName: \"@kimi-cli/kimi-cli\",\n  },\n  configSchema: KimiSettings,\n  defaultConfig: (): KimiSettings => decodeKimiSettings({}),\n});\n","/**\n * QwenAcpAgent — descriptor for Qwen Code (`qwen`, `@qwen-code/qwen-code`),\n * a Gemini CLI fork that speaks ACP natively via `qwen --experimental-acp`.\n * Unlike Gemini CLI, Qwen Code advertises ACP `loadSession`, so persisted\n * session ids are honored on resume (session/load by id).\n *\n * @module provider/acp/QwenAcpAgent\n */\nimport { ProviderDriverKind } from \"@t3tools/contracts\";\n\nimport type { AcpAgentDescriptor } from \"./AcpAgentSupport.ts\";\n\nexport const QwenAcpAgent: AcpAgentDescriptor = {\n  provider: ProviderDriverKind.make(\"qwen\"),\n  displayName: \"Qwen Code\",\n  defaultBinary: \"qwen\",\n  acpArgs: [\"--experimental-acp\"],\n  defaultModel: \"qwen3-coder-plus\",\n  builtInModels: [\"qwen3-coder-plus\", \"qwen3-coder-flash\"],\n  supportsSessionLoad: true,\n};\n","/**\n * QwenDriver — `ProviderDriver` for Qwen Code\n * (`qwen --experimental-acp`), built on the generic ACP agent machinery.\n * Qwen Code advertises ACP `loadSession`, so persisted session ids resume.\n *\n * @module provider/Drivers/QwenDriver\n */\nimport { QwenSettings } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nimport { QwenAcpAgent } from \"../acp/QwenAcpAgent.ts\";\nimport { makeAcpAgentDriver, type AcpAgentDriverEnv } from \"./makeAcpAgentDriver.ts\";\n\nconst decodeQwenSettings = Schema.decodeSync(QwenSettings);\n\nexport type QwenDriverEnv = AcpAgentDriverEnv;\n\nexport const QwenDriver = makeAcpAgentDriver({\n  driver: {\n    descriptor: QwenAcpAgent,\n    npmPackageName: \"@qwen-code/qwen-code\",\n  },\n  configSchema: QwenSettings,\n  defaultConfig: (): QwenSettings => decodeQwenSettings({}),\n});\n","/**\n * BUILT_IN_DRIVERS — the static set of `ProviderDriver`s this build ships\n * with.\n *\n * Every driver that the server knows how to instantiate from settings is\n * listed here. The `ProviderInstanceRegistry` iterates this array when\n * resolving `providerInstances` entries; anything not in the array surfaces\n * as an `\"unavailable\"` shadow snapshot at runtime (see\n * `buildUnavailableProviderSnapshot`).\n *\n * Adding a new first-party driver means:\n *   1. implement `ProviderDriver` in a sibling `Drivers/<Name>Driver.ts`,\n *   2. add it to this array,\n *   3. ensure the runtime layer satisfies its declared `R`.\n *\n * The aggregated `BuiltInDriversEnv` type is the union of every driver's\n * env requirement — the registry layer's `R` is this type, and the runtime\n * layer (ChildProcessSpawner, FileSystem, Path, ServerConfig, …) must\n * satisfy it.\n *\n * agentlink fork: Cursor/Grok/OpenCode drivers were removed; ACP-based\n * drivers (Gemini/Qwen/Kimi/JoyCode) land here on top of `acp/AcpSessionRuntime.ts`.\n *\n * @module provider/builtInDrivers\n */\nimport { ClaudeDriver, type ClaudeDriverEnv } from \"./Drivers/ClaudeDriver.ts\";\nimport { CodexDriver, type CodexDriverEnv } from \"./Drivers/CodexDriver.ts\";\nimport { GeminiDriver, type GeminiDriverEnv } from \"./Drivers/GeminiDriver.ts\";\nimport { JoyCodeDriver, type JoyCodeDriverEnv } from \"./Drivers/JoyCodeDriver.ts\";\nimport { KimiDriver, type KimiDriverEnv } from \"./Drivers/KimiDriver.ts\";\nimport { QwenDriver, type QwenDriverEnv } from \"./Drivers/QwenDriver.ts\";\nimport type { AnyProviderDriver } from \"./ProviderDriver.ts\";\n\n/**\n * Union of infrastructure services required to construct any built-in\n * driver. The registry layer declares `R = BuiltInDriversEnv`; the runtime\n * layer must provide every service in this union.\n */\nexport type BuiltInDriversEnv =\n  | ClaudeDriverEnv\n  | CodexDriverEnv\n  | GeminiDriverEnv\n  | JoyCodeDriverEnv\n  | QwenDriverEnv\n  | KimiDriverEnv;\n\n/**\n * Ordered list of built-in drivers. Order matters only for tie-breaking in\n * UI presentation — the registry itself is keyed by `driverKind`, so\n * iteration order has no functional effect on instance lookup.\n */\nexport const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv>> = [\n  CodexDriver,\n  ClaudeDriver,\n  GeminiDriver,\n  QwenDriver,\n  KimiDriver,\n  JoyCodeDriver,\n];\n","/**\n * ProviderInstanceRegistryMutator — internal handle used by the hydration\n * layer to reconcile the live registry with a fresh\n * `ProviderInstanceConfigMap`.\n *\n * Kept separate from the public `ProviderInstanceRegistry` service tag so\n * downstream consumers (drivers, reactors, `ProviderService`) can only read\n * from the registry. Only the hydration layer — which watches\n * `ServerSettingsService.streamChanges` and applies diffs — imports this\n * tag.\n *\n * The mutator exposes a single entry point, `reconcile(configMap)`, which:\n *\n *   1. Diffs the incoming map against the live one keyed by instance id.\n *   2. Closes the per-instance `Scope` of every removed or replaced entry\n *      (tearing down adapter processes, refresh fibres, temp files) BEFORE\n *      creating the replacement — `reconcile` guarantees \"at most one live\n *      instance per id\" at all times.\n *   3. Opens a fresh child `Scope` for every added or replaced entry, runs\n *      the driver's `create`, and stores the resulting `ProviderInstance`\n *      plus its scope.\n *   4. Publishes one `void` tick on the registry's `streamChanges` PubSub at\n *      the end of the batch — consumers re-pull `listInstances` /\n *      `listUnavailable`.\n *\n * `reconcile` is idempotent: calling it with an unchanged config map is a\n * no-op (no scope churn, no pubsub emission).\n *\n * @module provider/Services/ProviderInstanceRegistryMutator\n */\nimport type { ProviderInstanceConfigMap } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nexport interface ProviderInstanceRegistryMutatorShape {\n  /**\n   * Bring the live registry in line with the supplied config map. See\n   * module docs for the add / remove / replace semantics.\n   *\n   * The effect never fails: individual driver `create` failures are\n   * captured as \"unavailable\" shadow snapshots inside the registry, the\n   * same way boot-time failures are handled by\n   * `makeProviderInstanceRegistry`. This keeps settings-watcher loops from\n   * erroring out on a single bad entry.\n   */\n  readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;\n}\n\nexport class ProviderInstanceRegistryMutator extends Context.Service<\n  ProviderInstanceRegistryMutator,\n  ProviderInstanceRegistryMutatorShape\n>()(\"t3/provider/Services/ProviderInstanceRegistryMutator\") {}\n","/**\n * Helpers for synthesizing \"unavailable\" `ServerProvider` snapshots.\n *\n * When `ServerSettings.providerInstances` (or persisted thread/session\n * state) references a driver this build does not ship — typical after a\n * downgrade from a fork or a feature-branch test session — the runtime\n * needs to surface the entry to the UI without crashing. This module\n * produces shadow snapshots that satisfy `ServerProvider`'s wire shape\n * while signalling unavailability.\n *\n * @module unavailableProviderSnapshot\n */\nimport {\n  ProviderDriverKind,\n  type ProviderInstanceId,\n  type ServerProvider,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\n\nimport { buildServerProvider } from \"./providerSnapshot.ts\";\n\nexport interface UnavailableProviderSnapshotInput {\n  readonly driverKind: ProviderDriverKind | string;\n  readonly instanceId: ProviderInstanceId;\n  readonly displayName?: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly reason: string;\n  /**\n   * Optional override for `checkedAt`. Defaulted to the current Effect\n   * `DateTime` so callers\n   * (notably tests) don't have to pass it.\n   */\n  readonly checkedAt?: string;\n}\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\n/**\n * Produce a `ServerProvider` snapshot representing a configured instance\n * whose driver the running build does not implement. The result is safe\n * to broadcast over the wire and is structured so the web UI can render\n * a \"missing driver\" affordance without special-casing.\n */\nexport function buildUnavailableProviderSnapshot(\n  input: UnavailableProviderSnapshotInput,\n): Effect.Effect<ServerProvider> {\n  return Effect.gen(function* () {\n    const checkedAt = input.checkedAt ?? (yield* nowIso);\n    const displayName = input.displayName?.trim() || (input.driverKind as string);\n\n    const base = buildServerProvider({\n      presentation: { displayName },\n      enabled: false,\n      checkedAt,\n      models: [],\n      skills: [],\n      probe: {\n        installed: false,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: input.reason,\n      },\n    });\n\n    return {\n      ...base,\n      instanceId: input.instanceId,\n      ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n      driver:\n        typeof input.driverKind === \"string\"\n          ? ProviderDriverKind.make(input.driverKind)\n          : input.driverKind,\n      availability: \"unavailable\",\n      unavailableReason: input.reason,\n    };\n  });\n}\n","/**\n * ProviderInstanceRegistryLive — runtime implementation of\n * `ProviderInstanceRegistry` plus its sibling mutator.\n *\n * Materializes every entry in a `ProviderInstanceConfigMap`:\n *\n *   - When the entry's `driver` matches a registered driver, the registry\n *     decodes the opaque `config` envelope through `driver.configSchema`\n *     and calls `driver.create()` inside a fresh child scope. The\n *     resulting `ProviderInstance` is stored keyed by instance id,\n *     alongside its scope so the entry can be torn down independently.\n *   - When the entry's `driver` is unknown to this build (fork, rollback,\n *     in-flight PR branch), the registry emits an `\"unavailable\"` shadow\n *     `ServerProvider` snapshot instead of failing. This is what makes\n *     downgrades and fork-hopping safe per the\n *     `forward/backward compatibility invariant` in\n *     `packages/contracts/src/providerInstance.ts`.\n *   - When the entry's config fails schema decode, the registry logs and\n *     emits a shadow snapshot with the schema detail — same bucket as an\n *     unknown driver.\n *\n * Unlike the pre-Slice-D layer, the registry now holds mutable state\n * (`Ref`s + `PubSub`) and exposes an internal mutator\n * (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a\n * fresh config map against the live state, tearing down removed instances\n * and building new ones without disturbing unaffected instances.\n *\n * Every live instance runs inside its own child `Scope`. The registry's\n * own scope owns all child scopes via finalizers, so closing the registry\n * tears every instance down in reverse order; closing a single instance\n * (via `reconcile` removing it) leaves the rest untouched.\n *\n * @module provider/Layers/ProviderInstanceRegistryLive\n */\nimport {\n  defaultInstanceIdForDriver,\n  ProviderInstanceId,\n  type ProviderInstanceConfig,\n  type ProviderInstanceConfigMap,\n  type ProviderDriverKind,\n  type ServerProvider,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { buildUnavailableProviderSnapshot } from \"../unavailableProviderSnapshot.ts\";\nimport {\n  ProviderInstanceRegistry,\n  type ProviderInstanceRegistryShape,\n} from \"../Services/ProviderInstanceRegistry.ts\";\nimport {\n  ProviderInstanceRegistryMutator,\n  type ProviderInstanceRegistryMutatorShape,\n} from \"../Services/ProviderInstanceRegistryMutator.ts\";\nimport type { AnyProviderDriver, ProviderInstance } from \"../ProviderDriver.ts\";\n\n/**\n * Live registry entry: the materialized `ProviderInstance` + the fresh\n * child scope its `create` effect ran in + the original `entry` envelope\n * so `reconcile` can cheaply detect \"no-op\" updates.\n */\ninterface LiveEntry {\n  readonly instance: ProviderInstance;\n  readonly scope: Scope.Closeable;\n  readonly entry: ProviderInstanceConfig;\n}\n\n/**\n * Internal state shared between the public registry service and the\n * mutator service. Both services are thin shells around these refs.\n */\ninterface RegistryState {\n  readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;\n  readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;\n  readonly changes: PubSub.PubSub<void>;\n}\n\n/**\n * Structural equality on `ProviderInstanceConfig` envelopes. Used by\n * `reconcile` to skip rebuilds when settings arrive unchanged. Config\n * payloads are opaque `unknown` at the envelope layer; `Equal.equals`\n * falls back to structural equality for plain records, which matches how\n * the schema decode output is constructed.\n */\nconst entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>\n  Equal.equals(a, b);\n\nconst decodedConfigEnabled = (config: unknown): boolean | undefined => {\n  if (!config || typeof config !== \"object\" || globalThis.Array.isArray(config)) {\n    return undefined;\n  }\n  const enabled = (config as { readonly enabled?: unknown }).enabled;\n  return typeof enabled === \"boolean\" ? enabled : undefined;\n};\n\n/**\n * Build one live entry from a raw config envelope. Returns either a\n * `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and\n * undefined entry — callers dispatch to the appropriate Ref bucket.\n */\nconst buildEntry = <R>(input: {\n  readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;\n  readonly parentScope: Scope.Scope;\n  readonly instanceId: ProviderInstanceId;\n  readonly rawInstanceId: string;\n  readonly entry: ProviderInstanceConfig;\n}): Effect.Effect<\n  | { readonly kind: \"live\"; readonly live: LiveEntry }\n  | { readonly kind: \"unavailable\"; readonly snapshot: ServerProvider },\n  never,\n  R\n> =>\n  Effect.gen(function* () {\n    const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;\n    const driver = driversById.get(entry.driver);\n    if (!driver) {\n      return {\n        kind: \"unavailable\" as const,\n        snapshot: yield* buildUnavailableProviderSnapshot({\n          driverKind: entry.driver,\n          instanceId,\n          displayName: entry.displayName,\n          accentColor: entry.accentColor,\n          reason: `Driver '${entry.driver}' is not registered in this build.`,\n        }),\n      };\n    }\n\n    const decoder = Schema.decodeUnknownEffect(driver.configSchema);\n    const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);\n    if (decodeResult._tag === \"Failure\") {\n      const issue = decodeResult.failure;\n      const detail = issue.message ?? String(issue);\n      yield* Effect.logError(\"Failed to decode provider instance config\", {\n        instanceId: rawInstanceId,\n        driver: entry.driver,\n        detail,\n      });\n      return {\n        kind: \"unavailable\" as const,\n        snapshot: yield* buildUnavailableProviderSnapshot({\n          driverKind: entry.driver,\n          instanceId,\n          displayName: entry.displayName,\n          accentColor: entry.accentColor,\n          reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,\n        }),\n      };\n    }\n\n    const typedConfig = decodeResult.success;\n    const childScope = yield* Scope.make();\n    // Attach the child scope to the registry's parent scope: if the\n    // registry scope closes, each surviving instance's child scope is\n    // closed through this finalizer. `reconcile` manually closes the\n    // child scope on remove/replace; subsequent close via the parent's\n    // finalizer is a no-op because `Scope.close` is idempotent.\n    yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));\n\n    const createResult = yield* driver\n      .create({\n        instanceId,\n        displayName: entry.displayName,\n        accentColor: entry.accentColor,\n        environment: entry.environment ?? [],\n        enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,\n        config: typedConfig,\n      })\n      .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);\n    if (createResult._tag === \"Failure\") {\n      yield* Effect.logError(\"Failed to create provider instance\", {\n        instanceId: rawInstanceId,\n        driver: entry.driver,\n        detail: createResult.failure.detail,\n      });\n      yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);\n      return {\n        kind: \"unavailable\" as const,\n        snapshot: yield* buildUnavailableProviderSnapshot({\n          driverKind: entry.driver,\n          instanceId,\n          displayName: entry.displayName,\n          accentColor: entry.accentColor,\n          reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,\n        }),\n      };\n    }\n\n    return {\n      kind: \"live\" as const,\n      live: {\n        instance: createResult.success,\n        scope: childScope,\n        entry,\n      },\n    };\n  });\n\n/**\n * Reconcile-only implementation of the mutator. Exposed to the hydration\n * layer; never called directly by the rest of the server.\n */\nconst makeReconcile = <R>(input: {\n  readonly state: RegistryState;\n  readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;\n  readonly parentScope: Scope.Scope;\n}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {\n  const { state, driversById, parentScope } = input;\n  return (configMap: ProviderInstanceConfigMap) =>\n    Effect.gen(function* () {\n      const previousEntries = yield* Ref.get(state.entries);\n      const previousUnavailable = yield* Ref.get(state.unavailable);\n      const nextRaw = Object.entries(configMap);\n      const nextKeys = new Set<ProviderInstanceId>(\n        nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),\n      );\n\n      // 1. Close scopes for instances that disappeared or whose config\n      //    changed. Do this BEFORE creating replacements so ids map 1-to-1\n      //    to live scopes at all times.\n      const removedIds: Array<ProviderInstanceId> = [];\n      const replacedIds = new Set<ProviderInstanceId>();\n      for (const [instanceId, live] of previousEntries) {\n        if (!nextKeys.has(instanceId)) {\n          removedIds.push(instanceId);\n          continue;\n        }\n        const nextEntry = configMap[instanceId];\n        if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {\n          replacedIds.add(instanceId);\n        }\n      }\n      for (const id of [...removedIds, ...replacedIds]) {\n        const live = previousEntries.get(id);\n        if (live) {\n          yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);\n        }\n      }\n\n      // 2. Build additions and replacements. Walk `nextRaw` so the final\n      //    entry order follows settings-author order.\n      const builtEntries = new Map<ProviderInstanceId, LiveEntry>();\n      const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();\n      let orderChanged = false;\n      const previousOrder = [...previousEntries.keys()];\n      const nextOrder: Array<ProviderInstanceId> = [];\n\n      for (const [rawInstanceId, entry] of nextRaw) {\n        const instanceId = ProviderInstanceId.make(rawInstanceId);\n        nextOrder.push(instanceId);\n\n        const existing = previousEntries.get(instanceId);\n        if (existing !== undefined && !replacedIds.has(instanceId)) {\n          // No-op update: keep the existing live entry and scope.\n          builtEntries.set(instanceId, existing);\n          continue;\n        }\n\n        const result = yield* buildEntry({\n          driversById,\n          parentScope,\n          instanceId,\n          rawInstanceId,\n          entry,\n        });\n        if (result.kind === \"live\") {\n          builtEntries.set(instanceId, result.live);\n        } else {\n          builtUnavailable.set(instanceId, result.snapshot);\n        }\n      }\n\n      if (previousOrder.length === nextOrder.length) {\n        for (let i = 0; i < previousOrder.length; i++) {\n          if (previousOrder[i] !== nextOrder[i]) {\n            orderChanged = true;\n            break;\n          }\n        }\n      } else {\n        orderChanged = true;\n      }\n\n      const entriesChanged =\n        orderChanged ||\n        removedIds.length > 0 ||\n        replacedIds.size > 0 ||\n        builtEntries.size !== previousEntries.size;\n      const unavailableChanged =\n        builtUnavailable.size !== previousUnavailable.size ||\n        [...builtUnavailable].some(([id, snapshot]) => {\n          const prev = previousUnavailable.get(id);\n          return prev === undefined || !Equal.equals(prev, snapshot);\n        }) ||\n        [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));\n\n      yield* Ref.set(state.entries, builtEntries);\n      yield* Ref.set(state.unavailable, builtUnavailable);\n\n      if (entriesChanged || unavailableChanged) {\n        yield* PubSub.publish(state.changes, undefined);\n      }\n    });\n};\n\n/**\n * Build the registry's runtime state from a concrete configMap. Returns a\n * record containing:\n *\n *   - `registry`: the read-only `ProviderInstanceRegistryShape` to expose\n *     under `ProviderInstanceRegistry`.\n *   - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose\n *     under `ProviderInstanceRegistryMutator`.\n *   - `reconcile`: the raw reconcile function, provided for convenience so\n *     boot-time layers can hydrate an initial map before publishing the\n *     services.\n *\n * The scope that this effect runs in owns every per-instance child scope\n * created during `reconcile`. Closing that scope closes every live\n * instance.\n */\nexport const makeProviderInstanceRegistry = <R>(input: {\n  readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n  readonly configMap: ProviderInstanceConfigMap;\n}): Effect.Effect<\n  {\n    readonly registry: ProviderInstanceRegistryShape;\n    readonly mutator: ProviderInstanceRegistryMutatorShape;\n  },\n  never,\n  R | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(\n      input.drivers.map((driver) => [driver.driverKind, driver]),\n    );\n\n    // Capture the enclosing scope so per-instance child scopes can be\n    // attached to it at `reconcile` time. Without this, `reconcile`\n    // called later (e.g. from the hydration layer) would attach child\n    // scopes to the *caller's* scope instead of the registry's.\n    const parentScope = yield* Scope.Scope;\n\n    // Capture the driver R context at construction time so `reconcile`\n    // can be invoked later without re-providing driver dependencies.\n    // The service tag's declared `reconcile: Effect<void>` hides R from\n    // consumers — we materialize that here.\n    const driverContext = yield* Effect.context<R>();\n\n    const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());\n    const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());\n    const changes = yield* PubSub.unbounded<void>();\n    yield* Effect.addFinalizer(() => PubSub.shutdown(changes));\n\n    const state: RegistryState = { entries, unavailable, changes };\n    const reconcileWithR = makeReconcile({ state, driversById, parentScope });\n    const reconcile: ProviderInstanceRegistryMutatorShape[\"reconcile\"] = (configMap) =>\n      reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));\n\n    // Hydrate the initial configMap synchronously so callers can read\n    // `listInstances` immediately after this effect completes.\n    yield* reconcile(input.configMap);\n\n    const registry: ProviderInstanceRegistryShape = {\n      getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),\n      listInstances: Ref.get(entries).pipe(\n        Effect.map(\n          (map) =>\n            Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,\n        ),\n      ),\n      listUnavailable: Ref.get(unavailable).pipe(\n        Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),\n      ),\n      // Getters: each read constructs a fresh Stream / Effect descriptor\n      // so multiple consumers don't share a single already-started\n      // Channel or subscription. Matches the pattern `ProviderRegistry`\n      // uses for its own `streamChanges`.\n      get streamChanges() {\n        return Stream.fromPubSub(changes);\n      },\n      // Synchronous subscribe — callers that need to consume changes\n      // from a forked fibre must acquire the subscription in their own\n      // fibre first (via `yield* registry.subscribeChanges`) and only\n      // then fork a consumer loop on `Stream.fromSubscription(...)` /\n      // `PubSub.take(...)`. See the shape docs for the race this avoids.\n      get subscribeChanges() {\n        return PubSub.subscribe(changes);\n      },\n    };\n\n    const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };\n\n    return { registry, mutator };\n  });\n\n/**\n * Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of\n * drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests\n * that want explicit control over the registry's source-of-truth without\n * wiring up the settings watcher.\n *\n * Only exposes the public registry tag — hot-reload consumers should use\n * `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.\n */\nexport const ProviderInstanceRegistryLayer = <R>(input: {\n  readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n  readonly configMap: ProviderInstanceConfigMap;\n}): Layer.Layer<ProviderInstanceRegistry, never, R> =>\n  Layer.effect(\n    ProviderInstanceRegistry,\n    makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),\n  ) as Layer.Layer<ProviderInstanceRegistry, never, R>;\n\n/**\n * Layer variant that also exposes the mutator tag. Consumed by\n * `ProviderInstanceRegistryHydrationLive` to reconcile on settings\n * changes. Tests that exercise the mutator directly can pair this Layer\n * with a test-local `ServerSettingsService`.\n */\nexport const ProviderInstanceRegistryMutableLayer = <R>(input: {\n  readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n  readonly configMap: ProviderInstanceConfigMap;\n}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>\n  Layer.effectContext(\n    makeProviderInstanceRegistry(input).pipe(\n      Effect.map(({ registry, mutator }) =>\n        Context.make(ProviderInstanceRegistry, registry).pipe(\n          Context.add(ProviderInstanceRegistryMutator, mutator),\n        ),\n      ),\n    ),\n  ) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;\n\nexport { defaultInstanceIdForDriver };\n","/**\n * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`\n * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.\n *\n * The server still reads two shapes:\n *\n *   1. `settings.providerInstances` — the new driver-agnostic map the\n *      registry expects. Keyed by `ProviderInstanceId`, values are\n *      `ProviderInstanceConfig` envelopes.\n *   2. `settings.providers.<kind>` — the legacy single-instance-per-driver\n *      fields (`providers.codex`, `providers.claudeAgent`, …). These are\n *      the source of truth for every deployment that hasn't been migrated\n *      yet to an explicit `providerInstances` entry.\n *\n * This module bridges (2) into (1) and wires the resulting map into a\n * mutable registry. For every built-in driver whose id is not already\n * present in `providerInstances` (keyed on\n * `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a\n * routing slug), we synthesize an envelope from the legacy field. The\n * registry decodes both flavours through the same `configSchema` and ends\n * up with one uniform `ProviderInstance` per entry.\n *\n * Explicit `providerInstances` entries always win — users can already\n * override the legacy `providers.<kind>` blob by authoring a\n * `providerInstances.codex` entry with a matching driver, and we don't\n * want the synthesized envelope to silently stomp their config.\n *\n * Hot-reload\n * ----------\n * On layer build we:\n *   1. Read the current `ServerSettings` once and use it to seed the\n *      registry's initial state via `ProviderInstanceRegistryMutableLayer`.\n *   2. Fork a daemon fiber (lifetime tied to the layer's scope) that\n *      subscribes to `ServerSettingsService.streamChanges` and calls\n *      `ProviderInstanceRegistryMutator.reconcile` on every emission.\n *\n * Failures inside the watcher are logged and swallowed so a single bad\n * settings emission cannot kill the registry. Unknown drivers and invalid\n * configs already round-trip through the registry's own \"unavailable\"\n * shadow bucket.\n *\n * @module provider/Layers/ProviderInstanceRegistryHydration\n */\nimport {\n  defaultInstanceIdForDriver,\n  type ProviderInstanceConfig,\n  type ProviderInstanceConfigMap,\n  ServerSettings,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Stream from \"effect/Stream\";\n\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from \"../builtInDrivers.ts\";\nimport { ProviderInstanceRegistry } from \"../Services/ProviderInstanceRegistry.ts\";\nimport { ProviderInstanceRegistryMutator } from \"../Services/ProviderInstanceRegistryMutator.ts\";\nimport { ProviderInstanceRegistryMutableLayer } from \"./ProviderInstanceRegistryLive.ts\";\n\n/**\n * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.\n *\n * Strategy:\n *   1. Copy all explicit `settings.providerInstances` entries verbatim.\n *   2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key\n *      is *not* already in the explicit map, synthesize an entry from the\n *      matching legacy `settings.providers.<kind>` blob.\n *\n * The returned map is the input the registry consumes; pure & exported\n * separately so the hydration logic can be exercised by unit tests\n * without layering.\n */\nexport const deriveProviderInstanceConfigMap = (\n  settings: ServerSettings,\n): ProviderInstanceConfigMap => {\n  const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };\n\n  for (const driver of BUILT_IN_DRIVERS) {\n    const instanceId = defaultInstanceIdForDriver(driver.driverKind);\n    if (instanceId in merged) {\n      // Explicit `providerInstances` entry for this slot — user-authored\n      // config always wins over the legacy mirror.\n      continue;\n    }\n\n    // Only built-in drivers have a legacy mirror; the registry's\n    // `providers` struct is keyed on the same literal slug as\n    // `driverKind`. Access is dynamic (the driver kind is a branded string),\n    // but it's constrained to `keyof settings.providers` by the union of\n    // built-in driver kinds.\n    const legacyKey = driver.driverKind as keyof ServerSettings[\"providers\"];\n    const legacyConfig = settings.providers[legacyKey];\n    if (legacyConfig === undefined) {\n      continue;\n    }\n\n    merged[instanceId] = {\n      driver: driver.driverKind,\n      config: legacyConfig,\n    };\n  }\n\n  return merged as ProviderInstanceConfigMap;\n};\n\n/**\n * Layer that consumes `ProviderInstanceRegistryMutator` and forks a\n * settings-watcher fiber. The fiber's lifetime is tied to the enclosing\n * layer scope (process lifetime in production), so it is interrupted on\n * shutdown without leaking.\n *\n * Errors inside the watcher are logged and swallowed — the registry's own\n * \"unavailable\" bucket already absorbs unknown drivers and invalid\n * configs, so the only way the watcher could fail is a settings stream\n * tear-down, which logs and exits cleanly.\n */\nconst SettingsWatcherLive = Layer.effectDiscard(\n  Effect.gen(function* () {\n    const mutator = yield* ProviderInstanceRegistryMutator;\n    const serverSettings = yield* ServerSettingsService;\n    yield* serverSettings.streamChanges.pipe(\n      Stream.runForEach((next) =>\n        mutator\n          .reconcile(deriveProviderInstanceConfigMap(next))\n          .pipe(\n            Effect.catchCause((cause) =>\n              Effect.logError(\"ProviderInstanceRegistry reconcile failed\", cause),\n            ),\n          ),\n      ),\n      Effect.forkScoped,\n    );\n  }),\n);\n\n/**\n * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in\n * sync with subsequent `streamChanges` emissions.\n *\n * The Layer's two halves:\n *   - `ProviderInstanceRegistryMutableLayer` produces the registry +\n *     mutator from the initial config map. Its scope owns every\n *     per-instance child scope created during reconcile.\n *   - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber\n *     in the same scope.\n *\n * Composing via `Layer.provideMerge` makes the watcher's deps available\n * from the mutable layer while still surfacing the registry as an output.\n * The mutator tag is technically also exposed; only this module imports\n * it, so the visibility leak is harmless in practice.\n */\nexport const ProviderInstanceRegistryHydrationLive: Layer.Layer<\n  ProviderInstanceRegistry,\n  never,\n  BuiltInDriversEnv | ServerSettingsService\n> = Layer.unwrap(\n  Effect.gen(function* () {\n    const serverSettings = yield* ServerSettingsService;\n    const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(\n      Effect.orElseSucceed(() => undefined),\n    );\n    const initialConfigMap =\n      initialSettings === undefined\n        ? ({} as ProviderInstanceConfigMap)\n        : deriveProviderInstanceConfigMap(initialSettings);\n\n    const mutableLayer = ProviderInstanceRegistryMutableLayer({\n      drivers: BUILT_IN_DRIVERS,\n      configMap: initialConfigMap,\n    });\n\n    return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));\n  }),\n) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;\n","/**\n * ProviderCommandReactor - Provider command reaction service interface.\n *\n * Owns background workers that react to orchestration intent events and\n * dispatch provider-side command execution.\n *\n * @module ProviderCommandReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * ProviderCommandReactorShape - Service API for provider command reactors.\n */\nexport interface ProviderCommandReactorShape {\n  /**\n   * Start reacting to provider-intent orchestration domain events.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   *\n   * Filters orchestration domain events to provider-intent types before\n   * processing.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * ProviderCommandReactor - Service tag for provider command reaction workers.\n */\nexport class ProviderCommandReactor extends Context.Service<\n  ProviderCommandReactor,\n  ProviderCommandReactorShape\n>()(\"t3/orchestration/Services/ProviderCommandReactor\") {}\n","/**\n * ThreadDeletionReactor - Thread deletion cleanup reactor service interface.\n *\n * Owns background workers that react to thread deletion domain events and\n * perform best-effort runtime cleanup for provider sessions and terminals.\n *\n * @module ThreadDeletionReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * ThreadDeletionReactorShape - Service API for thread deletion cleanup.\n */\nexport interface ThreadDeletionReactorShape {\n  /**\n   * Start reacting to thread.deleted orchestration domain events.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * ThreadDeletionReactor - Service tag for thread deletion cleanup workers.\n */\nexport class ThreadDeletionReactor extends Context.Service<\n  ThreadDeletionReactor,\n  ThreadDeletionReactorShape\n>()(\"t3/orchestration/Services/ThreadDeletionReactor\") {}\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport {\n  OrchestrationReactor,\n  type OrchestrationReactorShape,\n} from \"../Services/OrchestrationReactor.ts\";\nimport { ProviderCommandReactor } from \"../Services/ProviderCommandReactor.ts\";\nimport { ProviderRuntimeIngestionService } from \"../Services/ProviderRuntimeIngestion.ts\";\nimport { ThreadDeletionReactor } from \"../Services/ThreadDeletionReactor.ts\";\n\nexport const makeOrchestrationReactor = Effect.gen(function* () {\n  const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;\n  const providerCommandReactor = yield* ProviderCommandReactor;\n  const threadDeletionReactor = yield* ThreadDeletionReactor;\n\n  const start: OrchestrationReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    yield* providerRuntimeIngestion.start();\n    yield* providerCommandReactor.start();\n    yield* threadDeletionReactor.start();\n  });\n\n  return {\n    start,\n  } satisfies OrchestrationReactorShape;\n});\n\nexport const OrchestrationReactorLive = Layer.effect(\n  OrchestrationReactor,\n  makeOrchestrationReactor,\n);\n","/**\n * RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts.\n *\n * This service exists to expose short-lived orchestration milestones that are\n * useful in tests and harnesses but are not part of the production runtime\n * event model. `CheckpointReactor` publishes receipts such as baseline capture,\n * diff finalization, and turn-processing quiescence so integration tests can\n * wait for those exact points without inferring them indirectly from persisted\n * state.\n *\n * Production code should only call `publish`. Test code may subscribe via\n * `streamEventsForTest`, which is intentionally named to make the intended\n * usage explicit.\n *\n * @module RuntimeReceiptBus\n */\nimport { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nexport const CheckpointBaselineCapturedReceipt = Schema.Struct({\n  type: Schema.Literal(\"checkpoint.baseline.captured\"),\n  threadId: ThreadId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  createdAt: IsoDateTime,\n});\nexport type CheckpointBaselineCapturedReceipt = typeof CheckpointBaselineCapturedReceipt.Type;\n\nexport const CheckpointDiffFinalizedReceipt = Schema.Struct({\n  type: Schema.Literal(\"checkpoint.diff.finalized\"),\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: Schema.Literals([\"ready\", \"missing\", \"error\"]),\n  createdAt: IsoDateTime,\n});\nexport type CheckpointDiffFinalizedReceipt = typeof CheckpointDiffFinalizedReceipt.Type;\n\nexport const TurnProcessingQuiescedReceipt = Schema.Struct({\n  type: Schema.Literal(\"turn.processing.quiesced\"),\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\nexport type TurnProcessingQuiescedReceipt = typeof TurnProcessingQuiescedReceipt.Type;\n\nexport const OrchestrationRuntimeReceipt = Schema.Union([\n  CheckpointBaselineCapturedReceipt,\n  CheckpointDiffFinalizedReceipt,\n  TurnProcessingQuiescedReceipt,\n]);\nexport type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Type;\n\nexport interface RuntimeReceiptBusShape {\n  readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;\n  readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;\n}\n\nexport class RuntimeReceiptBus extends Context.Service<RuntimeReceiptBus, RuntimeReceiptBusShape>()(\n  \"t3/orchestration/Services/RuntimeReceiptBus\",\n) {}\n","/**\n * RuntimeReceiptBus layers.\n *\n * `RuntimeReceiptBusLive` is the production default and intentionally does not\n * retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory\n * PubSub-backed implementation used by integration tests that need to await\n * checkpoint-reactor milestones precisely.\n *\n * @module RuntimeReceiptBus\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n  RuntimeReceiptBus,\n  type RuntimeReceiptBusShape,\n  type OrchestrationRuntimeReceipt,\n} from \"../Services/RuntimeReceiptBus.ts\";\n\nconst makeRuntimeReceiptBus = Effect.succeed({\n  publish: () => Effect.void,\n  streamEventsForTest: Stream.empty,\n} satisfies RuntimeReceiptBusShape);\n\nconst makeRuntimeReceiptBusTest = Effect.gen(function* () {\n  const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();\n\n  return {\n    publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),\n    get streamEventsForTest() {\n      return Stream.fromPubSub(pubSub);\n    },\n  } satisfies RuntimeReceiptBusShape;\n});\n\nexport const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);\nexport const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest);\n","import {\n  ApprovalRequestId,\n  type AssistantDeliveryMode,\n  CommandId,\n  MessageId,\n  type OrchestrationEvent,\n  type OrchestrationMessage,\n  type OrchestrationProposedPlanId,\n  classifyTaskAgentKind,\n  EventId,\n  isToolLifecycleItemType,\n  ProviderDriverKind,\n  ThreadId,\n  type ThreadTokenUsageSnapshot,\n  TurnId,\n  type OrchestrationProposedPlan,\n  type OrchestrationThread,\n  type OrchestrationThreadActivity,\n  type ProviderRuntimeEvent,\n} from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\n\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport { ProjectionTurnRepository } from \"../../persistence/Services/ProjectionTurns.ts\";\nimport { ProjectionTurnRepositoryLive } from \"../../persistence/Layers/ProjectionTurns.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport { ThreadBackgroundLivenessService } from \"../ThreadBackgroundLiveness.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport {\n  ProviderRuntimeReconciliationError,\n  ProviderRuntimeIngestionService,\n  type ProviderRuntimeIngestionShape,\n} from \"../Services/ProviderRuntimeIngestion.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\n\nconst providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;\nconst providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;\n\nfunction providerReconciliationFailureDetail(cause: unknown): string {\n  return cause instanceof Error && cause.message.toLowerCase().includes(\"active writer\")\n    ? \"对话正在另一端运行，请等待另一端结束后再继续。\"\n    : cause instanceof Error\n      ? cause.message\n      : \"Provider snapshot sync failed.\";\n}\n\n// Fallback when the in-memory description cache no longer has the task name\n// (server restart, session-exit sweep, TTL/capacity eviction): earlier\n// task.started/task.progress activities for the task are persisted with it.\nfunction findTaskTitleInActivities(\n  activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,\n  taskId: string,\n): string | undefined {\n  if (!activities) {\n    return undefined;\n  }\n  for (let index = activities.length - 1; index >= 0; index -= 1) {\n    const activity = activities[index];\n    if (!activity || (activity.kind !== \"task.started\" && activity.kind !== \"task.progress\")) {\n      continue;\n    }\n    const payload =\n      activity.payload && typeof activity.payload === \"object\"\n        ? (activity.payload as { taskId?: unknown; title?: unknown; detail?: unknown })\n        : undefined;\n    if (payload?.taskId !== taskId) {\n      continue;\n    }\n    const title =\n      typeof payload.title === \"string\"\n        ? payload.title\n        : activity.kind === \"task.started\" && typeof payload.detail === \"string\"\n          ? payload.detail\n          : undefined;\n    if (title && title.trim().length > 0) {\n      return title;\n    }\n  }\n  return undefined;\n}\n\ninterface AssistantSegmentState {\n  baseKey: string;\n  nextSegmentIndex: number;\n  activeMessageId: MessageId | null;\n}\n\nconst TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;\nconst TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);\nconst BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;\nconst BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);\nconst BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY = 10_000;\nconst BUFFERED_PROPOSED_PLAN_BY_ID_TTL = Duration.minutes(120);\nconst TASK_DESCRIPTION_BY_TASK_CACHE_CAPACITY = 10_000;\nconst TASK_DESCRIPTION_BY_TASK_TTL = Duration.minutes(120);\nconst MAX_BUFFERED_ASSISTANT_CHARS = 24_000;\nconst STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== \"0\";\n\ntype TurnStartRequestedDomainEvent = Extract<\n  OrchestrationEvent,\n  { type: \"thread.turn-start-requested\" }\n>;\n\ntype RuntimeIngestionInput =\n  | {\n      source: \"runtime\";\n      event: ProviderRuntimeEvent;\n    }\n  | {\n      source: \"domain\";\n      event: TurnStartRequestedDomainEvent;\n    };\n\nfunction toTurnId(value: TurnId | string | undefined): TurnId | undefined {\n  return value === undefined ? undefined : TurnId.make(String(value));\n}\n\nfunction toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {\n  return value === undefined ? undefined : ApprovalRequestId.make(value);\n}\n\nfunction sameId(left: string | null | undefined, right: string | null | undefined): boolean {\n  if (left === null || left === undefined || right === null || right === undefined) {\n    return false;\n  }\n  return left === right;\n}\n\nfunction hasAssistantMessageForTurn(\n  messages: ReadonlyArray<OrchestrationMessage>,\n  turnId: TurnId,\n  options?: { readonly streamingOnly?: boolean },\n): boolean {\n  for (let index = 0; index < messages.length; index += 1) {\n    const message = messages[index];\n    if (!message) {\n      continue;\n    }\n    if (message.role !== \"assistant\" || message.turnId !== turnId) {\n      continue;\n    }\n    if (options?.streamingOnly === true && !message.streaming) {\n      continue;\n    }\n    return true;\n  }\n  return false;\n}\n\nfunction findMessageById(\n  messages: ReadonlyArray<OrchestrationMessage>,\n  messageId: MessageId,\n): OrchestrationMessage | undefined {\n  for (let index = 0; index < messages.length; index += 1) {\n    const message = messages[index];\n    if (message?.id === messageId) {\n      return message;\n    }\n  }\n  return undefined;\n}\n\nfunction findProposedPlanById(\n  proposedPlans: ReadonlyArray<\n    Pick<OrchestrationProposedPlan, \"id\" | \"createdAt\" | \"implementedAt\" | \"implementationThreadId\">\n  >,\n  planId: string,\n):\n  | Pick<OrchestrationProposedPlan, \"id\" | \"createdAt\" | \"implementedAt\" | \"implementationThreadId\">\n  | undefined {\n  for (let index = 0; index < proposedPlans.length; index += 1) {\n    const proposedPlan = proposedPlans[index];\n    if (proposedPlan?.id === planId) {\n      return proposedPlan;\n    }\n  }\n  return undefined;\n}\n\nfunction truncateDetail(value: string, limit = 180): string {\n  return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;\n}\n\nfunction normalizeProposedPlanMarkdown(planMarkdown: string | undefined): string | undefined {\n  const trimmed = planMarkdown?.trim();\n  if (!trimmed) {\n    return undefined;\n  }\n  return trimmed;\n}\n\nfunction hasRenderableAssistantText(text: string | undefined): boolean {\n  return (text?.trim().length ?? 0) > 0;\n}\n\nfunction proposedPlanIdForTurn(threadId: ThreadId, turnId: TurnId): string {\n  return `plan:${threadId}:turn:${turnId}`;\n}\n\nfunction proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId): string {\n  const turnId = toTurnId(event.turnId);\n  if (turnId) {\n    return proposedPlanIdForTurn(threadId, turnId);\n  }\n  if (event.itemId) {\n    return `plan:${threadId}:item:${event.itemId}`;\n  }\n  return `plan:${threadId}:event:${event.eventId}`;\n}\n\nfunction assistantSegmentBaseKeyFromEvent(event: ProviderRuntimeEvent): string {\n  return String(event.itemId ?? event.turnId ?? event.eventId);\n}\n\nfunction assistantSegmentMessageId(baseKey: string, segmentIndex: number): MessageId {\n  return MessageId.make(\n    segmentIndex === 0 ? `assistant:${baseKey}` : `assistant:${baseKey}:segment:${segmentIndex}`,\n  );\n}\nfunction buildContextWindowActivityPayload(\n  event: ProviderRuntimeEvent,\n): ThreadTokenUsageSnapshot | undefined {\n  if (event.type !== \"thread.token-usage.updated\" || event.payload.usage.usedTokens <= 0) {\n    return undefined;\n  }\n  return event.payload.usage;\n}\n\nfunction normalizeRuntimeTurnState(\n  value: string | undefined,\n): \"completed\" | \"failed\" | \"interrupted\" | \"cancelled\" {\n  switch (value) {\n    case \"failed\":\n    case \"interrupted\":\n    case \"cancelled\":\n    case \"completed\":\n      return value;\n    default:\n      return \"completed\";\n  }\n}\n\nfunction orchestrationSessionStatusFromRuntimeState(\n  state: \"starting\" | \"running\" | \"waiting\" | \"ready\" | \"interrupted\" | \"stopped\" | \"error\",\n): \"starting\" | \"running\" | \"ready\" | \"interrupted\" | \"stopped\" | \"error\" {\n  switch (state) {\n    case \"starting\":\n      return \"starting\";\n    case \"running\":\n    case \"waiting\":\n      return \"running\";\n    case \"ready\":\n      return \"ready\";\n    case \"interrupted\":\n      return \"interrupted\";\n    case \"stopped\":\n      return \"stopped\";\n    case \"error\":\n      return \"error\";\n  }\n}\n\nfunction sessionStatusAllowsActiveTurn(\n  status: ReturnType<typeof orchestrationSessionStatusFromRuntimeState>,\n): boolean {\n  return status === \"starting\" || status === \"running\";\n}\n\nfunction requestKindFromCanonicalRequestType(\n  requestType: string | undefined,\n): \"command\" | \"file-read\" | \"file-change\" | undefined {\n  switch (requestType) {\n    case \"command_execution_approval\":\n    case \"exec_command_approval\":\n      return \"command\";\n    case \"file_read_approval\":\n      return \"file-read\";\n    case \"file_change_approval\":\n    case \"apply_patch_approval\":\n      return \"file-change\";\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Copies the optional TaskAgentLinkage bundle from a task.* runtime payload\n * into the persisted activity payload. Identity fields ride on every row so\n * client folds survive activity retention; absent fields stay absent.\n */\nfunction taskLinkageActivityFields(payload: Record<string, unknown>): Record<string, unknown> {\n  const fields: Record<string, unknown> = {\n    // Server-stamped classification: persisted rows are self-describing, so\n    // clients trust the stamp instead of re-deriving agent-vs-background\n    // from taskType denylists and marker heuristics (legacy rows without a\n    // stamp keep the client fallback).\n    agentKind: classifyTaskAgentKind({\n      taskType: typeof payload.taskType === \"string\" ? payload.taskType : undefined,\n      agentId: typeof payload.agentId === \"string\" ? payload.agentId : undefined,\n    }),\n  };\n  for (const key of [\n    \"taskType\",\n    \"agentId\",\n    \"title\",\n    \"role\",\n    \"model\",\n    \"effort\",\n    \"toolUseId\",\n    \"parentAgentId\",\n    \"workflowName\",\n    \"agentIndex\",\n    \"phaseIndex\",\n    \"phaseTitle\",\n    \"phases\",\n    \"attempt\",\n    \"runHandles\",\n    \"outputFile\",\n    \"agentPath\",\n    \"timelineBypass\",\n    \"typedUsage\",\n    \"status\",\n    \"error\",\n  ] as const) {\n    if (payload[key] !== undefined) {\n      fields[key] = payload[key];\n    }\n  }\n  return fields;\n}\n\nexport function runtimeEventToActivities(\n  event: ProviderRuntimeEvent,\n  taskTitle?: string,\n): ReadonlyArray<OrchestrationThreadActivity> {\n  const maybeSequence = (() => {\n    const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number };\n    return eventWithSequence.sessionSequence !== undefined\n      ? { sequence: eventWithSequence.sessionSequence }\n      : {};\n  })();\n  switch (event.type) {\n    case \"request.opened\": {\n      if (event.payload.requestType === \"tool_user_input\") {\n        return [];\n      }\n      const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"approval\",\n          kind: \"approval.requested\",\n          summary:\n            requestKind === \"command\"\n              ? \"Command approval requested\"\n              : requestKind === \"file-read\"\n                ? \"File-read approval requested\"\n                : requestKind === \"file-change\"\n                  ? \"File-change approval requested\"\n                  : \"Approval requested\",\n          payload: {\n            requestId: toApprovalRequestId(event.requestId),\n            ...(requestKind ? { requestKind } : {}),\n            requestType: event.payload.requestType,\n            ...(event.payload.detail ? { detail: event.payload.detail } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"request.resolved\": {\n      if (event.payload.requestType === \"tool_user_input\") {\n        return [];\n      }\n      const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"approval\",\n          kind: \"approval.resolved\",\n          summary: \"Approval resolved\",\n          payload: {\n            requestId: toApprovalRequestId(event.requestId),\n            ...(requestKind ? { requestKind } : {}),\n            requestType: event.payload.requestType,\n            ...(event.payload.decision ? { decision: event.payload.decision } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"runtime.error\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"error\",\n          kind: \"runtime.error\",\n          summary: \"Runtime error\",\n          payload: {\n            message: truncateDetail(event.payload.message),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"tool.denied\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"error\",\n          kind: \"tool.denied\",\n          summary: `Tool denied: ${event.payload.toolName}`,\n          payload: {\n            toolName: event.payload.toolName,\n            ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),\n            ...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"runtime.warning\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"runtime.warning\",\n          // Use the adapter-supplied message as the row label so the work log\n          // shows what the warning was about, not a generic \"Runtime warning\".\n          summary: truncateDetail(event.payload.message, 120),\n          payload: {\n            message: truncateDetail(event.payload.message),\n            ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"turn.plan.updated\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"turn.plan.updated\",\n          summary: \"Plan updated\",\n          payload: {\n            plan: event.payload.plan,\n            ...(event.payload.explanation !== undefined\n              ? { explanation: event.payload.explanation }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"user-input.requested\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"user-input.requested\",\n          summary: \"User input requested\",\n          payload: {\n            ...(event.requestId ? { requestId: event.requestId } : {}),\n            questions: event.payload.questions,\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"user-input.resolved\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"user-input.resolved\",\n          summary: \"User input submitted\",\n          payload: {\n            ...(event.requestId ? { requestId: event.requestId } : {}),\n            answers: event.payload.answers,\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.started\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"task.started\",\n          summary:\n            event.payload.taskType === \"plan\"\n              ? \"Plan task started\"\n              : event.payload.taskType\n                ? `${event.payload.taskType} task started`\n                : \"Task started\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),\n            ...(event.payload.description\n              ? { detail: truncateDetail(event.payload.description) }\n              : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.progress\": {\n      return [\n        {\n          // Stable per-task id: progress is \"latest state\", not history, so\n          // each tick REPLACES the last via the activity upsert (PK + the\n          // replace-by-id apply in projector and client reducer). Keeps one\n          // progress row per task instead of thousands, so a large fleet's\n          // ticks can no longer evict its own start/terminal rows out of\n          // the 500-row retention window. Thread-scoped: activity_id is a\n          // GLOBAL primary key and Claude task ids are session-local, so a\n          // bare taskId could collide across threads and steal another\n          // thread's row (review finding).\n          id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"task.progress\",\n          summary:\n            event.payload.description.trim().length > 0\n              ? truncateDetail(event.payload.description, 120)\n              : \"Reasoning update\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.description.trim().length > 0\n              ? { title: truncateDetail(event.payload.description, 120) }\n              : {}),\n            detail: truncateDetail(event.payload.summary ?? event.payload.description),\n            ...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),\n            ...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),\n            ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.updated\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: event.payload.status === \"failed\" ? \"error\" : \"info\",\n          kind: \"task.updated\",\n          summary:\n            event.payload.status === \"failed\"\n              ? \"Task failed\"\n              : event.payload.status\n                ? `Task ${event.payload.status}`\n                : \"Task updated\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.description\n              ? { detail: truncateDetail(event.payload.description) }\n              : {}),\n            ...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}),\n            ...(event.payload.isBackgrounded !== undefined\n              ? { isBackgrounded: event.payload.isBackgrounded }\n              : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"tool.progress\": {\n      // Only agent-owned heartbeats are persisted: they feed the owning\n      // agent's activity line. Parent-conversation tool progress stays\n      // ephemeral (item lifecycle already covers it).\n      if (event.payload.taskId === undefined) {\n        return [];\n      }\n      return [\n        {\n          // Same stable-id treatment as task.progress: a heartbeat is\n          // \"what is this agent doing right now\", so one row per task\n          // (thread-scoped for the same global-PK collision reason).\n          id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`),\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"tool.progress\",\n          summary: event.payload.toolName ?? \"Tool progress\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),\n            ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),\n            ...(event.payload.elapsedSeconds !== undefined\n              ? { elapsedSeconds: event.payload.elapsedSeconds }\n              : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.completed\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: event.payload.status === \"failed\" ? \"error\" : \"info\",\n          kind: \"task.completed\",\n          summary:\n            event.payload.status === \"failed\"\n              ? \"Task failed\"\n              : event.payload.status === \"stopped\"\n                ? \"Task stopped\"\n                : \"Task completed\",\n          payload: {\n            taskId: event.payload.taskId,\n            status: event.payload.status,\n            ...(taskTitle ? { title: truncateDetail(taskTitle, 120) } : {}),\n            // summary + detail mirror task.progress: clients label the row from\n            // summary and keep detail for the preview/expanded body.\n            ...(event.payload.summary\n              ? {\n                  summary: truncateDetail(event.payload.summary),\n                  detail: truncateDetail(event.payload.summary),\n                }\n              : {}),\n            ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"thread.state.changed\": {\n      if (event.payload.state !== \"compacted\") {\n        return [];\n      }\n\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"context-compaction\",\n          summary: \"Context compacted\",\n          payload: {\n            state: event.payload.state,\n            ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"thread.token-usage.updated\": {\n      const payload = buildContextWindowActivityPayload(event);\n      if (!payload) {\n        return [];\n      }\n\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"context-window.updated\",\n          summary: \"Context window updated\",\n          payload,\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"item.updated\": {\n      if (!isToolLifecycleItemType(event.payload.itemType)) {\n        return [];\n      }\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"tool\",\n          kind: \"tool.updated\",\n          summary: event.payload.title ?? \"Tool updated\",\n          payload: {\n            itemType: event.payload.itemType,\n            ...(event.payload.status ? { status: event.payload.status } : {}),\n            ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),\n            ...(event.payload.data !== undefined ? { data: event.payload.data } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"item.completed\": {\n      if (!isToolLifecycleItemType(event.payload.itemType)) {\n        return [];\n      }\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"tool\",\n          kind: \"tool.completed\",\n          summary: event.payload.title ?? \"Tool\",\n          payload: {\n            itemType: event.payload.itemType,\n            ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),\n            ...(event.payload.data !== undefined ? { data: event.payload.data } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"item.started\": {\n      if (!isToolLifecycleItemType(event.payload.itemType)) {\n        return [];\n      }\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"tool\",\n          kind: \"tool.started\",\n          summary: `${event.payload.title ?? \"Tool\"} started`,\n          payload: {\n            itemType: event.payload.itemType,\n            ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    default:\n      break;\n  }\n\n  return [];\n}\n\nconst make = Effect.gen(function* () {\n  const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;\n  const crypto = yield* Crypto.Crypto;\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const providerService = yield* ProviderService;\n  const projectionTurnRepository = yield* ProjectionTurnRepository;\n  const serverSettingsService = yield* ServerSettingsService;\n  const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>\n    String(event.eventId).startsWith(\"codex-snapshot:\")\n      ? Effect.succeed(CommandId.make(`provider:${event.eventId}:${tag}`))\n      : crypto.randomUUIDv4.pipe(\n          Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),\n        );\n  const threadLocksRef = yield* SynchronizedRef.make(\n    new Map<ThreadId, Semaphore.Semaphore>(),\n  );\n  const getThreadSemaphore = (threadId: ThreadId) =>\n    SynchronizedRef.modifyEffect(threadLocksRef, (current) => {\n      const existing = current.get(threadId);\n      if (existing) return Effect.succeed([existing, current] as const);\n      return Semaphore.make(1).pipe(\n        Effect.map((semaphore) => {\n          const next = new Map(current);\n          next.set(threadId, semaphore);\n          return [semaphore, next] as const;\n        }),\n      );\n    });\n  const withThreadLock = <A, E, R>(threadId: ThreadId, effect: Effect.Effect<A, E, R>) =>\n    Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));\n\n  const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({\n    capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,\n    timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,\n    lookup: () => Effect.succeed(new Set<MessageId>()),\n  });\n\n  const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({\n    capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,\n    timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,\n    lookup: () => Effect.succeed(\"\"),\n  });\n\n  const assistantSegmentStateByTurnKey = yield* Cache.make<string, AssistantSegmentState>({\n    capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,\n    timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,\n    lookup: () =>\n      Effect.die(\n        new Error(\"assistant segment state should be read through getOption before initialization\"),\n      ),\n  });\n\n  const bufferedProposedPlanById = yield* Cache.make<string, { text: string; createdAt: string }>({\n    capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY,\n    timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL,\n    lookup: () => Effect.succeed({ text: \"\", createdAt: \"\" }),\n  });\n\n  // Task names arrive on task.started/task.progress but not on task.completed,\n  // so remember them per task to title the completion activity.\n  const taskDescriptionByTaskKey = yield* Cache.make<string, string>({\n    capacity: TASK_DESCRIPTION_BY_TASK_CACHE_CAPACITY,\n    timeToLive: TASK_DESCRIPTION_BY_TASK_TTL,\n    lookup: () => Effect.succeed(\"\"),\n  });\n\n  const rememberTaskDescription = (threadId: ThreadId, taskId: string, description: string) =>\n    Cache.set(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId), description);\n\n  // Entries are left in place after completion so replayed or duplicate\n  // terminal events stay titled; TTL, capacity, and the session-exit sweep\n  // bound the cache.\n  const lookupTaskDescription = (threadId: ThreadId, taskId: string) =>\n    Cache.getOption(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId)).pipe(\n      Effect.map((description) =>\n        Option.filter(description, (value) => value.length > 0).pipe(Option.getOrUndefined),\n      ),\n    );\n\n  const resolveThreadDetail = Effect.fn(\"resolveThreadDetail\")(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadDetailById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const resolveThreadShell = Effect.fn(\"resolveThreadShell\")(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadShellById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>\n    Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(\n      Effect.flatMap((existingIds) =>\n        Cache.set(\n          turnMessageIdsByTurnKey,\n          providerTurnKey(threadId, turnId),\n          Option.match(existingIds, {\n            onNone: () => new Set([messageId]),\n            onSome: (ids) => {\n              const nextIds = new Set(ids);\n              nextIds.add(messageId);\n              return nextIds;\n            },\n          }),\n        ),\n      ),\n    );\n\n  const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>\n    Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(\n      Effect.flatMap((existingIds) =>\n        Option.match(existingIds, {\n          onNone: () => Effect.void,\n          onSome: (ids) => {\n            const nextIds = new Set(ids);\n            nextIds.delete(messageId);\n            if (nextIds.size === 0) {\n              return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));\n            }\n            return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds);\n          },\n        }),\n      ),\n    );\n\n  const getAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(\n      Effect.map((existingIds) =>\n        Option.getOrElse(existingIds, (): Set<MessageId> => new Set<MessageId>()),\n      ),\n    );\n\n  const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));\n\n  const getAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.getOption(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId));\n\n  const setAssistantSegmentStateForTurn = (\n    threadId: ThreadId,\n    turnId: TurnId,\n    state: AssistantSegmentState,\n  ) => Cache.set(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId), state);\n\n  const clearAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.invalidate(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId));\n\n  const getActiveAssistantMessageIdForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    getAssistantSegmentStateForTurn(threadId, turnId).pipe(\n      Effect.map((state) =>\n        Option.flatMap(state, (entry) =>\n          entry.activeMessageId ? Option.some(entry.activeMessageId) : Option.none(),\n        ),\n      ),\n    );\n\n  const startAssistantSegmentForTurn = (input: {\n    threadId: ThreadId;\n    turnId: TurnId;\n    baseKey: string;\n  }) =>\n    getAssistantSegmentStateForTurn(input.threadId, input.turnId).pipe(\n      Effect.flatMap((existingState) =>\n        Effect.gen(function* () {\n          const nextState = Option.match(existingState, {\n            onNone: () => ({\n              baseKey: input.baseKey,\n              nextSegmentIndex: 1,\n              activeMessageId: assistantSegmentMessageId(input.baseKey, 0),\n            }),\n            onSome: (state) => {\n              const segmentIndex = state.baseKey === input.baseKey ? state.nextSegmentIndex : 0;\n              const messageId = assistantSegmentMessageId(input.baseKey, segmentIndex);\n              return {\n                baseKey: input.baseKey,\n                nextSegmentIndex: state.baseKey === input.baseKey ? state.nextSegmentIndex + 1 : 1,\n                activeMessageId: messageId,\n              } satisfies AssistantSegmentState;\n            },\n          });\n          yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, nextState);\n          return nextState.activeMessageId!;\n        }),\n      ),\n    );\n\n  const getOrCreateAssistantMessageId = (input: {\n    threadId: ThreadId;\n    event: ProviderRuntimeEvent;\n    turnId?: TurnId;\n  }) =>\n    Effect.gen(function* () {\n      if (!input.turnId) {\n        return assistantSegmentMessageId(assistantSegmentBaseKeyFromEvent(input.event), 0);\n      }\n\n      const activeMessageId = yield* getActiveAssistantMessageIdForTurn(\n        input.threadId,\n        input.turnId,\n      );\n      if (Option.isSome(activeMessageId)) {\n        return activeMessageId.value;\n      }\n\n      return yield* startAssistantSegmentForTurn({\n        threadId: input.threadId,\n        turnId: input.turnId,\n        baseKey: assistantSegmentBaseKeyFromEvent(input.event),\n      });\n    });\n\n  const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>\n    Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(\n      Effect.flatMap((existingText) =>\n        Effect.gen(function* () {\n          const nextText = Option.match(existingText, {\n            onNone: () => delta,\n            onSome: (text) => `${text}${delta}`,\n          });\n          if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {\n            yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);\n            return \"\";\n          }\n\n          // Safety valve: flush full buffered text as an assistant delta to cap memory.\n          yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);\n          return nextText;\n        }),\n      ),\n    );\n\n  const takeBufferedAssistantText = (messageId: MessageId) =>\n    Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(\n      Effect.flatMap((existingText) =>\n        Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(\n          Effect.as(Option.getOrElse(existingText, () => \"\")),\n        ),\n      ),\n    );\n\n  const clearBufferedAssistantText = (messageId: MessageId) =>\n    Cache.invalidate(bufferedAssistantTextByMessageId, messageId);\n\n  const appendBufferedProposedPlan = (planId: string, delta: string, createdAt: string) =>\n    Cache.getOption(bufferedProposedPlanById, planId).pipe(\n      Effect.flatMap((existingEntry) => {\n        const existing = Option.getOrUndefined(existingEntry);\n        return Cache.set(bufferedProposedPlanById, planId, {\n          text: `${existing?.text ?? \"\"}${delta}`,\n          createdAt:\n            existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,\n        });\n      }),\n    );\n\n  const takeBufferedProposedPlan = (planId: string) =>\n    Cache.getOption(bufferedProposedPlanById, planId).pipe(\n      Effect.flatMap((existingEntry) =>\n        Cache.invalidate(bufferedProposedPlanById, planId).pipe(\n          Effect.as(Option.getOrUndefined(existingEntry)),\n        ),\n      ),\n    );\n\n  const clearBufferedProposedPlan = (planId: string) =>\n    Cache.invalidate(bufferedProposedPlanById, planId);\n\n  const clearAssistantMessageState = (messageId: MessageId) =>\n    clearBufferedAssistantText(messageId);\n\n  const flushBufferedAssistantMessage = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    messageId: MessageId;\n    turnId?: TurnId;\n    createdAt: string;\n    commandTag: string;\n  }) =>\n    Effect.gen(function* () {\n      const bufferedText = yield* takeBufferedAssistantText(input.messageId);\n      if (!hasRenderableAssistantText(bufferedText)) {\n        return false;\n      }\n\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.message.assistant.delta\",\n        commandId: yield* providerCommandId(\n          input.event,\n          `${input.commandTag}:${input.messageId}`,\n        ),\n        threadId: input.threadId,\n        messageId: input.messageId,\n        delta: bufferedText,\n        ...(input.turnId ? { turnId: input.turnId } : {}),\n        createdAt: input.createdAt,\n      });\n      return true;\n    });\n\n  const flushBufferedAssistantMessagesForTurn = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    turnId: TurnId;\n    createdAt: string;\n    commandTag: string;\n  }) =>\n    Effect.gen(function* () {\n      const assistantMessageIds = yield* getAssistantMessageIdsForTurn(\n        input.threadId,\n        input.turnId,\n      );\n      const flushedMessageIds = new Set<MessageId>();\n      yield* Effect.forEach(\n        assistantMessageIds,\n        (messageId) =>\n          flushBufferedAssistantMessage({\n            event: input.event,\n            threadId: input.threadId,\n            messageId,\n            turnId: input.turnId,\n            createdAt: input.createdAt,\n            commandTag: input.commandTag,\n          }).pipe(\n            Effect.tap((flushed) =>\n              flushed ? Effect.sync(() => flushedMessageIds.add(messageId)) : Effect.void,\n            ),\n          ),\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      return flushedMessageIds;\n    });\n\n  const finalizeAssistantMessage = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    messageId: MessageId;\n    turnId?: TurnId;\n    createdAt: string;\n    commandTag: string;\n    finalDeltaCommandTag: string;\n    fallbackText?: string;\n    hasProjectedMessage?: boolean;\n  }) =>\n    Effect.gen(function* () {\n      const bufferedText = yield* takeBufferedAssistantText(input.messageId);\n      const text =\n        bufferedText.length > 0\n          ? bufferedText\n          : (input.fallbackText?.trim().length ?? 0) > 0\n            ? input.fallbackText!\n            : \"\";\n      const hasRenderableText = hasRenderableAssistantText(text);\n\n      if (hasRenderableText) {\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.message.assistant.delta\",\n          commandId: yield* providerCommandId(\n            input.event,\n            `${input.finalDeltaCommandTag}:${input.messageId}`,\n          ),\n          threadId: input.threadId,\n          messageId: input.messageId,\n          delta: text,\n          ...(input.turnId ? { turnId: input.turnId } : {}),\n          createdAt: input.createdAt,\n        });\n      }\n\n      if (input.hasProjectedMessage || hasRenderableText) {\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.message.assistant.complete\",\n          commandId: yield* providerCommandId(\n            input.event,\n            `${input.commandTag}:${input.messageId}`,\n          ),\n          threadId: input.threadId,\n          messageId: input.messageId,\n          ...(input.turnId ? { turnId: input.turnId } : {}),\n          createdAt: input.createdAt,\n        });\n      }\n      yield* clearAssistantMessageState(input.messageId);\n    });\n\n  const finalizeActiveAssistantSegmentForTurn = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    turnId: TurnId;\n    createdAt: string;\n    commandTag: string;\n    finalDeltaCommandTag: string;\n    hasProjectedMessage: boolean;\n    flushedMessageIds?: ReadonlySet<MessageId>;\n  }) =>\n    Effect.gen(function* () {\n      const activeMessageId = yield* getActiveAssistantMessageIdForTurn(\n        input.threadId,\n        input.turnId,\n      );\n      if (Option.isNone(activeMessageId)) {\n        return;\n      }\n\n      yield* finalizeAssistantMessage({\n        event: input.event,\n        threadId: input.threadId,\n        messageId: activeMessageId.value,\n        turnId: input.turnId,\n        createdAt: input.createdAt,\n        commandTag: input.commandTag,\n        finalDeltaCommandTag: input.finalDeltaCommandTag,\n        hasProjectedMessage:\n          input.hasProjectedMessage ||\n          (input.flushedMessageIds?.has(activeMessageId.value) ?? false),\n      });\n      yield* forgetAssistantMessageId(input.threadId, input.turnId, activeMessageId.value);\n\n      const state = yield* getAssistantSegmentStateForTurn(input.threadId, input.turnId);\n      if (Option.isSome(state)) {\n        yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, {\n          ...state.value,\n          activeMessageId: null,\n        });\n      }\n    });\n\n  const upsertProposedPlan = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    threadProposedPlans: ReadonlyArray<{\n      id: string;\n      createdAt: string;\n      implementedAt: string | null;\n      implementationThreadId: ThreadId | null;\n    }>;\n    planId: string;\n    turnId?: TurnId;\n    planMarkdown: string | undefined;\n    createdAt: string;\n    updatedAt: string;\n  }) =>\n    Effect.gen(function* () {\n      const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);\n      if (!planMarkdown) {\n        return;\n      }\n\n      const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.proposed-plan.upsert\",\n        commandId: yield* providerCommandId(\n          input.event,\n          `proposed-plan-upsert:${input.planId}`,\n        ),\n        threadId: input.threadId,\n        proposedPlan: {\n          id: input.planId,\n          turnId: input.turnId ?? null,\n          planMarkdown,\n          implementedAt: existingPlan?.implementedAt ?? null,\n          implementationThreadId: existingPlan?.implementationThreadId ?? null,\n          createdAt: existingPlan?.createdAt ?? input.createdAt,\n          updatedAt: input.updatedAt,\n        },\n        createdAt: input.updatedAt,\n      });\n    });\n\n  const finalizeBufferedProposedPlan = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    threadProposedPlans: ReadonlyArray<{\n      id: string;\n      createdAt: string;\n      implementedAt: string | null;\n      implementationThreadId: ThreadId | null;\n    }>;\n    planId: string;\n    turnId?: TurnId;\n    fallbackMarkdown?: string;\n    updatedAt: string;\n  }) =>\n    Effect.gen(function* () {\n      const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);\n      const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);\n      const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);\n      const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;\n      if (!planMarkdown) {\n        return;\n      }\n\n      yield* upsertProposedPlan({\n        event: input.event,\n        threadId: input.threadId,\n        threadProposedPlans: input.threadProposedPlans,\n        planId: input.planId,\n        ...(input.turnId ? { turnId: input.turnId } : {}),\n        planMarkdown,\n        createdAt:\n          bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0\n            ? bufferedPlan.createdAt\n            : input.updatedAt,\n        updatedAt: input.updatedAt,\n      });\n      yield* clearBufferedProposedPlan(input.planId);\n    });\n\n  const clearTurnStateForSession = (threadId: ThreadId) =>\n    Effect.gen(function* () {\n      const prefix = `${threadId}:`;\n      const proposedPlanPrefix = `plan:${threadId}:`;\n      const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));\n      const assistantSegmentKeys = Array.from(yield* Cache.keys(assistantSegmentStateByTurnKey));\n      const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById));\n      const taskDescriptionKeys = Array.from(yield* Cache.keys(taskDescriptionByTaskKey));\n      yield* Effect.forEach(\n        turnKeys,\n        (key) =>\n          Effect.gen(function* () {\n            if (!key.startsWith(prefix)) {\n              return;\n            }\n\n            const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);\n            if (Option.isSome(messageIds)) {\n              yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {\n                concurrency: 1,\n              }).pipe(Effect.asVoid);\n            }\n\n            yield* Cache.invalidate(turnMessageIdsByTurnKey, key);\n          }),\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      yield* Effect.forEach(\n        assistantSegmentKeys,\n        (key) =>\n          key.startsWith(prefix)\n            ? Cache.invalidate(assistantSegmentStateByTurnKey, key)\n            : Effect.void,\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      yield* Effect.forEach(\n        proposedPlanKeys,\n        (key) =>\n          key.startsWith(proposedPlanPrefix)\n            ? Cache.invalidate(bufferedProposedPlanById, key)\n            : Effect.void,\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      yield* Effect.forEach(\n        taskDescriptionKeys,\n        (key) =>\n          key.startsWith(prefix) ? Cache.invalidate(taskDescriptionByTaskKey, key) : Effect.void,\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n    });\n\n  const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(\n    \"getSourceProposedPlanReferenceForPendingTurnStart\",\n  )(function* (threadId: ThreadId) {\n    const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n      threadId,\n    });\n    if (Option.isNone(pendingTurnStart)) {\n      return null;\n    }\n\n    const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;\n    const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;\n    if (sourceThreadId === null || sourcePlanId === null) {\n      return null;\n    }\n\n    return {\n      sourceThreadId,\n      sourcePlanId,\n    } as const;\n  });\n\n  const getExpectedProviderTurnIdForThread = Effect.fn(\"getExpectedProviderTurnIdForThread\")(\n    function* (threadId: ThreadId) {\n      const sessions = yield* providerService.listSessions();\n      const session = sessions.find((entry) => entry.threadId === threadId);\n      return session?.activeTurnId;\n    },\n  );\n\n  const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn(\n    \"getSourceProposedPlanReferenceForAcceptedTurnStart\",\n  )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) {\n    if (eventTurnId === undefined) {\n      return null;\n    }\n\n    const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);\n    if (!sameId(expectedTurnId, eventTurnId)) {\n      return null;\n    }\n\n    return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);\n  });\n\n  const markSourceProposedPlanImplemented = Effect.fn(\"markSourceProposedPlanImplemented\")(\n    function* (\n      sourceThreadId: ThreadId,\n      sourcePlanId: OrchestrationProposedPlanId,\n      implementationThreadId: ThreadId,\n      implementedAt: string,\n    ) {\n      const sourceThread = yield* resolveThreadDetail(sourceThreadId);\n      const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);\n      if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {\n        return;\n      }\n\n      const commandUuid = yield* crypto.randomUUIDv4;\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.proposed-plan.upsert\",\n        commandId: CommandId.make(\n          `provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`,\n        ),\n        threadId: sourceThread.id,\n        proposedPlan: {\n          ...sourcePlan,\n          implementedAt,\n          implementationThreadId,\n          updatedAt: implementedAt,\n        },\n        createdAt: implementedAt,\n      });\n    },\n  );\n\n  const processRuntimeEvent = (event: ProviderRuntimeEvent) =>\n    Effect.gen(function* () {\n      const thread = yield* resolveThreadShell(event.threadId);\n      if (!thread) return;\n\n      let loadedThreadDetail: OrchestrationThread | null | undefined;\n      const getLoadedThreadDetail = () =>\n        Effect.gen(function* () {\n          if (loadedThreadDetail !== undefined) {\n            return loadedThreadDetail;\n          }\n          loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;\n          return loadedThreadDetail;\n        });\n\n      const now = event.createdAt;\n      const eventTurnId = toTurnId(event.turnId);\n      const activeTurnId = thread.session?.activeTurnId ?? null;\n      const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n        threadId: thread.id,\n      });\n      const hasPendingTurnStart =\n        Option.isSome(pendingTurnStart) && thread.session?.status === \"starting\";\n\n      const conflictsWithActiveTurn =\n        activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);\n      const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;\n\n      // A turn.started that conflicts with the active turn is legitimate when\n      // the server itself has a turn start pending for this thread AND the\n      // provider session already tracks the event's turn as its active turn:\n      // steering a running turn makes some providers (e.g. opencode) open a\n      // new turn without ever completing the superseded one. A stale\n      // turn.started for some other turn id still gets rejected.\n      const conflictingTurnStartIsPendingTurnStart =\n        event.type === \"turn.started\" && conflictsWithActiveTurn\n          ? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&\n            Option.isSome(pendingTurnStart)\n          : false;\n\n      const shouldApplyThreadLifecycle = (() => {\n        if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {\n          return true;\n        }\n        switch (event.type) {\n          case \"session.exited\":\n            return true;\n          case \"session.started\":\n          case \"thread.started\":\n            return true;\n          case \"turn.started\":\n            return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;\n          case \"turn.completed\":\n            if (conflictsWithActiveTurn || missingTurnForActiveTurn) {\n              return false;\n            }\n            // Only the active turn may close the lifecycle state.\n            if (activeTurnId !== null && eventTurnId !== undefined) {\n              return sameId(activeTurnId, eventTurnId);\n            }\n            // If no active turn is tracked, accept completion scoped to this thread.\n            return true;\n          default:\n            return true;\n        }\n      })();\n      const acceptedTurnStartedSourcePlan =\n        event.type === \"turn.started\" && shouldApplyThreadLifecycle\n          ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)\n          : null;\n\n      if (\n        event.type === \"session.started\" ||\n        event.type === \"session.state.changed\" ||\n        event.type === \"session.exited\" ||\n        event.type === \"thread.started\" ||\n        event.type === \"turn.started\" ||\n        event.type === \"turn.completed\"\n      ) {\n        const status = (() => {\n          switch (event.type) {\n            case \"session.state.changed\": {\n              const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state);\n              return hasPendingTurnStart && runtimeStatus === \"ready\" ? \"starting\" : runtimeStatus;\n            }\n            case \"turn.started\":\n              return \"running\";\n            case \"session.exited\":\n              return \"stopped\";\n            case \"turn.completed\":\n              return normalizeRuntimeTurnState(event.payload.state) === \"failed\"\n                ? \"error\"\n                : \"ready\";\n            case \"session.started\":\n            case \"thread.started\":\n              // Provider thread/session start notifications can arrive during an\n              // active or pending turn; preserve that lifecycle state.\n              return activeTurnId !== null ? \"running\" : hasPendingTurnStart ? \"starting\" : \"ready\";\n          }\n        })();\n        const nextActiveTurnId =\n          event.type === \"turn.started\"\n            ? (eventTurnId ?? null)\n            : event.type === \"turn.completed\" || event.type === \"session.exited\"\n              ? null\n              : event.type === \"session.state.changed\" &&\n                  !sessionStatusAllowsActiveTurn(\n                    orchestrationSessionStatusFromRuntimeState(event.payload.state),\n                  )\n                ? null\n                : activeTurnId;\n        const lastError =\n          event.type === \"session.state.changed\" && event.payload.state === \"error\"\n            ? (event.payload.reason ?? thread.session?.lastError ?? \"Provider session error\")\n            : event.type === \"turn.completed\" &&\n                normalizeRuntimeTurnState(event.payload.state) === \"failed\"\n              ? (event.payload.errorMessage ?? thread.session?.lastError ?? \"Turn failed\")\n              : status === \"ready\"\n                ? null\n                : (thread.session?.lastError ?? null);\n\n        if (shouldApplyThreadLifecycle) {\n          if (event.type === \"turn.started\" && acceptedTurnStartedSourcePlan !== null) {\n            yield* markSourceProposedPlanImplemented(\n              acceptedTurnStartedSourcePlan.sourceThreadId,\n              acceptedTurnStartedSourcePlan.sourcePlanId,\n              thread.id,\n              now,\n            ).pipe(\n              Effect.catchCause((cause) =>\n                Effect.logWarning(\n                  \"provider runtime ingestion failed to mark source proposed plan\",\n                  {\n                    eventId: event.eventId,\n                    eventType: event.type,\n                    cause: Cause.pretty(cause),\n                  },\n                ),\n              ),\n            );\n          }\n\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.session.set\",\n            commandId: yield* providerCommandId(event, \"thread-session-set\"),\n            threadId: thread.id,\n            session: {\n              threadId: thread.id,\n              status,\n              providerName: event.provider,\n              ...(event.providerInstanceId !== undefined\n                ? { providerInstanceId: event.providerInstanceId }\n                : {}),\n              runtimeMode: thread.session?.runtimeMode ?? \"full-access\",\n              activeTurnId: nextActiveTurnId,\n              lastError,\n              updatedAt: now,\n            },\n            createdAt: now,\n          });\n        }\n      }\n\n      const assistantDelta =\n        event.type === \"content.delta\" && event.payload.streamKind === \"assistant_text\"\n          ? event.payload.delta\n          : undefined;\n      const proposedPlanDelta =\n        event.type === \"turn.proposed.delta\" ? event.payload.delta : undefined;\n\n      if (assistantDelta && assistantDelta.length > 0) {\n        const turnId = toTurnId(event.turnId);\n        const assistantMessageId = yield* getOrCreateAssistantMessageId({\n          threadId: thread.id,\n          event,\n          ...(turnId ? { turnId } : {}),\n        });\n        if (turnId) {\n          yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);\n        }\n\n        const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(\n          serverSettingsService.getSettings,\n          (settings) => (settings.enableAssistantStreaming ? \"streaming\" : \"buffered\"),\n        );\n        if (assistantDeliveryMode === \"buffered\") {\n          const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);\n          if (spillChunk.length > 0) {\n            yield* orchestrationEngine.dispatch({\n              type: \"thread.message.assistant.delta\",\n              commandId: yield* providerCommandId(event, \"assistant-delta-buffer-spill\"),\n              threadId: thread.id,\n              messageId: assistantMessageId,\n              delta: spillChunk,\n              ...(turnId ? { turnId } : {}),\n              createdAt: now,\n            });\n          }\n        } else {\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.message.assistant.delta\",\n            commandId: yield* providerCommandId(event, \"assistant-delta\"),\n            threadId: thread.id,\n            messageId: assistantMessageId,\n            delta: assistantDelta,\n            ...(turnId ? { turnId } : {}),\n            createdAt: now,\n          });\n        }\n      }\n\n      const pauseForUserTurnId =\n        event.type === \"request.opened\" || event.type === \"user-input.requested\"\n          ? toTurnId(event.turnId)\n          : undefined;\n      if (pauseForUserTurnId) {\n        const detailedThread = yield* getLoadedThreadDetail();\n        const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(\n          serverSettingsService.getSettings,\n          (settings) => (settings.enableAssistantStreaming ? \"streaming\" : \"buffered\"),\n        );\n        const flushedMessageIds =\n          assistantDeliveryMode === \"buffered\"\n            ? yield* flushBufferedAssistantMessagesForTurn({\n                event,\n                threadId: thread.id,\n                turnId: pauseForUserTurnId,\n                createdAt: now,\n                commandTag:\n                  event.type === \"request.opened\"\n                    ? \"assistant-delta-flush-on-request-opened\"\n                    : \"assistant-delta-flush-on-user-input-requested\",\n              })\n            : new Set<MessageId>();\n        yield* finalizeActiveAssistantSegmentForTurn({\n          event,\n          threadId: thread.id,\n          turnId: pauseForUserTurnId,\n          createdAt: now,\n          commandTag:\n            event.type === \"request.opened\"\n              ? \"assistant-complete-on-request-opened\"\n              : \"assistant-complete-on-user-input-requested\",\n          finalDeltaCommandTag:\n            event.type === \"request.opened\"\n              ? \"assistant-delta-finalize-on-request-opened\"\n              : \"assistant-delta-finalize-on-user-input-requested\",\n          hasProjectedMessage:\n            detailedThread !== null &&\n            hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {\n              streamingOnly: true,\n            }),\n          flushedMessageIds,\n        });\n      }\n\n      if (proposedPlanDelta && proposedPlanDelta.length > 0) {\n        const planId = proposedPlanIdFromEvent(event, thread.id);\n        yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);\n      }\n\n      const assistantCompletion =\n        event.type === \"item.completed\" && event.payload.itemType === \"assistant_message\"\n          ? {\n              messageId: MessageId.make(\n                `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,\n              ),\n              fallbackText: event.payload.detail,\n            }\n          : undefined;\n      const proposedPlanCompletion =\n        event.type === \"turn.proposed.completed\"\n          ? {\n              planId: proposedPlanIdFromEvent(event, thread.id),\n              turnId: toTurnId(event.turnId),\n              planMarkdown: event.payload.planMarkdown,\n            }\n          : undefined;\n\n      if (assistantCompletion) {\n        const detailedThread = yield* getLoadedThreadDetail();\n        const messages = detailedThread?.messages ?? [];\n        const turnId = toTurnId(event.turnId);\n        const activeAssistantMessageId = turnId\n          ? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)\n          : Option.none<MessageId>();\n        const hasAssistantMessagesForTurn =\n          turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;\n        const assistantMessageId = Option.getOrElse(\n          activeAssistantMessageId,\n          () => assistantCompletion.messageId,\n        );\n        const existingAssistantMessage = findMessageById(messages, assistantMessageId);\n        const shouldApplyFallbackCompletionText =\n          !existingAssistantMessage || existingAssistantMessage.text.length === 0;\n\n        const shouldSkipRedundantCompletion =\n          Option.isNone(activeAssistantMessageId) &&\n          turnId !== undefined &&\n          hasAssistantMessagesForTurn &&\n          (assistantCompletion.fallbackText?.trim().length ?? 0) === 0;\n\n        if (!shouldSkipRedundantCompletion) {\n          if (turnId && Option.isNone(activeAssistantMessageId)) {\n            yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);\n          }\n\n          yield* finalizeAssistantMessage({\n            event,\n            threadId: thread.id,\n            messageId: assistantMessageId,\n            ...(turnId ? { turnId } : {}),\n            createdAt: now,\n            commandTag: \"assistant-complete\",\n            finalDeltaCommandTag: \"assistant-delta-finalize\",\n            hasProjectedMessage: existingAssistantMessage !== undefined,\n            ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText\n              ? { fallbackText: assistantCompletion.fallbackText }\n              : {}),\n          });\n\n          if (turnId) {\n            yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId);\n          }\n        }\n\n        if (turnId) {\n          yield* clearAssistantSegmentStateForTurn(thread.id, turnId);\n        }\n      }\n\n      if (proposedPlanCompletion) {\n        const detailedThread = yield* getLoadedThreadDetail();\n        yield* finalizeBufferedProposedPlan({\n          event,\n          threadId: thread.id,\n          threadProposedPlans: detailedThread?.proposedPlans ?? [],\n          planId: proposedPlanCompletion.planId,\n          ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),\n          fallbackMarkdown: proposedPlanCompletion.planMarkdown,\n          updatedAt: now,\n        });\n      }\n\n      if (event.type === \"turn.completed\") {\n        const detailedThread = yield* getLoadedThreadDetail();\n        const messages = detailedThread?.messages ?? [];\n        const proposedPlans = detailedThread?.proposedPlans ?? [];\n        const turnId = toTurnId(event.turnId);\n        if (turnId) {\n          const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);\n          yield* Effect.forEach(\n            assistantMessageIds,\n            (assistantMessageId) =>\n              finalizeAssistantMessage({\n                event,\n                threadId: thread.id,\n                messageId: assistantMessageId,\n                turnId,\n                createdAt: now,\n                commandTag: \"assistant-complete-finalize\",\n                finalDeltaCommandTag: \"assistant-delta-finalize-fallback\",\n                hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,\n              }),\n            { concurrency: 1 },\n          ).pipe(Effect.asVoid);\n          yield* clearAssistantMessageIdsForTurn(thread.id, turnId);\n          yield* clearAssistantSegmentStateForTurn(thread.id, turnId);\n\n          yield* finalizeBufferedProposedPlan({\n            event,\n            threadId: thread.id,\n            threadProposedPlans: proposedPlans,\n            planId: proposedPlanIdForTurn(thread.id, turnId),\n            turnId,\n            updatedAt: now,\n          });\n        }\n      }\n\n      if (event.type === \"session.exited\") {\n        yield* clearTurnStateForSession(thread.id);\n      }\n\n      if (event.type === \"runtime.error\") {\n        const runtimeErrorMessage = event.payload.message;\n\n        const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD\n          ? true\n          : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);\n\n        if (shouldApplyRuntimeError) {\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.session.set\",\n            commandId: yield* providerCommandId(event, \"runtime-error-session-set\"),\n            threadId: thread.id,\n            session: {\n              threadId: thread.id,\n              status: \"error\",\n              providerName: event.provider,\n              ...(event.providerInstanceId !== undefined\n                ? { providerInstanceId: event.providerInstanceId }\n                : {}),\n              runtimeMode: thread.session?.runtimeMode ?? \"full-access\",\n              activeTurnId: eventTurnId ?? null,\n              lastError: runtimeErrorMessage,\n              updatedAt: now,\n            },\n            createdAt: now,\n          });\n        }\n      }\n\n      if (event.type === \"thread.metadata.updated\" && event.payload.name) {\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.meta.update\",\n          commandId: yield* providerCommandId(event, \"thread-meta-update\"),\n          threadId: thread.id,\n          title: event.payload.name,\n        });\n      }\n\n      if (event.type === \"task.started\" || event.type === \"task.progress\") {\n        const description = event.payload.description?.trim();\n        if (description) {\n          yield* rememberTaskDescription(thread.id, event.payload.taskId, description);\n        }\n      }\n      // Sidebar background liveness: fed from the same lifecycle stream,\n      // read by the shell query at mapping time (no persistence).\n      switch (event.type) {\n        case \"task.started\":\n        case \"task.progress\":\n        case \"task.updated\":\n        case \"task.completed\": {\n          const payload = event.payload as {\n            taskId: string;\n            taskType?: string;\n            status?: string;\n            agentId?: string;\n          };\n          threadBackgroundLiveness.recordTaskLiveness({\n            threadId: thread.id,\n            taskId: payload.taskId,\n            taskType: payload.taskType,\n            status: payload.status,\n            agentId: payload.agentId,\n            kind:\n              event.type === \"task.started\"\n                ? \"started\"\n                : event.type === \"task.progress\"\n                  ? \"progress\"\n                  : event.type === \"task.updated\"\n                    ? \"updated\"\n                    : \"completed\",\n          });\n          break;\n        }\n        case \"session.exited\":\n          threadBackgroundLiveness.clearThreadLiveness(thread.id);\n          break;\n        default:\n          break;\n      }\n\n      let taskTitle: string | undefined;\n      if (event.type === \"task.completed\") {\n        taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);\n        if (!taskTitle) {\n          const threadDetail = yield* getLoadedThreadDetail();\n          taskTitle = findTaskTitleInActivities(threadDetail?.activities, event.payload.taskId);\n        }\n      }\n\n      const activities = runtimeEventToActivities(event, taskTitle);\n      yield* Effect.forEach(activities, (activity) =>\n        providerCommandId(event, `thread-activity-append:${activity.id}`).pipe(\n          Effect.flatMap((commandId) =>\n            orchestrationEngine.dispatch({\n              type: \"thread.activity.append\",\n              commandId,\n              threadId: thread.id,\n              activity,\n              createdAt: activity.createdAt,\n            }),\n          ),\n        ),\n      ).pipe(Effect.asVoid);\n    });\n\n  const reconcileThreadUnlocked = Effect.fn(\"reconcileThreadUnlocked\")(function* (\n    threadId: ThreadId,\n    options?: { readonly requireWritable?: boolean },\n  ) {\n    const thread = yield* resolveThreadShell(threadId);\n    if (!thread) {\n      return;\n    }\n    const session = thread.session;\n    if (session?.providerName !== ProviderDriverKind.make(\"codex\")) {\n      return;\n    }\n\n    // Read the full native snapshot before mutating the local projection.\n    const snapshot = yield* providerService.readThread(threadId);\n    for (const turn of snapshot.turns) {\n      const existingTurn = yield* projectionTurnRepository.getByTurnId({\n        threadId,\n        turnId: turn.id,\n      });\n      const existing = Option.getOrUndefined(existingTurn);\n      const isTerminal =\n        turn.status === \"completed\" ||\n        turn.status === \"failed\" ||\n        turn.status === \"interrupted\";\n      if (\n        isTerminal &&\n        existing &&\n        (existing.state === \"completed\" ||\n          existing.state === \"error\" ||\n          existing.state === \"interrupted\")\n      ) {\n        continue;\n      }\n\n      if (isTerminal) {\n        const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n          threadId,\n        });\n        const originatedInAgentLink =\n          existing?.pendingMessageId !== null && existing?.pendingMessageId !== undefined\n            ? true\n            : Option.isSome(pendingTurnStart);\n        if (!originatedInAgentLink) {\n          const createdAt =\n            turn.startedAt ?? turn.runtimeEvents?.[0]?.createdAt ?? session.updatedAt;\n          const providerThreadId = snapshot.providerThreadId ?? String(threadId);\n          for (const userMessage of turn.userMessages ?? []) {\n            yield* orchestrationEngine.dispatch({\n              type: \"thread.message.user.import\",\n              commandId: CommandId.make(\n                `provider-user:${providerThreadId}:${turn.id}:${userMessage.id}:import`,\n              ),\n              threadId,\n              messageId: MessageId.make(\n                `provider-user:${providerThreadId}:${turn.id}:${userMessage.id}`,\n              ),\n              turnId: turn.id,\n              text: userMessage.text,\n              createdAt,\n            });\n          }\n        }\n      }\n\n      const runtimeEvents = turn.runtimeEvents ?? [];\n      yield* Effect.forEach(\n        isTerminal\n          ? runtimeEvents\n          : runtimeEvents.filter((event) => event.type === \"turn.started\"),\n        processRuntimeEvent,\n        { concurrency: 1, discard: true },\n      );\n    }\n\n    if (options?.requireWritable !== true) {\n      return;\n    }\n    yield* providerService.ensureSession(threadId).pipe(\n      Effect.tapError((cause) =>\n        Effect.gen(function* () {\n          const updatedAt = DateTime.formatIso(yield* DateTime.now);\n          const detail = providerReconciliationFailureDetail(cause);\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.session.set\",\n            commandId: CommandId.make(\n              `provider-writer-acquisition:${threadId}:${yield* crypto.randomUUIDv4}`,\n            ),\n            threadId,\n            session: {\n              ...session,\n              status: \"error\",\n              activeTurnId: null,\n              lastError: detail,\n              updatedAt,\n            },\n            createdAt: updatedAt,\n          });\n        }),\n      ),\n    );\n  });\n\n  const reconcileThread: ProviderRuntimeIngestionShape[\"reconcileThread\"] = (\n    threadId,\n    options,\n  ) =>\n    withThreadLock(threadId, reconcileThreadUnlocked(threadId, options)).pipe(\n      Effect.mapError((cause) =>\n        cause instanceof ProviderRuntimeReconciliationError\n          ? cause\n          : new ProviderRuntimeReconciliationError({\n              threadId,\n              detail: providerReconciliationFailureDetail(cause),\n              cause,\n            }),\n      ),\n    );\n\n  const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;\n\n  const processInput = (input: RuntimeIngestionInput) =>\n    input.source === \"runtime\" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);\n\n  const processInputSafely = (input: RuntimeIngestionInput) =>\n    processInput(input).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.failCause(cause);\n        }\n        return Effect.logWarning(\"provider runtime ingestion failed to process event\", {\n          source: input.source,\n          eventId: input.event.eventId,\n          eventType: input.event.type,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processInputSafely);\n\n  const start: ProviderRuntimeIngestionShape[\"start\"] = () =>\n    Effect.gen(function* () {\n      yield* forkParked(\n        Stream.runForEach(providerService.streamEvents, (event) =>\n          worker.enqueue({ source: \"runtime\", event }),\n        ),\n      );\n      yield* forkParked(\n        Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {\n          if (event.type !== \"thread.turn-start-requested\") {\n            return Effect.void;\n          }\n          return worker.enqueue({ source: \"domain\", event });\n        }),\n      );\n    });\n\n  return {\n    start,\n    reconcileThread,\n    drain: worker.drain,\n  } satisfies ProviderRuntimeIngestionShape;\n});\n\nexport const ProviderRuntimeIngestionLive = Layer.effect(\n  ProviderRuntimeIngestionService,\n  make,\n).pipe(Layer.provide(ProjectionTurnRepositoryLive));\n","import { ProjectId } from \"@t3tools/contracts\";\n\n/**\n * agentlink fork: this helper used to live in `checkpointing/Utils.ts`, which\n * was removed with the checkpointing subsystem. It has no git dependency —\n * it only resolves the working directory a thread's provider session should\n * run in (worktree override first, then the owning project's workspace root).\n */\nexport function resolveThreadWorkspaceCwd(input: {\n  readonly thread: {\n    readonly projectId: ProjectId;\n    readonly worktreePath: string | null;\n  };\n  readonly projects: ReadonlyArray<{\n    readonly id: ProjectId;\n    readonly workspaceRoot: string;\n  }>;\n}): string | undefined {\n  const worktreeCwd = input.thread.worktreePath ?? undefined;\n  if (worktreeCwd) {\n    return worktreeCwd;\n  }\n\n  return input.projects.find((project) => project.id === input.thread.projectId)?.workspaceRoot;\n}\n","import type {\n  OrchestrationEvent,\n  ProviderSession,\n  RuntimeMode,\n  TurnId,\n  ChatAttachment,\n  ModelSelection,\n  OrchestrationSession,\n  ProjectId,\n} from \"@t3tools/contracts\";\nimport {\n  CommandId,\n  EventId,\n  ProviderDriverKind,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\n\nimport { resolveThreadWorkspaceCwd } from \"../../threadWorkspaceCwd.ts\";\nimport { increment, orchestrationEventsProcessedTotal } from \"../../observability/Metrics.ts\";\nimport { ProviderAdapterRequestError } from \"../../provider/Errors.ts\";\nimport type { ProviderServiceError } from \"../../provider/Errors.ts\";\nimport { TextGeneration } from \"../../textGeneration/TextGeneration.ts\";\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport { ProviderRegistry } from \"../../provider/Services/ProviderRegistry.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport {\n  ProviderCommandReactor,\n  type ProviderCommandReactorShape,\n} from \"../Services/ProviderCommandReactor.ts\";\nimport { forkParked, ServerActivation } from \"../../serverActivation.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nconst isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);\nconst isProviderDriverKind = Schema.is(ProviderDriverKind);\n\ntype ProviderIntentEvent = Extract<\n  OrchestrationEvent,\n  {\n    type:\n      | \"thread.meta-updated\"\n      | \"thread.runtime-mode-set\"\n      | \"thread.turn-start-requested\"\n      | \"thread.turn-interrupt-requested\"\n      | \"thread.approval-response-requested\"\n      | \"thread.user-input-response-requested\"\n      | \"thread.session-stop-requested\";\n  }\n>;\n\nfunction toNonEmptyProviderInput(value: string | undefined): string | undefined {\n  const normalized = value?.trim();\n  return normalized && normalized.length > 0 ? normalized : undefined;\n}\n\nfunction mapProviderSessionStatusToOrchestrationStatus(\n  status: \"connecting\" | \"ready\" | \"running\" | \"error\" | \"closed\",\n): OrchestrationSession[\"status\"] {\n  switch (status) {\n    case \"connecting\":\n      return \"starting\";\n    case \"running\":\n      return \"running\";\n    case \"error\":\n      return \"error\";\n    case \"closed\":\n      return \"stopped\";\n    case \"ready\":\n    default:\n      return \"ready\";\n  }\n}\n\nconst turnStartKeyForEvent = (event: ProviderIntentEvent): string =>\n  event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;\n\nconst HANDLED_TURN_START_KEY_MAX = 10_000;\nconst HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);\nconst DEFAULT_RUNTIME_MODE: RuntimeMode = \"full-access\";\nconst DEFAULT_THREAD_TITLE = \"New thread\";\nconst MAX_REGENERATION_ATTACHMENTS = 4;\nconst MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;\nconst MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;\nconst THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = \"[Earlier content truncated]\\n\\n\";\nconst FIRST_USER_CONTEXT_TRUNCATION_MARKER = \"\\n[First user message truncated]\";\n\ntype ThreadTitleMessage = {\n  readonly role: \"user\" | \"assistant\" | \"system\";\n  readonly text: string;\n  readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;\n};\n\nfunction formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {\n  if (message.role === \"system\") {\n    return undefined;\n  }\n  const text = message.text.trim();\n  const attachmentSummary = (message.attachments ?? [])\n    .map((attachment) => attachment.name)\n    .join(\", \");\n  const contents = [\n    ...(text.length > 0 ? [text] : []),\n    ...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),\n  ].join(\"\\n\");\n  return contents.length > 0 ? `${message.role.toUpperCase()}:\\n${contents}` : undefined;\n}\n\nfunction limitFirstUserSection(section: string): string {\n  if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {\n    return section;\n  }\n  return `${section.slice(\n    0,\n    MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,\n  )}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;\n}\n\nfunction collectRecentThreadTitleContext(\n  messages: ReadonlyArray<ThreadTitleMessage>,\n  maxChars: number,\n): {\n  readonly context: string;\n  readonly attachments: ReadonlyArray<ChatAttachment>;\n  readonly truncated: boolean;\n} {\n  let context = \"\";\n  let truncated = false;\n  const retainedAttachments: Array<ChatAttachment> = [];\n\n  for (const message of messages.toReversed()) {\n    const section = formatThreadTitleSection(message);\n    if (section === undefined) {\n      continue;\n    }\n\n    const separator = context.length > 0 ? \"\\n\\n\" : \"\";\n    const available = maxChars - context.length - separator.length;\n    if (section.length > available) {\n      if (available > 0) {\n        context = `${section.slice(-available)}${separator}${context}`;\n        retainedAttachments.unshift(...(message.attachments ?? []));\n      }\n      truncated = true;\n      break;\n    }\n    context = `${section}${separator}${context}`;\n    retainedAttachments.unshift(...(message.attachments ?? []));\n  }\n\n  return { context, attachments: retainedAttachments, truncated };\n}\n\nfunction formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {\n  readonly message: string;\n  readonly attachments: ReadonlyArray<ChatAttachment>;\n} {\n  const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);\n  if (!recent.truncated) {\n    return {\n      message: recent.context,\n      attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),\n    };\n  }\n\n  const firstUserMessage = messages.find(\n    (message) => message.role === \"user\" && formatThreadTitleSection(message),\n  );\n  const firstUserSection = firstUserMessage\n    ? formatThreadTitleSection(firstUserMessage)\n    : undefined;\n  if (!firstUserMessage || !firstUserSection) {\n    return {\n      message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,\n      attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),\n    };\n  }\n\n  const pinnedSection = limitFirstUserSection(firstUserSection);\n  const recentContextBudget =\n    MAX_THREAD_TITLE_CONTEXT_CHARS -\n    pinnedSection.length -\n    \"\\n\\n\".length -\n    THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;\n  const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);\n  const pinnedAttachment = firstUserMessage.attachments?.[0];\n  const recentAttachments = retainedRecent.attachments.filter(\n    (attachment) => attachment.id !== pinnedAttachment?.id,\n  );\n\n  return {\n    message: `${pinnedSection}\\n\\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,\n    attachments: [\n      ...(pinnedAttachment ? [pinnedAttachment] : []),\n      ...recentAttachments.slice(\n        -(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),\n      ),\n    ],\n  };\n}\n\nexport function providerErrorLabel(value: string | undefined): string {\n  const normalized = value?.trim();\n  return normalized && normalized.length > 0 ? normalized : \"unknown\";\n}\n\nexport function providerErrorLabelFromInstanceHint(input: {\n  readonly instanceId?: string | undefined;\n  readonly modelSelectionInstanceId?: string | undefined;\n  readonly sessionProvider?: string | undefined;\n}): string {\n  return providerErrorLabel(\n    input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,\n  );\n}\n\nfunction canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {\n  const trimmedCurrentTitle = currentTitle.trim();\n  if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {\n    return true;\n  }\n\n  const trimmedTitleSeed = titleSeed?.trim();\n  return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0\n    ? trimmedCurrentTitle === trimmedTitleSeed\n    : false;\n}\n\nfunction findProviderAdapterRequestError(\n  cause: Cause.Cause<ProviderServiceError>,\n): ProviderAdapterRequestError | undefined {\n  const failReason = cause.reasons.find(Cause.isFailReason);\n  return isProviderAdapterRequestError(failReason?.error) ? failReason.error : undefined;\n}\n\nfunction isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {\n  const error = findProviderAdapterRequestError(cause);\n  if (error) {\n    const detail = error.detail.toLowerCase();\n    return (\n      detail.includes(\"unknown pending approval request\") ||\n      detail.includes(\"unknown pending permission request\")\n    );\n  }\n  const message = Cause.pretty(cause);\n  return (\n    message.includes(\"unknown pending approval request\") ||\n    message.includes(\"unknown pending permission request\")\n  );\n}\n\nfunction isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {\n  const error = findProviderAdapterRequestError(cause);\n  if (error) {\n    const detail = error.detail.toLowerCase();\n    return (\n      detail.includes(\"unknown pending user-input request\") ||\n      detail.includes(\"unknown pending user input request\") ||\n      detail.includes(\"unknown pending codex user input request\")\n    );\n  }\n  const message = Cause.pretty(cause).toLowerCase();\n  return (\n    message.includes(\"unknown pending user-input request\") ||\n    message.includes(\"unknown pending user input request\") ||\n    message.includes(\"unknown pending codex user input request\")\n  );\n}\n\nfunction stalePendingRequestDetail(\n  requestKind: \"approval\" | \"user-input\",\n  requestId: string,\n): string {\n  return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;\n}\n\nconst make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const providerService = yield* ProviderService;\n  const providerRegistry = yield* ProviderRegistry;\n  const textGeneration = yield* TextGeneration;\n  const serverSettingsService = yield* ServerSettingsService;\n  const serverCommandId = (tag: string) =>\n    crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));\n  const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));\n  const handledTurnStartKeys = yield* Cache.make<string, true>({\n    capacity: HANDLED_TURN_START_KEY_MAX,\n    timeToLive: HANDLED_TURN_START_KEY_TTL,\n    lookup: () => Effect.succeed(true),\n  });\n\n  const hasHandledTurnStartRecently = (key: string) =>\n    Cache.getOption(handledTurnStartKeys, key).pipe(\n      Effect.flatMap((cached) =>\n        Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))),\n      ),\n    );\n\n  const threadModelSelections = new Map<string, ModelSelection>();\n\n  const appendProviderFailureActivity = (input: {\n    readonly threadId: ThreadId;\n    readonly kind:\n      | \"provider.turn.start.failed\"\n      | \"provider.turn.interrupt.failed\"\n      | \"provider.approval.respond.failed\"\n      | \"provider.user-input.respond.failed\"\n      | \"provider.session.stop.failed\";\n    readonly summary: string;\n    readonly detail: string;\n    readonly turnId: TurnId | null;\n    readonly createdAt: string;\n    readonly requestId?: string;\n  }) =>\n    Effect.all({\n      commandId: serverCommandId(\"provider-failure-activity\"),\n      eventId: serverEventId(),\n    }).pipe(\n      Effect.flatMap(({ commandId, eventId }) =>\n        orchestrationEngine.dispatch({\n          type: \"thread.activity.append\",\n          commandId,\n          threadId: input.threadId,\n          activity: {\n            id: eventId,\n            tone: \"error\",\n            kind: input.kind,\n            summary: input.summary,\n            payload: {\n              detail: input.detail,\n              ...(input.requestId ? { requestId: input.requestId } : {}),\n            },\n            turnId: input.turnId,\n            createdAt: input.createdAt,\n          },\n          createdAt: input.createdAt,\n        }),\n      ),\n    );\n\n  const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {\n    const failReason = cause.reasons.find(Cause.isFailReason);\n    const providerError = isProviderAdapterRequestError(failReason?.error)\n      ? failReason.error\n      : undefined;\n    if (providerError) {\n      return providerError.detail;\n    }\n    return Cause.pretty(cause);\n  };\n\n  const setThreadSession = (input: {\n    readonly threadId: ThreadId;\n    readonly session: OrchestrationSession;\n    readonly createdAt: string;\n  }) =>\n    serverCommandId(\"provider-session-set\").pipe(\n      Effect.flatMap((commandId) =>\n        orchestrationEngine.dispatch({\n          type: \"thread.session.set\",\n          commandId,\n          threadId: input.threadId,\n          session: input.session,\n          createdAt: input.createdAt,\n        }),\n      ),\n    );\n\n  const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {\n    readonly threadId: ThreadId;\n    readonly detail: string;\n    readonly createdAt: string;\n  }) {\n    const thread = yield* resolveThread(input.threadId);\n    if (!thread) {\n      return;\n    }\n    const session = thread.session;\n    yield* setThreadSession({\n      threadId: input.threadId,\n      session: {\n        ...(session ?? {\n          threadId: input.threadId,\n          providerName: null,\n          providerInstanceId: thread.modelSelection.instanceId,\n          runtimeMode: thread.runtimeMode,\n        }),\n        status: session?.status === \"stopped\" ? \"stopped\" : \"error\",\n        activeTurnId: null,\n        lastError: input.detail,\n        updatedAt: input.createdAt,\n      },\n      createdAt: input.createdAt,\n    });\n  });\n\n  const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {\n    return yield* projectionSnapshotQuery\n      .getProjectShellById(projectId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadDetailById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {\n    readonly threadId: ThreadId;\n    readonly currentModelSelection: ModelSelection;\n    readonly requestedModelSelection: ModelSelection | undefined;\n  }) {\n    const requestedModelSelection = input.requestedModelSelection;\n    if (\n      requestedModelSelection === undefined ||\n      (input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&\n        input.currentModelSelection.model === requestedModelSelection.model)\n    ) {\n      return;\n    }\n    const providers = yield* providerRegistry.getProviders;\n    const requiresNewThread =\n      providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)\n        ?.requiresNewThreadForModelChange === true ||\n      providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)\n        ?.requiresNewThreadForModelChange === true;\n    if (!requiresNewThread) {\n      return;\n    }\n    return yield* new ProviderAdapterRequestError({\n      provider: providerErrorLabelFromInstanceHint({\n        instanceId: String(requestedModelSelection.instanceId),\n        modelSelectionInstanceId: String(input.currentModelSelection.instanceId),\n      }),\n      method: \"thread.turn.start\",\n      detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,\n    });\n  });\n\n  const ensureSessionForThread = Effect.fn(\"ensureSessionForThread\")(function* (\n    threadId: ThreadId,\n    createdAt: string,\n    options?: {\n      readonly modelSelection?: ModelSelection;\n      readonly pendingTurnStart?: boolean;\n    },\n  ) {\n    const thread = yield* resolveThread(threadId);\n    if (!thread) {\n      return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));\n    }\n\n    const desiredRuntimeMode = thread.runtimeMode;\n    const requestedModelSelection = options?.modelSelection;\n    const resolveActiveSession = (threadId: ThreadId) =>\n      providerService\n        .listSessions()\n        .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));\n\n    const activeSession = yield* resolveActiveSession(threadId);\n    const activeThreadSession =\n      thread.session !== null && thread.session.status !== \"stopped\" && activeSession\n        ? thread.session\n        : null;\n    if (\n      activeThreadSession !== null &&\n      activeSession !== undefined &&\n      (activeThreadSession.providerInstanceId === undefined ||\n        activeSession.providerInstanceId === undefined)\n    ) {\n      return yield* new ProviderAdapterRequestError({\n        provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),\n        method: \"thread.turn.start\",\n        detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,\n      });\n    }\n    const currentInstanceId =\n      activeThreadSession !== null &&\n      activeSession !== undefined &&\n      activeSession.providerInstanceId !== undefined\n        ? activeSession.providerInstanceId\n        : thread.modelSelection.instanceId;\n    const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;\n    const desiredInstanceId = desiredModelSelection.instanceId;\n    const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(\n      Effect.mapError(\n        () =>\n          new ProviderAdapterRequestError({\n            provider: providerErrorLabelFromInstanceHint({\n              instanceId: String(currentInstanceId),\n              modelSelectionInstanceId: String(thread.modelSelection.instanceId),\n              sessionProvider: thread.session?.providerName ?? undefined,\n            }),\n            method: \"thread.turn.start\",\n            detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,\n          }),\n      ),\n    );\n    const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(\n      Effect.mapError(\n        () =>\n          new ProviderAdapterRequestError({\n            provider: providerErrorLabelFromInstanceHint({\n              instanceId: String(desiredModelSelection.instanceId),\n            }),\n            method: \"thread.turn.start\",\n            detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,\n          }),\n      ),\n    );\n    const desiredDriverKind = desiredInfo.driverKind;\n    if (!isProviderDriverKind(desiredDriverKind)) {\n      return yield* new ProviderAdapterRequestError({\n        provider: providerErrorLabel(String(desiredDriverKind)),\n        method: \"thread.turn.start\",\n        detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,\n      });\n    }\n    const preferredProvider: ProviderDriverKind = desiredDriverKind;\n    if (options?.pendingTurnStart === true && thread.session?.status !== \"running\") {\n      yield* setThreadSession({\n        threadId,\n        session: {\n          threadId,\n          status: \"starting\",\n          providerName: activeSession?.provider ?? preferredProvider,\n          providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId,\n          runtimeMode: desiredRuntimeMode,\n          activeTurnId: null,\n          lastError: null,\n          updatedAt: createdAt,\n        },\n        createdAt,\n      });\n    }\n    if (thread.session !== null) {\n      yield* rejectStartedThreadModelChangeIfRequired({\n        threadId,\n        currentModelSelection:\n          activeSession?.model !== undefined\n            ? {\n                ...thread.modelSelection,\n                instanceId: currentInstanceId,\n                model: activeSession.model,\n              }\n            : thread.modelSelection,\n        requestedModelSelection,\n      });\n    }\n    if (\n      thread.session !== null &&\n      requestedModelSelection !== undefined &&\n      requestedModelSelection.instanceId !== currentInstanceId\n    ) {\n      if (currentInfo.driverKind !== desiredInfo.driverKind) {\n        return yield* new ProviderAdapterRequestError({\n          provider: preferredProvider,\n          method: \"thread.turn.start\",\n          detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,\n        });\n      }\n      if (\n        currentInfo.continuationIdentity.continuationKey !==\n        desiredInfo.continuationIdentity.continuationKey\n      ) {\n        return yield* new ProviderAdapterRequestError({\n          provider: preferredProvider,\n          method: \"thread.turn.start\",\n          detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,\n        });\n      }\n    }\n    const project = yield* resolveProject(thread.projectId);\n    const effectiveCwd = resolveThreadWorkspaceCwd({\n      thread,\n      projects: project ? [project] : [],\n    });\n\n    const startProviderSession = (input?: {\n      readonly resumeCursor?: unknown;\n      readonly provider?: ProviderDriverKind;\n    }) =>\n      providerService.startSession(threadId, {\n        threadId,\n        ...(preferredProvider ? { provider: preferredProvider } : {}),\n        providerInstanceId: desiredInstanceId,\n        ...(effectiveCwd ? { cwd: effectiveCwd } : {}),\n        modelSelection: desiredModelSelection,\n        ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),\n        runtimeMode: desiredRuntimeMode,\n      });\n\n    const bindSessionToThread = (session: ProviderSession) =>\n      Effect.gen(function* () {\n        if (session.providerInstanceId === undefined) {\n          return yield* new ProviderAdapterRequestError({\n            provider: providerErrorLabel(session.provider),\n            method: \"thread.turn.start\",\n            detail: `Provider session '${session.threadId}' started without a provider instance id.`,\n          });\n        }\n        yield* setThreadSession({\n          threadId,\n          session: {\n            threadId,\n            status:\n              options?.pendingTurnStart === true && session.status === \"ready\"\n                ? \"starting\"\n                : mapProviderSessionStatusToOrchestrationStatus(session.status),\n            providerName: session.provider,\n            providerInstanceId: session.providerInstanceId,\n            runtimeMode: desiredRuntimeMode,\n            // Provider turn ids are not orchestration turn ids.\n            activeTurnId: null,\n            lastError: session.lastError ?? null,\n            updatedAt: session.updatedAt,\n          },\n          createdAt,\n        });\n      });\n\n    const existingSessionThreadId =\n      thread.session && thread.session.status !== \"stopped\" && activeSession ? thread.id : null;\n    if (existingSessionThreadId) {\n      const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;\n      const cwdChanged = effectiveCwd !== activeSession?.cwd;\n      const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))\n        .sessionModelSwitch;\n      const modelChanged =\n        requestedModelSelection !== undefined &&\n        requestedModelSelection.model !== activeSession?.model;\n      const instanceChanged =\n        requestedModelSelection !== undefined &&\n        activeSession?.providerInstanceId !== requestedModelSelection.instanceId;\n      const shouldRestartForModelChange = modelChanged && sessionModelSwitch === \"unsupported\";\n      const previousModelSelection = threadModelSelections.get(threadId);\n      const shouldRestartForModelSelectionChange =\n        preferredProvider === \"claudeAgent\" &&\n        requestedModelSelection !== undefined &&\n        !Equal.equals(previousModelSelection, requestedModelSelection);\n\n      if (\n        !runtimeModeChanged &&\n        !cwdChanged &&\n        !instanceChanged &&\n        !shouldRestartForModelChange &&\n        !shouldRestartForModelSelectionChange\n      ) {\n        return existingSessionThreadId;\n      }\n\n      const resumeCursor = shouldRestartForModelChange\n        ? undefined\n        : (activeSession?.resumeCursor ?? undefined);\n      yield* Effect.logInfo(\"provider command reactor restarting provider session\", {\n        threadId,\n        existingSessionThreadId,\n        currentProvider: activeSession?.provider,\n        currentInstanceId,\n        desiredInstanceId,\n        desiredProvider: desiredModelSelection.instanceId,\n        currentRuntimeMode: thread.session?.runtimeMode,\n        desiredRuntimeMode: thread.runtimeMode,\n        runtimeModeChanged,\n        previousCwd: activeSession?.cwd,\n        desiredCwd: effectiveCwd,\n        cwdChanged,\n        modelChanged,\n        instanceChanged,\n        shouldRestartForModelChange,\n        shouldRestartForModelSelectionChange,\n        hasResumeCursor: resumeCursor !== undefined,\n      });\n      const restartedSession = yield* startProviderSession(\n        resumeCursor !== undefined ? { resumeCursor } : undefined,\n      );\n      yield* Effect.logInfo(\"provider command reactor restarted provider session\", {\n        threadId,\n        previousSessionId: existingSessionThreadId,\n        restartedSessionThreadId: restartedSession.threadId,\n        provider: restartedSession.provider,\n        runtimeMode: restartedSession.runtimeMode,\n        cwd: restartedSession.cwd,\n      });\n      yield* bindSessionToThread(restartedSession);\n      return restartedSession.threadId;\n    }\n\n    const startedSession = yield* startProviderSession(undefined);\n    yield* bindSessionToThread(startedSession);\n    return startedSession.threadId;\n  });\n\n  const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {\n    readonly threadId: ThreadId;\n    readonly messageText: string;\n    readonly attachments?: ReadonlyArray<ChatAttachment>;\n    readonly modelSelection?: ModelSelection;\n    readonly interactionMode?: \"default\" | \"plan\";\n    readonly createdAt: string;\n  }) {\n    const thread = yield* resolveThread(input.threadId);\n    if (!thread) {\n      return yield* Effect.die(\n        new Error(`Thread '${input.threadId}' was not found in read model.`),\n      );\n    }\n    yield* ensureSessionForThread(input.threadId, input.createdAt, {\n      ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),\n      pendingTurnStart: true,\n    });\n    if (input.modelSelection !== undefined) {\n      threadModelSelections.set(input.threadId, input.modelSelection);\n    }\n    const normalizedInput = toNonEmptyProviderInput(input.messageText);\n    const normalizedAttachments = input.attachments ?? [];\n    const activeSession = yield* providerService\n      .listSessions()\n      .pipe(\n        Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),\n      );\n    const sessionModelSwitch =\n      activeSession === undefined\n        ? \"in-session\"\n        : activeSession.providerInstanceId === undefined\n          ? yield* new ProviderAdapterRequestError({\n              provider: providerErrorLabel(activeSession.provider),\n              method: \"thread.turn.start\",\n              detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,\n            })\n          : (yield* providerService.getCapabilities(activeSession.providerInstanceId))\n              .sessionModelSwitch;\n    const requestedModelSelection =\n      input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;\n    const modelForTurn =\n      sessionModelSwitch === \"unsupported\" && input.modelSelection === undefined\n        ? activeSession?.model !== undefined\n          ? {\n              ...requestedModelSelection,\n              model: activeSession.model,\n            }\n          : requestedModelSelection\n        : input.modelSelection;\n\n    return {\n      threadId: input.threadId,\n      ...(normalizedInput ? { input: normalizedInput } : {}),\n      ...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),\n      ...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),\n      ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),\n    };\n  });\n\n  const maybeGenerateThreadTitleForFirstTurn = Effect.fn(\"maybeGenerateThreadTitleForFirstTurn\")(\n    function* (input: {\n      readonly threadId: ThreadId;\n      readonly cwd: string;\n      readonly messageText: string;\n      readonly attachments?: ReadonlyArray<ChatAttachment>;\n      readonly titleSeed?: string;\n    }) {\n      const attachments = input.attachments ?? [];\n      yield* Effect.gen(function* () {\n        const { textGenerationModelSelection: modelSelection } =\n          yield* serverSettingsService.getSettings;\n\n        const generated = yield* textGeneration.generateThreadTitle({\n          cwd: input.cwd,\n          message: input.messageText,\n          ...(attachments.length > 0 ? { attachments } : {}),\n          modelSelection,\n        });\n        if (!generated) return;\n\n        const thread = yield* resolveThread(input.threadId);\n        if (!thread) return;\n        if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {\n          return;\n        }\n\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.meta.update\",\n          commandId: yield* serverCommandId(\"thread-title-rename\"),\n          threadId: input.threadId,\n          title: generated.title,\n        });\n      }).pipe(\n        Effect.catchCause((cause) =>\n          Effect.logWarning(\"provider command reactor failed to generate or rename thread title\", {\n            threadId: input.threadId,\n            cwd: input.cwd,\n            cause: Cause.pretty(cause),\n          }),\n        ),\n      );\n    },\n  );\n\n  const regenerateThreadTitle = Effect.fn(\"regenerateThreadTitle\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.meta-updated\" }>,\n    requestId: CommandId,\n  ) {\n    if (event.payload.regenerateTitle !== true) {\n      return { _tag: \"Superseded\" } as const;\n    }\n\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread || thread.titleRegeneration?.requestId !== requestId) {\n      return { _tag: \"Superseded\" } as const;\n    }\n\n    const { message, attachments } = formatThreadTitleContext(thread.messages);\n    if (message.length === 0) {\n      return { _tag: \"Completed\", title: undefined } as const;\n    }\n\n    const previousTitle = event.payload.previousTitle ?? thread.title;\n    if (thread.title !== previousTitle) {\n      return { _tag: \"Superseded\" } as const;\n    }\n    const project = yield* resolveProject(thread.projectId);\n    const cwd =\n      resolveThreadWorkspaceCwd({\n        thread,\n        projects: project ? [project] : [],\n      }) ?? process.cwd();\n    const { textGenerationModelSelection: modelSelection } =\n      yield* serverSettingsService.getSettings;\n    const generated = yield* textGeneration.generateThreadTitle({\n      cwd,\n      message,\n      previousTitle,\n      ...(attachments.length > 0 ? { attachments } : {}),\n      modelSelection,\n    });\n    if (generated.title === DEFAULT_THREAD_TITLE || generated.title === previousTitle) {\n      return { _tag: \"Completed\", title: undefined } as const;\n    }\n\n    const latestThread = yield* resolveThread(event.payload.threadId);\n    if (\n      !latestThread ||\n      latestThread.titleRegeneration?.requestId !== requestId ||\n      latestThread.title !== previousTitle\n    ) {\n      return { _tag: \"Superseded\" } as const;\n    }\n\n    return { _tag: \"Completed\", title: generated.title } as const;\n  });\n  const dispatchThreadTitleRegenerationCompletion = Effect.fn(\n    \"dispatchThreadTitleRegenerationCompletion\",\n  )(function* (input: {\n    readonly threadId: ThreadId;\n    readonly requestId: CommandId;\n    readonly title?: string;\n  }) {\n    yield* orchestrationEngine.dispatch({\n      type: \"thread.title.regeneration.complete\",\n      commandId: yield* serverCommandId(\"thread-title-regeneration-complete\"),\n      threadId: input.threadId,\n      requestId: input.requestId,\n      ...(input.title !== undefined ? { title: input.title } : {}),\n    });\n  });\n  const findInterruptedThreadTitleRegenerations = Effect.fn(\n    \"findInterruptedThreadTitleRegenerations\",\n  )(function* () {\n    const readModel = yield* projectionSnapshotQuery.getCommandReadModel();\n    return readModel.threads.flatMap((thread) => {\n      const requestId = thread.titleRegeneration?.requestId;\n      return requestId === undefined ? [] : [{ threadId: thread.id, requestId }];\n    });\n  });\n  const clearInterruptedThreadTitleRegenerations = Effect.fn(\n    \"clearInterruptedThreadTitleRegenerations\",\n  )(function* (\n    interrupted: ReadonlyArray<{ readonly threadId: ThreadId; readonly requestId: CommandId }>,\n  ) {\n    yield* Effect.forEach(\n      interrupted,\n      ({ threadId, requestId }) => {\n        return dispatchThreadTitleRegenerationCompletion({\n          threadId,\n          requestId,\n        }).pipe(\n          Effect.catchCause((cause) => {\n            if (Cause.hasInterruptsOnly(cause)) {\n              return Effect.interrupt;\n            }\n            return Effect.logWarning(\n              \"provider command reactor failed to clear interrupted title regeneration\",\n              {\n                threadId,\n                cause: Cause.pretty(cause),\n              },\n            );\n          }),\n        );\n      },\n      { discard: true },\n    );\n  });\n  const processThreadTitleRegenerationSafely = Effect.fn(\"processThreadTitleRegenerationSafely\")(\n    function* (event: Extract<ProviderIntentEvent, { type: \"thread.meta-updated\" }>) {\n      if (event.payload.regenerateTitle !== true) {\n        return;\n      }\n\n      const requestId = event.payload.titleRegeneration?.requestId ?? event.commandId;\n      if (requestId === null) {\n        return;\n      }\n      const result = yield* regenerateThreadTitle(event, requestId).pipe(\n        Effect.catchCause((cause) => {\n          if (Cause.hasInterruptsOnly(cause)) {\n            return Effect.failCause(cause);\n          }\n          return Effect.logWarning(\"provider command reactor failed to regenerate thread title\", {\n            threadId: event.payload.threadId,\n            cause: Cause.pretty(cause),\n          }).pipe(Effect.as({ _tag: \"Completed\", title: undefined } as const));\n        }),\n      );\n      if (result._tag === \"Superseded\") {\n        return;\n      }\n\n      const completion = {\n        threadId: event.payload.threadId,\n        requestId,\n        ...(result.title !== undefined ? { title: result.title } : {}),\n      };\n      yield* dispatchThreadTitleRegenerationCompletion(completion).pipe(\n        Effect.catchCause((cause) => {\n          if (Cause.hasInterruptsOnly(cause)) {\n            return Effect.failCause(cause);\n          }\n          return Effect.logWarning(\n            \"provider command reactor retrying title regeneration completion\",\n            {\n              threadId: event.payload.threadId,\n              cause: Cause.pretty(cause),\n            },\n          ).pipe(Effect.andThen(dispatchThreadTitleRegenerationCompletion(completion)));\n        }),\n      );\n    },\n    (effect, event) =>\n      effect.pipe(\n        Effect.catchCause((cause) => {\n          if (Cause.hasInterruptsOnly(cause)) {\n            return Effect.failCause(cause);\n          }\n          return Effect.logWarning(\n            \"provider command reactor failed to complete title regeneration\",\n            {\n              threadId: event.payload.threadId,\n              cause: Cause.pretty(cause),\n            },\n          );\n        }),\n      ),\n  );\n  const threadTitleRegenerationWorker = yield* makeDrainableWorker(\n    processThreadTitleRegenerationSafely,\n  );\n\n  const processTurnStartRequested = Effect.fn(\"processTurnStartRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.turn-start-requested\" }>,\n  ) {\n    const key = turnStartKeyForEvent(event);\n    if (yield* hasHandledTurnStartRecently(key)) {\n      return;\n    }\n\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n\n    const message = thread.messages.find((entry) => entry.id === event.payload.messageId);\n    if (!message || message.role !== \"user\") {\n      yield* appendProviderFailureActivity({\n        threadId: event.payload.threadId,\n        kind: \"provider.turn.start.failed\",\n        summary: \"Provider turn start failed\",\n        detail: `User message '${event.payload.messageId}' was not found for turn start request.`,\n        turnId: null,\n        createdAt: event.payload.createdAt,\n      });\n      return;\n    }\n\n    const isFirstUserMessageTurn =\n      thread.messages.filter((entry) => entry.role === \"user\").length === 1;\n    if (isFirstUserMessageTurn) {\n      const project = yield* resolveProject(thread.projectId);\n      const generationCwd =\n        resolveThreadWorkspaceCwd({\n          thread,\n          projects: project ? [project] : [],\n        }) ?? process.cwd();\n      const generationInput = {\n        messageText: message.text,\n        ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),\n        ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),\n      };\n\n      if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {\n        yield* maybeGenerateThreadTitleForFirstTurn({\n          threadId: event.payload.threadId,\n          cwd: generationCwd,\n          ...generationInput,\n        }).pipe(Effect.forkScoped);\n      }\n    }\n\n    const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {\n      if (Cause.hasInterruptsOnly(cause)) {\n        return Effect.void;\n      }\n      const detail = formatFailureDetail(cause);\n      return setThreadSessionErrorOnTurnStartFailure({\n        threadId: event.payload.threadId,\n        detail,\n        createdAt: event.payload.createdAt,\n      }).pipe(\n        Effect.flatMap(() =>\n          appendProviderFailureActivity({\n            threadId: event.payload.threadId,\n            kind: \"provider.turn.start.failed\",\n            summary: \"Provider turn start failed\",\n            detail,\n            turnId: null,\n            createdAt: event.payload.createdAt,\n          }),\n        ),\n        Effect.asVoid,\n      );\n    };\n\n    const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>\n      handleTurnStartFailure(cause).pipe(\n        Effect.catchCause((recoveryCause) =>\n          Effect.logWarning(\"provider command reactor failed to recover turn start failure\", {\n            eventType: event.type,\n            threadId: event.payload.threadId,\n            cause: Cause.pretty(recoveryCause),\n            originalCause: Cause.pretty(cause),\n          }),\n        ),\n      );\n\n    const sendTurnRequest = yield* buildSendTurnRequestForThread({\n      threadId: event.payload.threadId,\n      messageText: message.text,\n      ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),\n      ...(event.payload.modelSelection !== undefined\n        ? { modelSelection: event.payload.modelSelection }\n        : {}),\n      interactionMode: event.payload.interactionMode,\n      createdAt: event.payload.createdAt,\n    }).pipe(\n      Effect.map(Option.some),\n      Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),\n    );\n\n    if (Option.isNone(sendTurnRequest)) {\n      return;\n    }\n\n    yield* providerService\n      .sendTurn(sendTurnRequest.value)\n      .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);\n  });\n\n  const processTurnInterruptRequested = Effect.fn(\"processTurnInterruptRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.turn-interrupt-requested\" }>,\n  ) {\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n    const hasSession = thread.session && thread.session.status !== \"stopped\";\n    if (!hasSession) {\n      return yield* appendProviderFailureActivity({\n        threadId: event.payload.threadId,\n        kind: \"provider.turn.interrupt.failed\",\n        summary: \"Provider turn interrupt failed\",\n        detail: \"No active provider session is bound to this thread.\",\n        turnId: event.payload.turnId ?? null,\n        createdAt: event.payload.createdAt,\n      });\n    }\n\n    // Orchestration turn ids are not provider turn ids, so interrupt by session.\n    yield* providerService.interruptTurn({ threadId: event.payload.threadId });\n  });\n\n  const processApprovalResponseRequested = Effect.fn(\"processApprovalResponseRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.approval-response-requested\" }>,\n  ) {\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n    const hasSession = thread.session && thread.session.status !== \"stopped\";\n    if (!hasSession) {\n      return yield* appendProviderFailureActivity({\n        threadId: event.payload.threadId,\n        kind: \"provider.approval.respond.failed\",\n        summary: \"Provider approval response failed\",\n        detail: \"No active provider session is bound to this thread.\",\n        turnId: null,\n        createdAt: event.payload.createdAt,\n        requestId: event.payload.requestId,\n      });\n    }\n\n    yield* providerService\n      .respondToRequest({\n        threadId: event.payload.threadId,\n        requestId: event.payload.requestId,\n        decision: event.payload.decision,\n      })\n      .pipe(\n        Effect.catchCause((cause) =>\n          appendProviderFailureActivity({\n            threadId: event.payload.threadId,\n            kind: \"provider.approval.respond.failed\",\n            summary: \"Provider approval response failed\",\n            detail: isUnknownPendingApprovalRequestError(cause)\n              ? stalePendingRequestDetail(\"approval\", event.payload.requestId)\n              : Cause.pretty(cause),\n            turnId: null,\n            createdAt: event.payload.createdAt,\n            requestId: event.payload.requestId,\n          }),\n        ),\n      );\n  });\n\n  const processUserInputResponseRequested = Effect.fn(\"processUserInputResponseRequested\")(\n    function* (\n      event: Extract<ProviderIntentEvent, { type: \"thread.user-input-response-requested\" }>,\n    ) {\n      const thread = yield* resolveThread(event.payload.threadId);\n      if (!thread) {\n        return;\n      }\n      const hasSession = thread.session && thread.session.status !== \"stopped\";\n      if (!hasSession) {\n        return yield* appendProviderFailureActivity({\n          threadId: event.payload.threadId,\n          kind: \"provider.user-input.respond.failed\",\n          summary: \"Provider user input response failed\",\n          detail: \"No active provider session is bound to this thread.\",\n          turnId: null,\n          createdAt: event.payload.createdAt,\n          requestId: event.payload.requestId,\n        });\n      }\n\n      yield* providerService\n        .respondToUserInput({\n          threadId: event.payload.threadId,\n          requestId: event.payload.requestId,\n          answers: event.payload.answers,\n        })\n        .pipe(\n          Effect.catchCause((cause) =>\n            appendProviderFailureActivity({\n              threadId: event.payload.threadId,\n              kind: \"provider.user-input.respond.failed\",\n              summary: \"Provider user input response failed\",\n              detail: isUnknownPendingUserInputRequestError(cause)\n                ? stalePendingRequestDetail(\"user-input\", event.payload.requestId)\n                : Cause.pretty(cause),\n              turnId: null,\n              createdAt: event.payload.createdAt,\n              requestId: event.payload.requestId,\n            }),\n          ),\n        );\n    },\n  );\n\n  const processSessionStopRequested = Effect.fn(\"processSessionStopRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.session-stop-requested\" }>,\n  ) {\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n\n    const now = event.payload.createdAt;\n    if (thread.session && thread.session.status !== \"stopped\") {\n      yield* providerService.stopSession({ threadId: thread.id });\n    }\n\n    yield* setThreadSession({\n      threadId: thread.id,\n      session: {\n        threadId: thread.id,\n        status: \"stopped\",\n        providerName: thread.session?.providerName ?? null,\n        ...(thread.session?.providerInstanceId !== undefined\n          ? { providerInstanceId: thread.session.providerInstanceId }\n          : {}),\n        runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,\n        activeTurnId: null,\n        lastError: thread.session?.lastError ?? null,\n        updatedAt: now,\n      },\n      createdAt: now,\n    });\n  });\n\n  const processDomainEvent = Effect.fn(\"processDomainEvent\")(function* (\n    event: ProviderIntentEvent,\n  ) {\n    yield* Effect.annotateCurrentSpan({\n      \"orchestration.event_type\": event.type,\n      \"orchestration.thread_id\": event.payload.threadId,\n      ...(event.commandId ? { \"orchestration.command_id\": event.commandId } : {}),\n    });\n    yield* increment(orchestrationEventsProcessedTotal, {\n      eventType: event.type,\n    });\n    switch (event.type) {\n      case \"thread.meta-updated\":\n        yield* threadTitleRegenerationWorker.enqueue(event);\n        return;\n      case \"thread.runtime-mode-set\": {\n        const thread = yield* resolveThread(event.payload.threadId);\n        if (!thread?.session || thread.session.status === \"stopped\") {\n          return;\n        }\n        const cachedModelSelection = threadModelSelections.get(event.payload.threadId);\n        yield* ensureSessionForThread(\n          event.payload.threadId,\n          event.occurredAt,\n          cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},\n        );\n        return;\n      }\n      case \"thread.turn-start-requested\":\n        yield* processTurnStartRequested(event);\n        return;\n      case \"thread.turn-interrupt-requested\":\n        yield* processTurnInterruptRequested(event);\n        return;\n      case \"thread.approval-response-requested\":\n        yield* processApprovalResponseRequested(event);\n        return;\n      case \"thread.user-input-response-requested\":\n        yield* processUserInputResponseRequested(event);\n        return;\n      case \"thread.session-stop-requested\":\n        yield* processSessionStopRequested(event);\n        return;\n    }\n  });\n\n  const processDomainEventSafely = (event: ProviderIntentEvent) =>\n    processDomainEvent(event).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logWarning(\"provider command reactor failed to process event\", {\n          eventType: event.type,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processDomainEventSafely);\n\n  const start: ProviderCommandReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    const interruptedTitleRegenerations = yield* findInterruptedThreadTitleRegenerations().pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logWarning(\n          \"provider command reactor failed to find interrupted title regenerations\",\n          { cause: Cause.pretty(cause) },\n        ).pipe(Effect.as([]));\n      }),\n    );\n    const processEvent = Effect.fn(\"processEvent\")(function* (event: OrchestrationEvent) {\n      if (\n        (event.type === \"thread.meta-updated\" && event.payload.regenerateTitle === true) ||\n        event.type === \"thread.runtime-mode-set\" ||\n        event.type === \"thread.turn-start-requested\" ||\n        event.type === \"thread.turn-interrupt-requested\" ||\n        event.type === \"thread.approval-response-requested\" ||\n        event.type === \"thread.user-input-response-requested\" ||\n        event.type === \"thread.session-stop-requested\"\n      ) {\n        return yield* worker.enqueue(event);\n      }\n    });\n\n    yield* forkParked(Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent));\n\n    // The domain event stream is hot, so work pending before this reactor\n    // starts cannot be resumed. Correlated completions only clear the request\n    // captured here, leaving any newer request untouched.\n    const clearInterrupted = clearInterruptedThreadTitleRegenerations(\n      interruptedTitleRegenerations,\n    ).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logWarning(\n          \"provider command reactor failed to clear interrupted title regenerations\",\n          {\n            cause: Cause.pretty(cause),\n          },\n        );\n      }),\n    );\n    const activation = yield* ServerActivation;\n    if (activation === undefined) {\n      yield* clearInterrupted;\n    } else {\n      yield* forkParked(clearInterrupted);\n    }\n  });\n\n  return {\n    start,\n    drain: Effect.gen(function* () {\n      yield* worker.drain;\n      yield* threadTitleRegenerationWorker.drain;\n    }),\n  } satisfies ProviderCommandReactorShape;\n});\n\nexport const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);\n","import type { OrchestrationEvent } from \"@t3tools/contracts\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Stream from \"effect/Stream\";\n\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport {\n  ThreadDeletionReactor,\n  type ThreadDeletionReactorShape,\n} from \"../Services/ThreadDeletionReactor.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\n\ntype ThreadDeletedEvent = Extract<OrchestrationEvent, { type: \"thread.deleted\" }>;\n\nexport const logCleanupCauseUnlessInterrupted = <R, E>({\n  effect,\n  message,\n  threadId,\n}: {\n  readonly effect: Effect.Effect<void, E, R>;\n  readonly message: string;\n  readonly threadId: ThreadDeletedEvent[\"payload\"][\"threadId\"];\n}): Effect.Effect<void, E, R> =>\n  effect.pipe(\n    Effect.catchCause((cause) => {\n      if (Cause.hasInterruptsOnly(cause)) {\n        return Effect.failCause(cause);\n      }\n      return Effect.logDebug(message, {\n        threadId,\n        cause: Cause.pretty(cause),\n      });\n    }),\n  );\n\nconst make = Effect.gen(function* () {\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const providerService = yield* ProviderService;\n\n  const stopProviderSession = (threadId: ThreadDeletedEvent[\"payload\"][\"threadId\"]) =>\n    logCleanupCauseUnlessInterrupted({\n      effect: providerService.stopSession({ threadId }),\n      message: \"thread deletion cleanup skipped provider session stop\",\n      threadId,\n    });\n\n  const processThreadDeleted = Effect.fn(\"processThreadDeleted\")(function* (\n    event: ThreadDeletedEvent,\n  ) {\n    const { threadId } = event.payload;\n    yield* stopProviderSession(threadId);\n  });\n\n  const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>\n    processThreadDeleted(event).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.failCause(cause);\n        }\n        return Effect.logWarning(\"thread deletion reactor failed to process event\", {\n          eventType: event.type,\n          threadId: event.payload.threadId,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processThreadDeletedSafely);\n\n  const start: ThreadDeletionReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    yield* forkParked(\n      Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {\n        if (event.type !== \"thread.deleted\") {\n          return Effect.void;\n        }\n        return worker.enqueue(event);\n      }),\n    );\n  });\n\n  return {\n    start,\n    drain: worker.drain,\n  } satisfies ThreadDeletionReactorShape;\n});\n\nexport const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);\n","import {\n  type ProviderDriverKind,\n  type ProviderInstanceId,\n  type ServerProvider,\n  ServerProvider as ServerProviderSchema,\n} from \"@t3tools/contracts\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport { writeFileStringAtomically } from \"../atomicWrite.ts\";\n\nconst decodeProviderStatusCache = Schema.decodeUnknownEffect(\n  Schema.fromJsonString(ServerProviderSchema),\n);\n\nconst mergeProviderModels = (\n  fallbackModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n  cachedModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n): ReadonlyArray<ServerProvider[\"models\"][number]> => {\n  const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));\n  return [...fallbackModels, ...cachedModels.filter((model) => !fallbackSlugs.has(model.slug))];\n};\n\nexport const orderProviderSnapshots = (\n  providers: ReadonlyArray<ServerProvider>,\n): ReadonlyArray<ServerProvider> =>\n  [...providers].toSorted(\n    (left, right) =>\n      (left.displayName ?? \"\").localeCompare(right.displayName ?? \"\") ||\n      left.driver.localeCompare(right.driver) ||\n      left.instanceId.localeCompare(right.instanceId),\n  );\n\nexport const isCachedProviderCorrelated = (input: {\n  readonly cachedProvider: ServerProvider;\n  readonly fallbackProvider: ServerProvider;\n}): boolean =>\n  input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&\n  input.cachedProvider.driver === input.fallbackProvider.driver;\n\nexport const hydrateCachedProvider = (input: {\n  readonly cachedProvider: ServerProvider;\n  readonly fallbackProvider: ServerProvider;\n}): ServerProvider => {\n  if (!isCachedProviderCorrelated(input)) {\n    return input.fallbackProvider;\n  }\n\n  if (\n    !input.fallbackProvider.enabled ||\n    input.cachedProvider.enabled !== input.fallbackProvider.enabled\n  ) {\n    return input.fallbackProvider;\n  }\n\n  const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;\n  const hydratedProvider: ServerProvider = {\n    ...fallbackWithoutMessage,\n    models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),\n    installed: input.cachedProvider.installed,\n    version: input.cachedProvider.version,\n    status: input.cachedProvider.status,\n    auth: input.cachedProvider.auth,\n    checkedAt: input.cachedProvider.checkedAt,\n    slashCommands: input.cachedProvider.slashCommands,\n    skills: input.cachedProvider.skills,\n  };\n\n  return input.cachedProvider.message\n    ? { ...hydratedProvider, message: input.cachedProvider.message }\n    : hydratedProvider;\n};\n\n/**\n * Resolve the on-disk cache path for a provider instance snapshot.\n *\n * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of\n * a built-in kind this equals the legacy `<kind>.json` path (because\n * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing\n * cached snapshots remain readable without any rename step.\n *\n * Non-default instances (e.g. `codex_personal`) land in their own files and\n * never collide with other instances.\n *\n * Cache contents must still carry matching `instanceId` + `driver` identity\n * before hydration. The filename alone is not trusted as a routing key.\n */\nexport const resolveProviderStatusCachePath = Effect.fn(\"resolveProviderStatusCachePath\")(\n  function* (input: {\n    readonly cacheDir: string;\n    readonly instanceId: ProviderInstanceId;\n  }): Effect.fn.Return<string, never, Path.Path> {\n    const path = yield* Path.Path;\n    return path.join(input.cacheDir, `${input.instanceId}.json`);\n  },\n);\n\n/**\n * Legacy kind-keyed path resolver retained for callers that still think in\n * terms of `ProviderDriverKind`. Prefer `resolveProviderStatusCachePath` with an\n * `instanceId`; new code should route through the instance registry.\n *\n * @deprecated use `resolveProviderStatusCachePath` with an instance id.\n */\nexport const resolveLegacyProviderStatusCachePath = Effect.fn(\n  \"resolveLegacyProviderStatusCachePath\",\n)(function* (input: {\n  readonly cacheDir: string;\n  readonly provider: ProviderDriverKind;\n}): Effect.fn.Return<string, never, Path.Path> {\n  const path = yield* Path.Path;\n  return path.join(input.cacheDir, `${input.provider}.json`);\n});\n\nexport const readProviderStatusCache = (filePath: string) =>\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem;\n    const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));\n    if (!exists) {\n      return undefined;\n    }\n\n    const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => \"\"));\n    const trimmed = raw.trim();\n    if (trimmed.length === 0) {\n      return undefined;\n    }\n\n    return yield* decodeProviderStatusCache(trimmed).pipe(\n      Effect.matchCauseEffect({\n        onFailure: (cause) =>\n          Effect.logWarning(\"failed to parse provider status cache, ignoring\", {\n            path: filePath,\n            errorTag: causeErrorTag(cause),\n          }).pipe(Effect.as(undefined)),\n        onSuccess: Effect.succeed,\n      }),\n    );\n  });\n\nexport const writeProviderStatusCache = (input: {\n  readonly filePath: string;\n  readonly provider: ServerProvider;\n}) => {\n  const { updateState: _updateState, ...cacheableProvider } = input.provider;\n  return writeFileStringAtomically({\n    filePath: input.filePath,\n    contents: `${JSON.stringify(cacheableProvider, null, 2)}\\n`,\n  });\n};\n","/**\n * ProviderRegistryLive — aggregates per-instance snapshot streams into a\n * single materialized list.\n *\n * Historically this Layer composed four per-kind Live Layers\n * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a\n * `ServerProviderShape`. Those Lives were deleted during the driver /\n * instance refactor — every driver now carries its `snapshot: ServerProviderShape`\n * bundled onto the `ProviderInstance` the registry produces.\n *\n * Each configured instance (including multi-instance setups like\n * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,\n * keyed by `instanceId`. Instances whose driver is unavailable or whose\n * config failed to decode are merged from `instanceRegistry.listUnavailable`\n * as shadow snapshots so the UI can render their exact unavailable reason.\n *\n * Cache paths on disk are now keyed by `instanceId`. Because\n * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing\n * `<kind>.json` files remain the on-disk location for that driver's default\n * instance. Identity-less legacy cache contents are ignored and replaced by\n * the first live refresh.\n *\n * @module ProviderRegistryLive\n */\nimport {\n  defaultInstanceIdForDriver,\n  ProviderDriverKind,\n  type ProviderInstanceId,\n  type ServerProvider,\n  type ServerProviderUpdateState,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nimport { ServerConfig } from \"../../config.ts\";\nimport { ProviderInstanceRegistry } from \"../Services/ProviderInstanceRegistry.ts\";\nimport { ProviderRegistry, type ProviderRegistryShape } from \"../Services/ProviderRegistry.ts\";\nimport {\n  hydrateCachedProvider,\n  isCachedProviderCorrelated,\n  orderProviderSnapshots,\n  readProviderStatusCache,\n  resolveProviderStatusCachePath,\n  writeProviderStatusCache,\n} from \"../providerStatusCache.ts\";\nimport type { ProviderInstance } from \"../ProviderDriver.ts\";\nimport { makeManualOnlyProviderMaintenanceCapabilities } from \"../providerMaintenance.ts\";\nimport type { ProviderSnapshotSource } from \"../builtInProviderCatalog.ts\";\n\nconst loadProviders = (\n  providerSources: ReadonlyArray<ProviderSnapshotSource>,\n): Effect.Effect<ReadonlyArray<ServerProvider>> =>\n  Effect.forEach(\n    providerSources,\n    (providerSource) =>\n      providerSource.getSnapshot.pipe(\n        Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),\n      ),\n    {\n      concurrency: \"unbounded\",\n    },\n  );\n\nconst makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>\n  makeManualOnlyProviderMaintenanceCapabilities({\n    provider,\n    packageName: null,\n  });\n\nconst hasModelCapabilities = (model: ServerProvider[\"models\"][number]): boolean =>\n  (model.capabilities?.optionDescriptors?.length ?? 0) > 0;\n\nconst shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {\n  // agentlink fork: the upstream special case for OpenCode's deliberately\n  // non-authoritative initial snapshot was removed with the OpenCode driver.\n  // Every driver this build ships publishes authoritative model inventories,\n  // so a missing provider's models are never retained.\n  return true;\n};\n\nconst mergeProviderModels = (\n  provider: ServerProvider,\n  previousModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n  nextModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n): ReadonlyArray<ServerProvider[\"models\"][number]> => {\n  const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);\n\n  if (shouldRetainMissingModels && nextModels.length === 0 && previousModels.length > 0) {\n    return previousModels;\n  }\n\n  const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));\n  const mergedModels = nextModels.map((model) => {\n    const previousModel = previousBySlug.get(model.slug);\n    if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {\n      return model;\n    }\n    return {\n      ...model,\n      capabilities: previousModel.capabilities,\n    };\n  });\n  const nextSlugs = new Set(nextModels.map((model) => model.slug));\n  return shouldRetainMissingModels\n    ? [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))]\n    : mergedModels;\n};\n\nexport const mergeProviderSnapshot = (\n  previousProvider: ServerProvider | undefined,\n  nextProvider: ServerProvider,\n): ServerProvider =>\n  !previousProvider\n    ? nextProvider\n    : {\n        ...nextProvider,\n        models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),\n      };\n\nexport const mergeProviderSnapshots = (\n  previousProviders: ReadonlyArray<ServerProvider>,\n  nextProviders: ReadonlyArray<ServerProvider>,\n): ReadonlyArray<ServerProvider> => {\n  const mergedProviders = new Map(\n    previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),\n  );\n\n  for (const provider of nextProviders) {\n    mergedProviders.set(\n      snapshotInstanceKey(provider),\n      mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),\n    );\n  }\n\n  return orderProviderSnapshots([...mergedProviders.values()]);\n};\n\nexport const selectProvidersByKind = (\n  providers: ReadonlyArray<ServerProvider>,\n  providerKinds: ReadonlySet<ProviderDriverKind>,\n): ReadonlyArray<ServerProvider> =>\n  providers.filter((provider) => providerKinds.has(provider.driver));\n\nexport const haveProvidersChanged = (\n  previousProviders: ReadonlyArray<ServerProvider>,\n  nextProviders: ReadonlyArray<ServerProvider>,\n): boolean => !Equal.equals(previousProviders, nextProviders);\n\nconst correlateSnapshotWithSource = (\n  source: ProviderSnapshotSource,\n  snapshot: ServerProvider,\n): Effect.Effect<ServerProvider> => {\n  if (snapshot.instanceId !== source.instanceId) {\n    return Effect.die(\n      new Error(\n        `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,\n      ),\n    );\n  }\n  if (snapshot.driver !== source.driverKind) {\n    return Effect.die(\n      new Error(\n        `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,\n      ),\n    );\n  }\n  return Effect.succeed(snapshot);\n};\n\n/**\n * Key a snapshot for aggregation and persistence. Snapshot sources\n * must be correlated by instance id before reaching this map; missing\n * identities are defects, not runtime routing fallbacks.\n */\nconst snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {\n  return provider.instanceId;\n};\n\n// Project a live `ProviderInstance` into the aggregator's consumption\n// shape. Each call re-captures the instance's `snapshot` closures, so\n// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because\n// its settings changed), a fresh source rides the new PubSub instead\n// of a closed one.\nconst buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({\n  instanceId: instance.instanceId,\n  driverKind: instance.driverKind,\n  getSnapshot: instance.snapshot.getSnapshot,\n  refresh: instance.snapshot.refresh,\n  streamChanges: instance.snapshot.streamChanges,\n});\n\nexport const ProviderRegistryLive = Layer.effect(\n  ProviderRegistry,\n  Effect.gen(function* () {\n    const instanceRegistry = yield* ProviderInstanceRegistry;\n    const config = yield* ServerConfig;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n\n    // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for\n    // coalesced updates across every instance.\n    const changesPubSub = yield* Effect.acquireRelease(\n      PubSub.unbounded<ReadonlyArray<ServerProvider>>(),\n      PubSub.shutdown,\n    );\n\n    // Boot-only: hydrate `providersRef` from the on-disk per-instance\n    // cache so the UI has something to render during the first refresh.\n    // Instances added post-boot skip this path; their first entry in\n    // `providersRef` comes from the reactive `syncLiveSources` pass\n    // below.\n    const bootInstances = yield* instanceRegistry.listInstances;\n    const bootSources = bootInstances.map(buildSnapshotSource);\n    const fallbackProviders = yield* loadProviders(bootSources);\n    const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();\n    for (let index = 0; index < fallbackProviders.length; index++) {\n      const provider = fallbackProviders[index];\n      const source = bootSources[index];\n      if (provider === undefined || source === undefined) {\n        continue;\n      }\n      fallbackByInstance.set(source.instanceId, provider);\n    }\n\n    const cachedProviders = yield* Effect.forEach(\n      bootSources,\n      (source) =>\n        Effect.gen(function* () {\n          // One cache file per configured instance. For the default\n          // instance of a built-in kind the path equals `<kind>.json` —\n          // identical to the legacy filename. We still require the cache\n          // payload to carry matching instance id + driver kind; old\n          // identity-less payloads are discarded and the awaited refresh\n          // below repopulates the cache.\n          const filePath = yield* resolveProviderStatusCachePath({\n            cacheDir: config.providerStatusCacheDir,\n            instanceId: source.instanceId,\n          }).pipe(Effect.provideService(Path.Path, path));\n          const fallbackProvider = fallbackByInstance.get(source.instanceId);\n          if (fallbackProvider === undefined) {\n            return undefined;\n          }\n          return yield* readProviderStatusCache(filePath).pipe(\n            Effect.provideService(FileSystem.FileSystem, fileSystem),\n            Effect.flatMap((cachedProvider) => {\n              if (cachedProvider === undefined) {\n                return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));\n              }\n              const correlation = {\n                cachedProvider,\n                fallbackProvider,\n              } as const;\n              if (!isCachedProviderCorrelated(correlation)) {\n                return Effect.logWarning(\"provider status cache identity mismatch, ignoring\", {\n                  path: filePath,\n                  instanceId: source.instanceId,\n                  cachedInstanceId: cachedProvider.instanceId ?? null,\n                  driver: source.driverKind,\n                  cachedDriver: cachedProvider.driver ?? null,\n                }).pipe(Effect.as(undefined as ServerProvider | undefined));\n              }\n              return Effect.succeed(hydrateCachedProvider(correlation));\n            }),\n          );\n        }),\n      { concurrency: \"unbounded\" },\n    ).pipe(\n      Effect.map((providers) =>\n        orderProviderSnapshots(\n          providers.filter((provider): provider is ServerProvider => provider !== undefined),\n        ),\n      ),\n    );\n    const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);\n    const maintenanceActionStatesRef = yield* Ref.make<\n      ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>\n    >(new Map());\n\n    // Live-source registry — the dynamic counterpart to the boot-time\n    // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`\n    // reference is used for identity equality so \"no-op\" reconciles\n    // (settings unchanged) skip re-subscribing + re-probing.\n    const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(\n      new Map(),\n    );\n    // Serialize `syncLiveSources` so a rapid burst of reconciles doesn't\n    // interleave two passes clobbering each other's fiber bookkeeping.\n    const syncSemaphore = yield* Semaphore.make(1);\n\n    const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(\n      liveSubsRef,\n    ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));\n\n    const persistProvider = (provider: ServerProvider) =>\n      Effect.gen(function* () {\n        // Persist every instance — the file name is the instance id, so\n        // multi-instance setups (e.g. `codex_personal`, `codex_work`) each\n        // get their own cache. We resolve the path fresh so snapshots\n        // produced by newly-added instances post-boot still land on disk\n        // without the aggregator holding a stale `cachePathByInstance`\n        // entry.\n        const key = snapshotInstanceKey(provider);\n        const filePath = yield* resolveProviderStatusCachePath({\n          cacheDir: config.providerStatusCacheDir,\n          instanceId: key,\n        }).pipe(Effect.provideService(Path.Path, path));\n        yield* writeProviderStatusCache({ filePath, provider }).pipe(\n          Effect.provideService(FileSystem.FileSystem, fileSystem),\n          Effect.provideService(Path.Path, path),\n          Effect.tapError(Effect.logError),\n          Effect.ignore,\n        );\n      });\n\n    const applyProviderUpdateState = Effect.fn(\"applyProviderUpdateState\")(function* (\n      provider: ServerProvider,\n    ) {\n      const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);\n      const updateState = maintenanceActionStates.get(provider.instanceId)?.update;\n      if (!updateState) {\n        const { updateState: _updateState, ...providerWithoutUpdateState } = provider;\n        return providerWithoutUpdateState;\n      }\n      return {\n        ...provider,\n        updateState,\n      };\n    });\n\n    const upsertProviders = Effect.fn(\"upsertProviders\")(function* (\n      nextProviders: ReadonlyArray<ServerProvider>,\n      options?: {\n        readonly publish?: boolean;\n        readonly persist?: boolean;\n        readonly replace?: boolean;\n      },\n    ) {\n      const nextProvidersWithUpdateState = yield* Effect.forEach(\n        nextProviders,\n        applyProviderUpdateState,\n        {\n          concurrency: \"unbounded\",\n        },\n      );\n      const [previousProviders, providers, providersToPersist] = yield* Ref.modify(\n        providersRef,\n        (previousProviders) => {\n          const mergedProviders = new Map(\n            previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),\n          );\n          const updatedKeys = new Set<ProviderInstanceId>();\n\n          for (const provider of nextProvidersWithUpdateState) {\n            const key = snapshotInstanceKey(provider);\n            updatedKeys.add(key);\n            mergedProviders.set(\n              key,\n              options?.replace === true\n                ? provider\n                : mergeProviderSnapshot(mergedProviders.get(key), provider),\n            );\n          }\n\n          const providers = orderProviderSnapshots([...mergedProviders.values()]);\n          const providersToPersist = providers.filter((provider) =>\n            updatedKeys.has(snapshotInstanceKey(provider)),\n          );\n          return [[previousProviders, providers, providersToPersist] as const, providers];\n        },\n      );\n\n      if (haveProvidersChanged(previousProviders, providers)) {\n        if (options?.persist !== false) {\n          yield* Effect.forEach(providersToPersist, persistProvider, {\n            concurrency: \"unbounded\",\n            discard: true,\n          });\n        }\n        if (options?.publish !== false) {\n          yield* PubSub.publish(changesPubSub, providers);\n        }\n      }\n\n      return providers;\n    });\n\n    const syncProvider = Effect.fn(\"syncProvider\")(function* (\n      provider: ServerProvider,\n      options?: {\n        readonly publish?: boolean;\n      },\n    ) {\n      return yield* upsertProviders([provider], options);\n    });\n\n    const setProviderMaintenanceActionState = Effect.fn(\"setProviderMaintenanceActionState\")(\n      function* (input: {\n        readonly instanceId: ProviderInstanceId;\n        readonly action: \"update\";\n        readonly state: ServerProviderUpdateState | null;\n      }) {\n        yield* Ref.update(maintenanceActionStatesRef, (previous) => {\n          const previousActions = previous.get(input.instanceId);\n          const nextActions = { ...previousActions };\n          if (input.state === null || input.state.status === \"idle\") {\n            delete nextActions[input.action];\n          } else {\n            nextActions[input.action] = input.state;\n          }\n\n          const next = new Map(previous);\n          if (Object.keys(nextActions).length === 0) {\n            next.delete(input.instanceId);\n          } else {\n            next.set(input.instanceId, nextActions);\n          }\n          return next;\n        });\n\n        const existingProviders = yield* Ref.get(providersRef);\n        const matchingProvider = existingProviders.find(\n          (candidate) => candidate.instanceId === input.instanceId,\n        );\n        if (!matchingProvider) {\n          return existingProviders;\n        }\n\n        const nextProvider = yield* applyProviderUpdateState(matchingProvider);\n        return yield* upsertProviders([nextProvider], {\n          persist: false,\n        });\n      },\n    );\n\n    const refreshOneSource = Effect.fn(\"refreshOneSource\")(function* (\n      providerSource: ProviderSnapshotSource,\n    ) {\n      return yield* providerSource.refresh.pipe(\n        Effect.flatMap((nextProvider) =>\n          correlateSnapshotWithSource(providerSource, nextProvider).pipe(\n            Effect.flatMap(syncProvider),\n          ),\n        ),\n      );\n    });\n\n    const refreshAll = Effect.fn(\"refreshAll\")(function* () {\n      const sources = yield* getLiveSources;\n      return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {\n        concurrency: \"unbounded\",\n        discard: true,\n      }).pipe(Effect.andThen(Ref.get(providersRef)));\n    });\n\n    const refresh = Effect.fn(\"refresh\")(function* (provider?: ProviderDriverKind) {\n      if (provider === undefined) {\n        return yield* refreshAll();\n      }\n      // Kind-scoped refreshes target the default instance for that driver.\n      const defaultInstanceId = defaultInstanceIdForDriver(provider);\n      const sources = yield* getLiveSources;\n      const providerSource = sources.find(\n        (candidate) => candidate.instanceId === defaultInstanceId,\n      );\n      if (!providerSource) {\n        return yield* Ref.get(providersRef);\n      }\n      return yield* refreshOneSource(providerSource);\n    });\n\n    const refreshInstance = Effect.fn(\"refreshInstance\")(function* (\n      instanceId: ProviderInstanceId,\n    ) {\n      const sources = yield* getLiveSources;\n      const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);\n      if (!providerSource) {\n        return yield* Ref.get(providersRef);\n      }\n      return yield* refreshOneSource(providerSource);\n    });\n\n    const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(\n      \"getProviderMaintenanceCapabilitiesForInstance\",\n    )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {\n      const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(\n        (candidate) => candidate.instanceId === instanceId,\n      );\n      return (\n        instance?.snapshot.maintenanceCapabilities ??\n        makeManualProviderMaintenanceCapabilities(provider)\n      );\n    });\n\n    /**\n     * Diff the aggregator's live-source set against the current\n     * `ProviderInstanceRegistry` and:\n     *   - subscribe to each newly-added or rebuilt instance's\n     *     `streamChanges` (so periodic + enrichment refreshes land in\n     *     `providersRef`);\n     *   - read each newly-added/rebuilt instance's current snapshot after\n     *     subscribing, closing the race with its independently-running\n     *     background startup probe;\n     *   - prune `providersRef` of instances that no longer exist.\n     *\n     * Provider refreshes are owned by each managed provider and never run\n     * on this layer's construction path. Consumers see cached or pending\n     * snapshots immediately, then receive live probe results through the\n     * already-attached change stream.\n     *\n     * Per-instance subscription fibers are not tracked explicitly. When\n     * a rebuilt instance's old child scope closes, its PubSub shuts\n     * down and our `Stream.runForEach` fiber exits naturally.\n     */\n    const syncLiveSources = syncSemaphore.withPermits(1)(\n      Effect.gen(function* () {\n        const instances = yield* instanceRegistry.listInstances;\n        const unavailableProviders = yield* instanceRegistry.listUnavailable;\n        const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(\n          instances.map((instance) => [instance.instanceId, instance] as const),\n        );\n        const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());\n        for (const provider of unavailableProviders) {\n          knownInstanceIds.add(snapshotInstanceKey(provider));\n        }\n        const previousSubs = yield* Ref.get(liveSubsRef);\n\n        // Carry over subscriptions for instances whose identity is\n        // unchanged (reconcile treated them as no-op). Instances that\n        // disappeared, or were rebuilt with a different reference,\n        // fall through to the \"newly-added\" branch below.\n        const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();\n        for (const [instanceId, previousInstance] of previousSubs) {\n          const nextInstance = nextByInstance.get(instanceId);\n          if (nextInstance !== undefined && nextInstance === previousInstance) {\n            carriedOver.set(instanceId, previousInstance);\n          }\n        }\n\n        // Collect new/rebuilt instances in `nextByInstance` insertion\n        // order (which preserves settings-author order).\n        const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];\n        for (const [instanceId, instance] of nextByInstance) {\n          if (carriedOver.has(instanceId)) {\n            continue;\n          }\n          newlyAdded.push([instanceId, instance] as const);\n        }\n\n        // Fork long-lived subscriptions to each new/rebuilt instance's\n        // change stream before reading its current snapshot. If the\n        // driver's own initial probe finishes during this sync, either\n        // the current read or the active subscriber observes the result.\n        for (const [, instance] of newlyAdded) {\n          const source = buildSnapshotSource(instance);\n          yield* Stream.runForEach(source.streamChanges, (provider) =>\n            correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),\n          ).pipe(Effect.forkScoped);\n        }\n        yield* Effect.yieldNow;\n\n        // Snapshot current state without starting a probe. Managed providers\n        // launch their startup refresh independently, so this closes the\n        // subscription race without putting external work on the registry\n        // or HTTP server construction path.\n        yield* Effect.forEach(\n          newlyAdded,\n          ([, instance]) =>\n            Effect.gen(function* () {\n              const source = buildSnapshotSource(instance);\n              const provider = yield* source.getSnapshot;\n              yield* correlateSnapshotWithSource(source, provider).pipe(\n                Effect.flatMap(syncProvider),\n              );\n            }).pipe(Effect.ignoreCause({ log: true })),\n          { concurrency: \"unbounded\", discard: true },\n        );\n        yield* upsertProviders(unavailableProviders, {\n          persist: false,\n          replace: true,\n        });\n\n        const nextSubs = new Map(carriedOver);\n        for (const [instanceId, instance] of newlyAdded) {\n          nextSubs.set(instanceId, instance);\n        }\n        yield* Ref.set(liveSubsRef, nextSubs);\n\n        // Drop aggregator state for instances that have disappeared —\n        // otherwise the UI would keep rendering ghosts.\n        const [previousProviders, providers] = yield* Ref.modify(\n          providersRef,\n          (previousProviders) => {\n            const providers = orderProviderSnapshots(\n              previousProviders.filter((provider) =>\n                knownInstanceIds.has(snapshotInstanceKey(provider)),\n              ),\n            );\n            return [[previousProviders, providers] as const, providers];\n          },\n        );\n        if (haveProvidersChanged(previousProviders, providers)) {\n          yield* PubSub.publish(changesPubSub, providers);\n        }\n        yield* Ref.update(maintenanceActionStatesRef, (previous) => {\n          const next = new Map(previous);\n          for (const instanceId of previous.keys()) {\n            if (!knownInstanceIds.has(instanceId)) {\n              next.delete(instanceId);\n            }\n          }\n          return next;\n        });\n      }),\n    );\n    const syncLiveSourcesAndContinue = syncLiveSources.pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logError(\n          \"provider registry instance sync failed; keeping subscription alive\",\n          {\n            cause: Cause.pretty(cause),\n          },\n        );\n      }),\n    );\n\n    // Seed `providersRef` with the boot-time fallback snapshots so\n    // consumers calling `getProviders` immediately after layer build see\n    // a populated list — even before the first `syncLiveSources` refresh\n    // resolves. Cached snapshots (already in `providersRef`) merge with\n    // these via `upsertProviders` so on-disk state wins where present\n    // and pending fallbacks fill the gaps.\n    yield* upsertProviders(fallbackProviders, { publish: false });\n    // Subscribe to registry mutations BEFORE running the initial sync.\n    // `subscribeChanges` acquires the dequeue synchronously in this\n    // fibre; the subscription is active the instant this `yield*`\n    // returns. Forking the consumer loop later cannot lose a publish\n    // because no publish can reach a not-yet-subscribed dequeue.\n    //\n    // (Contrast with the pre-fix code that did\n    // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.\n    // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,\n    // and `forkScoped` only schedules the fibre — so a reconcile that\n    // published between \"fibre scheduled\" and \"fibre starts running\"\n    // was dropped, which made any settings change that replaced an\n    // instance never propagate to the aggregator's `providersRef`.)\n    // Subscribe to registry mutations BEFORE running the initial sync.\n    // `subscribeChanges` acquires the `PubSub.Subscription` synchronously\n    // in this fibre; the subscription is registered with the PubSub the\n    // instant this `yield*` returns, so any subsequent publish is\n    // buffered in the subscription regardless of when the consumer\n    // fibre below actually starts running.\n    //\n    // (Contrast with the pre-fix code that did\n    // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.\n    // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,\n    // which defers `PubSub.subscribe` to stream start. `forkScoped` only\n    // schedules the consumer fibre — so a reconcile that published\n    // between \"fibre scheduled\" and \"fibre starts running + subscribes\"\n    // was dropped, which made any settings change that replaced an\n    // instance never propagate to the aggregator's `providersRef`.)\n    const instanceChanges = yield* instanceRegistry.subscribeChanges;\n    // Initial sync attaches subscriptions and snapshots current state for\n    // every instance present at boot. Provider probes are already running in\n    // their managed background fibers and never block this layer.\n    yield* syncLiveSources;\n    // React to registry mutations — instance added / removed / rebuilt.\n    // `Stream.fromSubscription` builds a stream over the pre-acquired\n    // subscription rather than subscribing on stream start, which is\n    // what closes the race.\n    yield* Stream.runForEach(\n      Stream.fromSubscription(instanceChanges),\n      () => syncLiveSourcesAndContinue,\n    ).pipe(Effect.forkScoped);\n\n    const recoverRefreshFailure = Effect.fn(\"recoverRefreshFailure\")(function* (\n      cause: Cause.Cause<unknown>,\n    ) {\n      if (Cause.hasInterruptsOnly(cause)) {\n        return yield* Effect.interrupt;\n      }\n      yield* Effect.logError(\"provider registry refresh failed; preserving cached providers\", {\n        cause: Cause.pretty(cause),\n      });\n      return yield* Ref.get(providersRef);\n    });\n\n    return {\n      getProviders: Ref.get(providersRef),\n      refresh: (provider?: ProviderDriverKind) =>\n        refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),\n      refreshInstance: (instanceId: ProviderInstanceId) =>\n        refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),\n      getProviderMaintenanceCapabilitiesForInstance,\n      setProviderMaintenanceActionState,\n      get streamChanges() {\n        return Stream.fromPubSub(changesPubSub);\n      },\n    } satisfies ProviderRegistryShape;\n  }),\n);\n","import * as NodeModule from \"node:module\";\n\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HostProcessArchitecture, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\n\nimport * as PtyAdapter from \"./PtyAdapter.ts\";\n\nexport class NodePtyModuleLoadError extends Schema.TaggedErrorClass<NodePtyModuleLoadError>()(\n  \"NodePtyModuleLoadError\",\n  {\n    platform: Schema.String,\n    architecture: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to load node-pty for ${this.platform}-${this.architecture}.`;\n  }\n}\n\ntype NodePtyModuleLoader = () => Promise<typeof import(\"node-pty\")>;\n\nlet didEnsureSpawnHelperExecutable = false;\n\nconst resolveNodePtySpawnHelperPath = Effect.gen(function* () {\n  const requireForNodePty = NodeModule.createRequire(import.meta.url);\n  const path = yield* Path.Path;\n  const fs = yield* FileSystem.FileSystem;\n  const platform = yield* HostProcessPlatform;\n  const architecture = yield* HostProcessArchitecture;\n\n  const packageJsonPath = requireForNodePty.resolve(\"node-pty/package.json\");\n  const packageDir = path.dirname(packageJsonPath);\n  const candidates = [\n    path.join(packageDir, \"build\", \"Release\", \"spawn-helper\"),\n    path.join(packageDir, \"build\", \"Debug\", \"spawn-helper\"),\n    path.join(packageDir, \"prebuilds\", `${platform}-${architecture}`, \"spawn-helper\"),\n  ];\n\n  for (const candidate of candidates) {\n    if (yield* fs.exists(candidate)) {\n      return candidate;\n    }\n  }\n  return null;\n}).pipe(Effect.orElseSucceed(() => null));\n\nconst ensureNodePtySpawnHelperExecutable = Effect.fn(function* () {\n  const fs = yield* FileSystem.FileSystem;\n  const platform = yield* HostProcessPlatform;\n  if (platform === \"win32\") return;\n  if (didEnsureSpawnHelperExecutable) return;\n\n  const helperPath = yield* resolveNodePtySpawnHelperPath;\n  if (!helperPath) return;\n  didEnsureSpawnHelperExecutable = true;\n\n  if (!(yield* fs.exists(helperPath))) {\n    return;\n  }\n\n  // Best-effort: avoid FileSystem.stat in packaged mode where some fs metadata can be missing.\n  yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));\n});\n\nclass NodePtyProcess implements PtyAdapter.PtyProcess {\n  private readonly process: import(\"node-pty\").IPty;\n\n  constructor(process: import(\"node-pty\").IPty) {\n    this.process = process;\n  }\n\n  get pid(): number {\n    return this.process.pid;\n  }\n\n  write(data: string): void {\n    this.process.write(data);\n  }\n\n  resize(cols: number, rows: number): void {\n    this.process.resize(cols, rows);\n  }\n\n  kill(signal?: string): void {\n    this.process.kill(signal);\n  }\n\n  onData(callback: (data: string) => void): () => void {\n    const disposable = this.process.onData(callback);\n    return () => {\n      disposable.dispose();\n    };\n  }\n\n  onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {\n    const disposable = this.process.onExit((event) => {\n      callback({\n        exitCode: event.exitCode,\n        signal: event.signal ?? null,\n      });\n    });\n    return () => {\n      disposable.dispose();\n    };\n  }\n}\n\nexport const make = Effect.fn(\"NodePtyAdapter.make\")(function* (\n  loadNodePtyModule: NodePtyModuleLoader = () => import(\"node-pty\"),\n) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const platform = yield* HostProcessPlatform;\n  const architecture = yield* HostProcessArchitecture;\n\n  const nodePty = yield* Effect.tryPromise({\n    try: loadNodePtyModule,\n    catch: (cause) =>\n      new NodePtyModuleLoadError({\n        platform,\n        architecture,\n        cause,\n      }),\n  }).pipe(Effect.orDie);\n\n  const ensureNodePtySpawnHelperExecutableCached = yield* Effect.cached(\n    ensureNodePtySpawnHelperExecutable().pipe(\n      Effect.provideService(FileSystem.FileSystem, fs),\n      Effect.provideService(Path.Path, path),\n      Effect.provideService(HostProcessPlatform, platform),\n      Effect.provideService(HostProcessArchitecture, architecture),\n      Effect.orElseSucceed(() => undefined),\n    ),\n  );\n\n  return PtyAdapter.PtyAdapter.of({\n    spawn: Effect.fn(\"NodePtyAdapter.spawn\")(function* (input) {\n      yield* ensureNodePtySpawnHelperExecutableCached;\n      const ptyProcess = yield* Effect.try({\n        try: () =>\n          nodePty.spawn(input.shell, input.args ?? [], {\n            cwd: input.cwd,\n            cols: input.cols,\n            rows: input.rows,\n            env: input.env,\n            name: platform === \"win32\" ? \"xterm-color\" : \"xterm-256color\",\n          }),\n        catch: (cause) =>\n          new PtyAdapter.PtySpawnError({\n            adapter: \"node-pty\",\n            shell: input.shell,\n            cause,\n          }),\n      });\n      return new NodePtyProcess(ptyProcess);\n    }),\n  });\n});\n\nexport const layer = Layer.effect(PtyAdapter.PtyAdapter, make());\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Headers from \"effect/unstable/http/Headers\";\n\nexport const httpHeaderRedactionLayer = Layer.effect(\n  Headers.CurrentRedactedNames,\n  Effect.map(Headers.CurrentRedactedNames, (names) => [...names, \"dpop\"]),\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Logger from \"effect/Logger\";\nimport * as References from \"effect/References\";\nimport * as Layer from \"effect/Layer\";\n\nimport { ServerConfig } from \"./config.ts\";\n\nexport const ServerLoggerLive = Effect.gen(function* () {\n  const config = yield* ServerConfig;\n  const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel);\n  const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], {\n    mergeWithExisting: false,\n  });\n\n  return Layer.mergeAll(loggerLayer, minimumLogLevelLayer);\n}).pipe(Layer.unwrap);\n","import { httpHeaderRedactionLayer } from \"@t3tools/shared/httpObservability\";\nimport { makeLocalFileTracer, makeTraceSink } from \"@t3tools/shared/observability\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as References from \"effect/References\";\nimport * as Tracer from \"effect/Tracer\";\nimport * as OtlpExporter from \"effect/unstable/observability/OtlpExporter\";\nimport * as OtlpMetrics from \"effect/unstable/observability/OtlpMetrics\";\nimport * as OtlpSerialization from \"effect/unstable/observability/OtlpSerialization\";\nimport * as OtlpTracer from \"effect/unstable/observability/OtlpTracer\";\n\nimport * as ServerConfig from \"../../config.ts\";\nimport * as ResourceAttribution from \"../../resourceTelemetry/ResourceAttribution.ts\";\nimport { ServerLoggerLive } from \"../../serverLogger.ts\";\nimport * as BrowserTraceCollector from \"../BrowserTraceCollector.ts\";\n\nconst otlpSerializationLayer = OtlpSerialization.layerJson;\n\nexport const ObservabilityLive = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    const attribution = yield* ResourceAttribution.ResourceAttribution;\n\n    const traceReferencesLayer = Layer.mergeAll(\n      Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),\n      Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),\n      httpHeaderRedactionLayer,\n    );\n\n    const tracerLayer = Layer.unwrap(\n      Effect.gen(function* () {\n        const sink = yield* makeTraceSink({\n          filePath: config.serverTracePath,\n          maxBytes: config.traceMaxBytes,\n          maxFiles: config.traceMaxFiles,\n          batchWindowMs: config.traceBatchWindowMs,\n          onFlush: (stats) =>\n            attribution.record({\n              component: \"server-trace\",\n              operation: \"append\",\n              logicalWriteBytes: stats.logicalWriteBytes,\n              count: stats.count,\n              durationMs: stats.durationMs,\n            }),\n        });\n        const delegate =\n          config.otlpTracesUrl === undefined\n            ? undefined\n            : yield* OtlpTracer.make({\n                url: config.otlpTracesUrl,\n                exportInterval: `${config.otlpExportIntervalMs} millis`,\n                resource: {\n                  serviceName: config.otlpServiceName,\n                  attributes: {\n                    \"service.runtime\": \"t3-server\",\n                    \"service.mode\": config.mode,\n                  },\n                },\n              });\n\n        const tracer = yield* makeLocalFileTracer({\n          filePath: config.serverTracePath,\n          maxBytes: config.traceMaxBytes,\n          maxFiles: config.traceMaxFiles,\n          batchWindowMs: config.traceBatchWindowMs,\n          sink,\n          ...(delegate ? { delegate } : {}),\n        });\n\n        return Layer.mergeAll(\n          Layer.succeed(Tracer.Tracer, tracer),\n          BrowserTraceCollector.layer(sink),\n        );\n      }),\n    ).pipe(Layer.provide(OtlpExporter.layerFlusher), Layer.provideMerge(otlpSerializationLayer));\n\n    const metricsLayer =\n      config.otlpMetricsUrl === undefined\n        ? Layer.empty\n        : OtlpMetrics.layer({\n            url: config.otlpMetricsUrl,\n            exportInterval: `${config.otlpExportIntervalMs} millis`,\n            resource: {\n              serviceName: config.otlpServiceName,\n              attributes: {\n                \"service.runtime\": \"t3-server\",\n                \"service.mode\": config.mode,\n              },\n            },\n          }).pipe(Layer.provideMerge(otlpSerializationLayer));\n\n    return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer);\n  }),\n);\n","/**\n * agentlink fork: the T3 Connect cloud link subsystem (`cloud/`) was cut\n * from this build. The `connect` HTTP group stays registered so\n * `EnvironmentHttpApi` keeps its full surface, but every endpoint fails\n * fast with a typed internal-server error instead of reaching deleted\n * services.\n */\nimport { EnvironmentHttpApi, EnvironmentHttpInternalServerError } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nconst unsupported = new EnvironmentHttpInternalServerError({\n  message: \"T3 Connect is unsupported in this build.\",\n});\n\nexport const connectHttpApiLayer = HttpApiBuilder.group(EnvironmentHttpApi, \"connect\", (handlers) =>\n  handlers\n    .handle(\"linkProof\", () => Effect.fail(unsupported))\n    .handle(\"relayConfig\", () => Effect.fail(unsupported))\n    .handle(\"linkState\", () => Effect.fail(unsupported))\n    .handle(\"unlink\", () => Effect.fail(unsupported))\n    .handle(\"preferences\", () => Effect.fail(unsupported))\n    .handle(\"health\", () => Effect.fail(unsupported))\n    .handle(\"mintCredential\", () => Effect.fail(unsupported))\n    .handle(\"t3MintCredential\", () => Effect.fail(unsupported)),\n);\n","import {\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  EnvironmentHttpApi,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport { projectThreadDetailSnapshot } from \"./ActivityPayloadProjection.ts\";\nimport { normalizeDispatchCommand } from \"./Normalizer.ts\";\nimport {\n  annotateEnvironmentRequest,\n  failEnvironmentInternal,\n  failEnvironmentInvalidRequest,\n  failEnvironmentNotFound,\n  requireEnvironmentScope,\n} from \"../auth/http.ts\";\nimport { OrchestrationEngineService } from \"./Services/OrchestrationEngine.ts\";\nimport { ProjectionSnapshotQuery } from \"./Services/ProjectionSnapshotQuery.ts\";\n\nexport const orchestrationHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"orchestration\",\n  Effect.fnUntraced(function* (handlers) {\n    const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n    const orchestrationEngine = yield* OrchestrationEngineService;\n\n    return handlers\n      .handle(\n        \"snapshot\",\n        Effect.fn(\"environment.orchestration.snapshot\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationReadScope);\n          // Serve the lightweight command read model (thread bodies empty)\n          // instead of the fully hydrated snapshot. Hydrating every message\n          // and activity payload in the database has OOM-killed servers, and\n          // the route's only consumer (the project CLI) reads projects alone —\n          // UI clients load the shell and per-thread snapshots instead.\n          return yield* projectionSnapshotQuery\n            .getCommandReadModel()\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_snapshot_failed\", cause),\n              ),\n            );\n        }),\n      )\n      .handle(\n        \"shellSnapshot\",\n        Effect.fn(\"environment.orchestration.shellSnapshot\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationReadScope);\n          return yield* projectionSnapshotQuery\n            .getShellSnapshot()\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_snapshot_failed\", cause),\n              ),\n            );\n        }),\n      )\n      .handle(\n        \"threadSnapshot\",\n        Effect.fn(\"environment.orchestration.threadSnapshot\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationReadScope);\n          const snapshot = yield* projectionSnapshotQuery\n            .getThreadDetailSnapshot(args.params.threadId)\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_thread_snapshot_failed\", cause),\n              ),\n            );\n          if (Option.isNone(snapshot)) {\n            return yield* failEnvironmentNotFound(\"thread_not_found\");\n          }\n          return projectThreadDetailSnapshot(snapshot.value);\n        }),\n      )\n      .handle(\n        \"dispatch\",\n        Effect.fn(\"environment.orchestration.dispatch\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationOperateScope);\n          const normalizedCommand = yield* normalizeDispatchCommand(args.payload).pipe(\n            Effect.catch(() => failEnvironmentInvalidRequest(\"invalid_command\")),\n          );\n          return yield* orchestrationEngine\n            .dispatch(normalizedCommand)\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_dispatch_failed\", cause),\n              ),\n            );\n        }),\n      );\n  }),\n);\n","import { EnvironmentHttpApi } from \"@t3tools/contracts\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { FetchHttpClient, HttpRouter, HttpServer } from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport * as BackgroundPolicy from \"./background/BackgroundPolicy.ts\";\nimport * as HostPowerMonitor from \"./background/HostPowerMonitor.ts\";\nimport * as DesktopTelemetryReceiver from \"./resourceTelemetry/DesktopTelemetryReceiver.ts\";\nimport * as ResourceAttribution from \"./resourceTelemetry/ResourceAttribution.ts\";\nimport * as ServerConfig from \"./config.ts\";\nimport {\n  otlpTracesProxyRouteLayer,\n  assetRouteLayer,\n  serverEnvironmentHttpApiLayer,\n  staticAndDevRouteLayer,\n  browserApiCorsLayer,\n  httpCompressionLayer,\n} from \"./http.ts\";\nimport { fixPath } from \"./os-jank.ts\";\nimport * as HubTunnel from \"./tunnel/bridge.ts\";\nimport * as AgentAwarenessHub from \"./tunnel/AgentAwarenessHub.ts\";\nimport { websocketRpcRouteLayer } from \"./ws.ts\";\nimport * as ExternalLauncher from \"./process/externalLauncher.ts\";\nimport { layerConfig as SqlitePersistenceLayerLive } from \"./persistence/Layers/Sqlite.ts\";\nimport * as ServerLifecycleEvents from \"./serverLifecycleEvents.ts\";\nimport * as AnalyticsService from \"./telemetry/AnalyticsService.ts\";\nimport { ProviderSessionDirectoryLive } from \"./provider/Layers/ProviderSessionDirectory.ts\";\nimport * as ProviderSessionRuntime from \"./persistence/ProviderSessionRuntime.ts\";\nimport { ProviderAdapterRegistryLive } from \"./provider/Layers/ProviderAdapterRegistry.ts\";\nimport * as ProviderEventLoggers from \"./provider/Layers/ProviderEventLoggers.ts\";\nimport { ProviderServiceLive } from \"./provider/Layers/ProviderService.ts\";\nimport { ProviderSessionReaperLive } from \"./provider/Layers/ProviderSessionReaper.ts\";\nimport * as TextGeneration from \"./textGeneration/TextGeneration.ts\";\nimport { ProviderInstanceRegistryHydrationLive } from \"./provider/Layers/ProviderInstanceRegistryHydration.ts\";\nimport * as ProcessRunner from \"./processRunner.ts\";\nimport * as Keybindings from \"./keybindings.ts\";\nimport * as ServerRuntimeStartup from \"./serverRuntimeStartup.ts\";\nimport { OrchestrationReactorLive } from \"./orchestration/Layers/OrchestrationReactor.ts\";\nimport { RuntimeReceiptBusLive } from \"./orchestration/Layers/RuntimeReceiptBus.ts\";\nimport { ProviderRuntimeIngestionLive } from \"./orchestration/Layers/ProviderRuntimeIngestion.ts\";\nimport { ProviderCommandReactorLive } from \"./orchestration/Layers/ProviderCommandReactor.ts\";\nimport { ThreadDeletionReactorLive } from \"./orchestration/Layers/ThreadDeletionReactor.ts\";\nimport { ProviderRegistryLive } from \"./provider/Layers/ProviderRegistry.ts\";\nimport * as ServerSettings from \"./serverSettings.ts\";\nimport * as ProjectFaviconResolver from \"./project/ProjectFaviconResolver.ts\";\nimport * as T3ProjectFileLoader from \"./project/T3ProjectFileLoader.ts\";\nimport * as RepositoryIdentityResolver from \"./project/RepositoryIdentityResolver.ts\";\nimport * as WorkspaceEntries from \"./workspace/WorkspaceEntries.ts\";\nimport * as WorkspaceFileSystem from \"./workspace/WorkspaceFileSystem.ts\";\nimport * as WorkspacePaths from \"./workspace/WorkspacePaths.ts\";\nimport * as GitWorkspace from \"./workspace/GitWorkspace.ts\";\nimport * as TerminalManager from \"./terminal/Manager.ts\";\nimport * as NodePtyAdapter from \"./terminal/NodePtyAdapter.ts\";\nimport { ObservabilityLive } from \"./observability/Layers/Observability.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport { authHttpApiLayer, environmentAuthenticatedAuthLayer } from \"./auth/http.ts\";\nimport { connectHttpApiLayer } from \"./connectHttpStub.ts\";\nimport * as ServerSecretStore from \"./auth/ServerSecretStore.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport { OrchestrationLayerLive } from \"./orchestration/runtimeLayer.ts\";\nimport {\n  clearPersistedServerRuntimeState,\n  makePersistedServerRuntimeState,\n  persistServerRuntimeState,\n} from \"./serverRuntimeState.ts\";\nimport { orchestrationHttpApiLayer } from \"./orchestration/http.ts\";\nimport * as NetService from \"@t3tools/shared/Net\";\nimport { disableTailscaleServe, ensureTailscaleServe } from \"@t3tools/tailscale\";\nimport { ServerActivation } from \"./serverActivation.ts\";\n\n// Effect's default preemptive shutdown waits 20s before finalizing request scopes.\n// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer\n// already closes the websocket gracefully. Do not add an artificial drain before\n// those finalizers get a chance to run.\nconst HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;\nconst ApplicationObservabilityLive = ObservabilityLive.pipe(\n  Layer.provideMerge(ResourceAttribution.layer),\n);\n\nconst ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));\n\nconst DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(\n  Layer.provideMerge(ServerSettingsLayerLive),\n);\n\nconst HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(\n  Layer.provide(DesktopTelemetryReceiverLayerLive),\n);\n\nconst BackgroundLayerLive = BackgroundPolicy.layer.pipe(\n  Layer.provide(HostPowerMonitorLayerLive),\n  Layer.provideMerge(ServerSettingsLayerLive),\n);\n\nconst HttpServerLive = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    if (typeof Bun !== \"undefined\") {\n      const BunHttpServer = yield* Effect.promise(\n        () => import(\"@effect/platform-bun/BunHttpServer\"),\n      );\n      return BunHttpServer.layer({\n        port: config.port,\n        hostname: config.host ?? \"127.0.0.1\",\n        gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,\n        websocket: {\n          // Negotiate permessage-deflate with clients that offer it; clients\n          // that don't still get uncompressed frames on their connection. A\n          // dedicated compressor keeps a per-connection sliding window\n          // (context takeover) so the compression dictionary is shared across\n          // server-to-client frames. Decompression uses the shared\n          // decompressor: uWebSockets' dedicated decompressor path can abort\n          // connections (close 1006) on valid DEFLATE input — see\n          // https://github.com/uNetworking/uWebSockets.js/issues/633.\n          perMessageDeflate: {\n            compress: \"dedicated\",\n            decompress: \"shared\",\n          },\n        },\n      });\n    } else {\n      const [NodeHttpServer, NodeHttp] = yield* Effect.all([\n        Effect.promise(() => import(\"@effect/platform-node/NodeHttpServer\")),\n        Effect.promise(() => import(\"node:http\")),\n      ]);\n      return NodeHttpServer.layer(NodeHttp.createServer, {\n        host: config.host ?? \"127.0.0.1\",\n        port: config.port,\n        gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,\n        // Negotiate permessage-deflate with clients that offer it; clients\n        // that don't still get uncompressed frames on their connection.\n        // Context takeover stays enabled (ws default) so the compression\n        // window is shared across frames — that also makes small frames cheap\n        // to compress, so no size threshold is set (ws only honors\n        // `threshold` when context takeover is disabled).\n        websocket: { perMessageDeflate: true },\n      });\n    }\n  }),\n);\n\nconst PlatformServicesLive = Layer.unwrap(\n  Effect.gen(function* () {\n    if (typeof Bun !== \"undefined\") {\n      const { layer } = yield* Effect.promise(() => import(\"@effect/platform-bun/BunServices\"));\n      return layer;\n    } else {\n      const { layer } = yield* Effect.promise(() => import(\"@effect/platform-node/NodeServices\"));\n      return layer;\n    }\n  }),\n);\n\nconst ReactorLayerLive = Layer.empty.pipe(\n  Layer.provideMerge(OrchestrationReactorLive),\n  Layer.provideMerge(ProviderRuntimeIngestionLive),\n  Layer.provideMerge(ProviderCommandReactorLive),\n  Layer.provideMerge(ThreadDeletionReactorLive),\n  Layer.provideMerge(RuntimeReceiptBusLive),\n);\n\nconst ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(\n  Layer.provide(ProviderSessionRuntime.layer),\n);\n\n// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter\n// by looking up the default `ProviderInstance` per driver in the instance\n// registry. Adapter construction itself moved inside each driver's\n// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical\n// NDJSON writers and is provided at the outer runtime layer so both\n// `ProviderService` and the per-instance drivers read the same logger pair.\nconst ProviderLayerLive = ProviderServiceLive.pipe(\n  Layer.provideMerge(ProviderAdapterRegistryLive),\n  Layer.provideMerge(ProviderSessionDirectoryLayerLive),\n);\n\nconst PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));\n\nconst WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));\n\nconst WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(\n  Layer.provide(WorkspacePaths.layer),\n  Layer.provide(WorkspaceEntriesLayerLive),\n);\n\nconst WorkspaceLayerLive = Layer.mergeAll(\n  WorkspacePaths.layer,\n  WorkspaceEntriesLayerLive,\n  WorkspaceFileSystemLayerLive,\n);\n\nconst TerminalLayerLive = TerminalManager.layer.pipe(Layer.provide(NodePtyAdapter.layer));\n\nconst ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(\n  Layer.provide(WorkspacePaths.layer),\n  Layer.provide(T3ProjectFileLoader.layer),\n);\n\nconst AuthLayerLive = EnvironmentAuth.layer.pipe(\n  Layer.provideMerge(PersistenceLayerLive),\n  Layer.provide(ServerSecretStore.layer),\n);\n\nconst ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(\n  Layer.provideMerge(ProviderLayerLive),\n  Layer.provideMerge(OrchestrationLayerLive),\n);\n\nconst RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(\n  // Core Services\n  Layer.provideMerge(ServerSettingsLayerLive),\n  Layer.provideMerge(ProviderRuntimeLayerLive),\n  Layer.provideMerge(PersistenceLayerLive),\n  Layer.provideMerge(Keybindings.layer),\n  Layer.provideMerge(TextGeneration.layer),\n  Layer.provideMerge(ProviderRegistryLive),\n  // The instance registry is the new routing keystone — text generation,\n  // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`\n  // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;\n  // `providerInstances` hydration merges `settings.providers.<kind>`\n  // with explicit `providerInstances` entries on boot.\n  Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n  // Shared native/canonical NDJSON writers used by both the per-instance\n  // drivers (native stream, written from inside each `<X>Adapter`) and\n  // `ProviderService` (canonical stream, written after event normalization).\n  // Provided once at the runtime level so every consumer sees the same\n  // logger instances.\n  Layer.provideMerge(ProviderEventLoggers.layer),\n  Layer.provideMerge(WorkspaceLayerLive),\n  Layer.provideMerge(GitWorkspace.layer),\n  Layer.provideMerge(TerminalLayerLive),\n  Layer.provideMerge(ProjectFaviconResolverLayerLive),\n  Layer.provideMerge(RepositoryIdentityResolver.layer),\n  Layer.provideMerge(ServerEnvironment.layer),\n  Layer.provideMerge(AuthLayerLive),\n  Layer.provideMerge(ServerSecretStore.layer),\n);\n\nconst RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(\n  // Misc.\n  Layer.provideMerge(BackgroundLayerLive),\n  Layer.provideMerge(AnalyticsService.layer),\n  Layer.provideMerge(ExternalLauncher.layer),\n  Layer.provideMerge(ServerLifecycleEvents.layer),\n  Layer.provide(NetService.layer),\n);\n\nconst commandReadinessLayer = HttpRouter.middleware(\n  (httpEffect) =>\n    Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>\n      startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),\n    ),\n  { global: true },\n);\n\nexport const makeRoutesLayer = Layer.mergeAll(\n  HttpApiBuilder.layer(EnvironmentHttpApi).pipe(\n    Layer.provide(authHttpApiLayer),\n    Layer.provide(connectHttpApiLayer),\n    Layer.provide(orchestrationHttpApiLayer),\n    Layer.provide(serverEnvironmentHttpApiLayer),\n    Layer.provide(environmentAuthenticatedAuthLayer),\n  ),\n  otlpTracesProxyRouteLayer,\n  assetRouteLayer,\n  staticAndDevRouteLayer,\n  websocketRpcRouteLayer,\n).pipe(\n  Layer.provide(commandReadinessLayer),\n  Layer.provide(browserApiCorsLayer),\n  Layer.provide(httpCompressionLayer),\n);\n\nexport const makeServerLayer = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    const activation = yield* Deferred.make<void>();\n    const awaitActivation = Deferred.await(activation);\n    const activationLayer = Layer.succeed(ServerActivation, awaitActivation);\n    const runtimeStateParked = yield* Deferred.make<void>();\n    const tailscaleParked = yield* Deferred.make<void>();\n    const routesReady = yield* Deferred.make<void>();\n\n    yield* fixPath();\n\n    const httpListeningLayer = Layer.effectDiscard(\n      Effect.gen(function* () {\n        yield* HttpServer.HttpServer;\n        const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;\n        yield* startup.markHttpListening;\n      }),\n    );\n    const runtimeStateLayer = Layer.effectDiscard(\n      Effect.acquireRelease(\n        Effect.gen(function* () {\n          yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);\n          yield* awaitActivation;\n          const server = yield* HttpServer.HttpServer;\n          const address = server.address;\n          if (typeof address === \"string\" || !(\"port\" in address)) {\n            return;\n          }\n\n          const state = yield* makePersistedServerRuntimeState({\n            config,\n            port: address.port,\n          });\n          yield* persistServerRuntimeState({\n            path: config.serverRuntimeStatePath,\n            state,\n          }).pipe(\n            Effect.catchCause((cause) =>\n              Effect.logWarning(\"Failed to persist server runtime state\", { cause }),\n            ),\n          );\n        }),\n        () =>\n          clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(\n            Effect.catchCause((cause) =>\n              Effect.logWarning(\"Failed to clear server runtime state\", { cause }),\n            ),\n          ),\n      ),\n    );\n    const tailscaleServeLayer = config.tailscaleServeEnabled\n      ? Layer.effectDiscard(\n          Effect.acquireRelease(\n            Effect.gen(function* () {\n              yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);\n              yield* awaitActivation;\n              const server = yield* HttpServer.HttpServer;\n              const address = server.address;\n              if (typeof address === \"string\" || !(\"port\" in address)) {\n                return null;\n              }\n\n              const localPort = address.port;\n              return yield* ensureTailscaleServe({\n                localPort,\n                servePort: config.tailscaleServePort,\n                localHost: \"127.0.0.1\",\n              }).pipe(\n                Effect.as({ localPort, servePort: config.tailscaleServePort }),\n                Effect.tap(() =>\n                  Effect.logInfo(\"Tailscale Serve configured\", {\n                    localPort,\n                    servePort: config.tailscaleServePort,\n                  }),\n                ),\n                Effect.catch((cause) =>\n                  Effect.logWarning(\"Failed to configure Tailscale Serve\", {\n                    cause,\n                    localPort,\n                    servePort: config.tailscaleServePort,\n                  }).pipe(Effect.as(null)),\n                ),\n              );\n            }),\n            (configured) =>\n              configured\n                ? disableTailscaleServe({ servePort: configured.servePort }).pipe(\n                    Effect.tap(() =>\n                      Effect.logInfo(\"Tailscale Serve disabled\", {\n                        servePort: configured.servePort,\n                      }),\n                    ),\n                    Effect.catch((cause) =>\n                      Effect.logWarning(\"Failed to disable Tailscale Serve\", {\n                        cause,\n                        servePort: configured.servePort,\n                      }),\n                    ),\n                  )\n                : Effect.void,\n          ),\n        )\n      : Layer.empty;\n    const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({\n      activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),\n      abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),\n      awaitAuxiliaryParked: Effect.all(\n        [\n          Deferred.await(runtimeStateParked),\n          Deferred.await(routesReady),\n          ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),\n        ],\n        { concurrency: \"unbounded\" },\n      ).pipe(Effect.asVoid),\n    }).pipe(Layer.provideMerge(RuntimeDependenciesLive));\n\n    const routesLayer = HttpRouter.serve(makeRoutesLayer, {\n      disableLogger: !config.logWebSocketEvents,\n    }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));\n    // agentlink fork (步骤 6): with --hub/--machine-token/--enckey set, the\n    // daemon dials out to the hub and bridges E2EE RPC tunnels alongside the\n    // local server (which keeps listening — a LAN browser can still connect\n    // directly). Off by default.\n    const hubTunnelLayer = config.hubTunnel\n      ? Layer.mergeAll(\n          HubTunnel.layer(config.hubTunnel),\n          AgentAwarenessHub.layer(config.hubTunnel),\n        ).pipe(Layer.provideMerge(runtimeServicesLive))\n      : Layer.empty;\n    const serverApplicationLayer = Layer.mergeAll(\n      routesLayer,\n      httpListeningLayer,\n      runtimeStateLayer,\n      tailscaleServeLayer,\n      hubTunnelLayer,\n    );\n\n    return serverApplicationLayer.pipe(\n      Layer.provideMerge(runtimeServicesLive),\n      Layer.provide(activationLayer),\n      Layer.provideMerge(HttpServerLive),\n      Layer.provide(ApplicationObservabilityLive),\n      Layer.provideMerge(FetchHttpClient.layer),\n      Layer.provideMerge(PlatformServicesLive),\n    );\n  }),\n);\n\n// The CLI supplies configuration.\nexport const runServer = Layer.launch(makeServerLayer);\n","import * as Effect from \"effect/Effect\";\nimport { Command, GlobalFlag } from \"effect/unstable/cli\";\n\nimport { ServerConfig, type StartupPresentation } from \"../config.ts\";\nimport { acquireDaemonLock } from \"../daemonLock.ts\";\nimport { runServer } from \"../server.ts\";\nimport { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from \"./config.ts\";\n\nexport const runServerCommand = (\n  flags: CliServerFlags,\n  options?: {\n    readonly startupPresentation?: StartupPresentation;\n    readonly forceAutoBootstrapProjectFromCwd?: boolean;\n  },\n) =>\n  Effect.gen(function* () {\n    const logLevel = yield* GlobalFlag.LogLevel;\n    const config = yield* resolveServerConfig(flags, logLevel, options);\n    const releaseDaemonLock = yield* Effect.try({\n      try: () => acquireDaemonLock(config.stateDir),\n      catch: (error) => (error instanceof Error ? error : new Error(String(error))),\n    });\n    return yield* runServer.pipe(\n      Effect.provideService(ServerConfig, config),\n      Effect.ensuring(Effect.sync(releaseDaemonLock)),\n    );\n  });\n\nexport const startCommand = Command.make(\"start\", { ...sharedServerCommandFlags }).pipe(\n  Command.withDescription(\"Run the T3 Code server.\"),\n  Command.withHandler((flags) => runServerCommand(flags)),\n);\n\nexport const serveCommand = Command.make(\"serve\", { ...sharedServerCommandFlags }).pipe(\n  Command.withDescription(\"Run the T3 Code server without opening a browser.\"),\n  Command.withHandler((flags) =>\n    runServerCommand(flags, {\n      startupPresentation: \"headless\",\n      forceAutoBootstrapProjectFromCwd: false,\n    }),\n  ),\n);\n","import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { Command } from \"effect/unstable/cli\";\nimport { fileURLToPath } from \"node:url\";\n\nimport * as NetService from \"@t3tools/shared/Net\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { authCommand } from \"./cli/auth.ts\";\nimport { pairCommand } from \"./cli/pair.ts\";\nimport { sharedServerCommandFlags } from \"./cli/config.ts\";\nimport { projectCommand } from \"./cli/project.ts\";\nimport { runServerCommand, serveCommand, startCommand } from \"./cli/server.ts\";\n\nconst CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);\n\nexport const makeCli = () =>\n  Command.make(\"t3\", { ...sharedServerCommandFlags }).pipe(\n    Command.withDescription(\"Run the T3 Code server.\"),\n    Command.withHandler((flags) => runServerCommand(flags)),\n    Command.withSubcommands([startCommand, serveCommand, pairCommand, authCommand, projectCommand]),\n  );\n\nexport const cli = makeCli();\n\nif (fileURLToPath(import.meta.url) === process.argv[1]) {\n  const main = Command.run(cli, { version: packageJson.version }).pipe(\n    Effect.scoped,\n    Effect.provide(CliRuntimeLayer),\n  );\n  NodeRuntime.runMain(main as Effect.Effect<void, unknown, never>);\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,36,39,40,41,42,43,44,45,46,47,48,51,52,58,59,60,61,62,63,64,65,86,87,88,94,101,102,103,104,105,106,107,108,109,110,111,112,117,176,177,241,243,249,250,251,252,253,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283],"mappings":";;;;;;;;;;;;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